output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def humanized_model_to_dict(instance, readonly_fields, fields=None, exclude=None):
"""
Returns a dict containing the humanized data in ``instance`` suitable for passing as
a Form's ``initial`` keyword argument.
``fields`` is an optional list of field names. If provided, only the named
fields will b... | Write a Python 3 script to
return a dict containing the humanized data in the given instance. | As a Python code composer, you craft elegant and concise scripts. |
def find_info(name=None):
"""Find the needed city server information."""
if not name:
return list(servers.keys())
name = name.lower()
if name in servers:
info = servers[name]
else:
raise CityNotFound("Could not find the specified city: %s" % name)
return info | Can you implement a function in Python 3 that
finds the needed city server information. | You are a Python code generator, capable of creating scripts from specifications. |
def which(
exe=None, default_paths=['/bin', '/sbin', '/usr/bin', '/usr/sbin', '/usr/local/bin']
):
"""Return path of bin. Python clone of /usr/bin/which.
from salt.util - https://www.github.com/saltstack/salt - license apache
:param exe: Application to search PATHs for.
:type exe: str
:param d... | Can you write a function in Python 3 where it
returns path of bin which returns None if no executable found | You are a Python code analyst, evaluating scripts for potential improvements. |
Runs a command in a shell and returns the combined contents of stdout and stderr. | Explain what the following Python 3 code does
def run(
cmd,
shell=False,
cwd=None,
log_in_real_time=True,
check_returncode=True,
callback=None,
):
""" Run 'cmd' in a shell and return the combined contents of stdout and
stderr (Blocking). Throws an exception if the command exits non-zero... | You are a Python code architect, reviewing and designing scalable and efficient code |
def process(self, msg, kwargs):
"""Add additional context information for loggers."""
prefixed_dict = {}
prefixed_dict['repo_vcs'] = self.bin_name
prefixed_dict['repo_name'] = self.name
kwargs["extra"] = prefixed_dict
return msg, kwargs | How would you code a function in Python 3 to
add additional context information for loggers. | As a python code expert, you are capable of creating scripts from specifications. |
Removes the given sexp from the list of terms. | Can you tell what is the following Python 3 function doing
def pop(self, sexp):
'''
Notes: Sequence works a bit different than other nodes.
This method (like others) expectes a list. However, sequence matches
against the list, whereas other nodes try to match against elements
of ... | You are a Python code generator, capable of creating scripts from specifications. |
Clone again, somewhere else | Can you generate a brief explanation for the following Python 3 code
def re_clone(self, repo_dir):
self.git('clone', self.remote_url, repo_dir)
return GitRepo(repo_dir) | As a python code expert, you are capable of creating scripts from specifications. |
Iterate over all parent nodes and one - self. | Can you generate a brief explanation for the following Python 3 code
def path(self):
yield self
if not self.parent: return
for node in self.parent.path: yield node | As a Python code analyst, you investigate and solve complex coding mysteries |
Iterate over all nodes of the tree excluding one self and one s children. | Explain what the following Python 3 code does
def others(self):
if not self.parent: return
yield self.parent
for sibling in self.parent.children.values():
if sibling.name == self.name: continue
for node in sibling: yield node
for node in self.parent.others: yield ... | You are a Python code generator, capable of creating scripts from specifications. |
Iterate over all children until a certain level and one - self. | Explain what the following Python 3 code does
def get_children(self, depth=1):
yield self
if depth == 0: return
for child in self.children.values():
for node in child.get_children(depth-1): yield node | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_level(self, level=2):
"""Get all nodes that are exactly this far away."""
if level == 1:
for child in self.children.values(): yield child
else:
for child in self.children.values():
for node in child.get_level(level-1): yield node | Write a Python 3 script to
get all nodes that are exactly this far away. | You are a Python code generator, capable of creating scripts from specifications. |
def trim(self, length):
"""Cut all branches over a certain length making new leaves at *length*."""
if length > 0:
for child in self.children.values(): child.trim(length-1)
else:
if hasattr(self, 'count'): self.count = sum(map(lambda x: x.count, self))
self.ch... | Can you write a function in Python 3 where it
cuts all branches over a certain length making new leaves at a certain length. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def mend(self, length):
"""Cut all branches from this node to its children and adopt
all nodes at certain level."""
if length == 0: raise Exception("Can't mend the root !")
if length == 1: return
self.children = OrderedDict((node.name, node) for node in self.get_level(length))
... | Can you implement a function in Python 3 that
cuts all branches from this node to its children and adopt all nodes at certain level. | You are a Python code generator, capable of creating scripts from specifications. |
def get_info(self, apply_tag=None, info_dicts=False):
"""
Get data from distroinfo instance.
:param apply_tag: apply supplied tag to info
:param info_dicts: return packages and releases as dicts
:return: parsed info metadata
"""
raw_infos = self.fetcher.fetch(*se... | Can you implement a function in Python 3 that
gets data from distroinfo instance. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Runs a Tornado create_application. | Explain what the following Python 3 code does
def run(create_application, settings=None, log_config=None):
from . import runner
app_settings = {} if settings is None else settings.copy()
debug_mode = bool(app_settings.get('debug',
int(os.environ.get('DEBUG', 0)) != 0)... | You are a Python code generator, capable of creating scripts from specifications. |
This method is used to get the URL and revision from a pip URL. | Can you tell what is the following Python 3 function doing
def get_url_and_revision_from_pip_url(cls, pip_url):
if '://' not in pip_url:
assert 'file:' not in pip_url
pip_url = pip_url.replace('git+', 'git+ssh://')
url, rev = super(GitRepo, cls).get_url_and_revision_from_pip_... | As a Python code composer, you craft elegant and concise scripts. |
def obtain(self):
"""Retrieve the repository, clone if doesn't exist."""
self.check_destination()
url = self.url
cmd = ['clone', '--progress']
if self.git_shallow:
cmd.extend(['--depth', '1'])
if self.tls_verify:
cmd.extend(['-c', 'http.sslVerify... | How would you implement a function in Python 3 that
retrieves the repository clone if doesn t exist. | You are a Python code analyst, evaluating scripts for potential improvements. |
Return remotes like git remote - v. | Explain what the following Python 3 code does
def remotes_get(self):
remotes = {}
cmd = self.run(['remote'])
ret = filter(None, cmd.split('\n'))
for remote_name in ret:
remotes[remote_name] = self.remote_get(remote_name)
return remotes | You are a Python code analyst, evaluating scripts for potential improvements. |
def remote_get(self, remote='origin'):
"""Get the fetch and push URL for a specified remote name.
:param remote: the remote name used to define the fetch and push URL
:type remote: str
:returns: remote name and url in tuple form
:rtype: tuple
"""
try:
... | Implement a function in Python 3 to
get the fetch and push URL for a specified remote name. | As a python code expert, you are capable of creating scripts from specifications. |
Set remote with name and URL like git remote add. | Can you generate a brief explanation for the following Python 3 code
def remote_set(self, url, name='origin'):
url = self.chomp_protocol(url)
if self.remote_get(name):
self.run(['remote', 'rm', 'name'])
self.run(['remote', 'add', name, url])
return self.remote_get(remote=n... | As a python code expert, you are capable of creating scripts from specifications. |
def chomp_protocol(url):
"""Return clean VCS url from RFC-style url
:param url: url
:type url: str
:rtype: str
:returns: url as VCS software would accept it
:seealso: #14
"""
if '+' in url:
url = url.split('+', 1)[1]
scheme, netloc, pa... | Write a Python 3 function that can
return url with VCS protocol removed | As a Python code composer, you craft elegant and concise scripts. |
def _log(self, message, stream, color=None, newline=False):
'''
Logs the message to the sys.stdout or sys.stderr stream.
When color is defined and the TERM environemnt variable contains the
string "color", then the output will be colored.
'''
if color and self.color_ter... | Write a Python 3 function that can
log the message to the sys. stdout or sys. stderr stream. | You are a Python code architect, reviewing and designing scalable and efficient code |
def info(self, message):
'''
Logs an informational message to stdout.
This method should only be used by the Runner.
'''
return self._log(
message=message.upper(),
stream=sys.stdout
) | Create a Python 3 function to
log an informational message to stdout. | You are a Python code generator, capable of creating scripts from specifications. |
Logs as whole test result as PASSED. | Can you generate a brief explanation for the following Python 3 code
def passed(self, message):
'''
Logs as whole test result as PASSED.
This method should only be used by the Runner.
'''
return self._log(
message=message.upper(),
stream=sys.stdout,
... | As a Python code composer, you craft elegant and concise scripts. |
def failed(self, message):
'''
Logs as whole test result as FAILED.
This method should only be used by the Runner.
'''
return self._log(
message=message.upper(),
stream=sys.stderr,
color=Logger.COLOR_RED_BOLD,
newline=True
... | Create a Python 3 function for
logging as whole test result as FAILED. | As a Python code analyst, you investigate and solve complex coding mysteries |
Decorator to run a function in a non - blocking way. | Can you generate the documentation for the following Python 3 function
def non_blocking(func):
from functools import wraps
@wraps(func)
def non_blocking_version(*args, **kwargs):
t = ReturnThread(target=func, args=args, kwargs=kwargs)
t.start()
return t
return non_blocking_versio... | As a python code expert, you are capable of creating scripts from specifications. |
Returns a base media URL based on the current settings. py settings. | Can you generate the documentation for the following Python 3 function
def media_url(self, with_ssl=False):
if self.serve_remote:
# Hand this off to whichever backend is being used.
url = self.remote_media_url(with_ssl)
else:
# Serving locally, just use the value in s... | As a Python code analyst, you investigate and solve complex coding mysteries |
def logs(self):
"""Find the log directory and return all the logs sorted."""
if not self.parent.loaded: self.parent.load()
logs = self.parent.p.logs_dir.flat_directories
logs.sort(key=lambda x: x.mod_time)
return logs | Can you create a Python 3 function that
finds the log directory and return all the logs sorted. | As a Python code translator, you convert algorithms and pseudocode into Python. |
A convenience method to run the same result as a SLURM job
but locally in a non - blocking way. | Here you have a function in Python 3, explain what it does
def run_locally(self, steps=None, **kwargs):
self.slurm_job = LoggedJobSLURM(self.command(steps),
base_dir = self.parent.p.logs_dir,
modules = self.modules,
... | As a Python code composer, you craft elegant and concise scripts. |
def run_slurm(self, steps=None, **kwargs):
"""Run the steps via the SLURM queue."""
# Optional extra SLURM parameters #
params = self.extra_slurm_params
params.update(kwargs)
# Mandatory extra SLURM parameters #
if 'time' not in params: params['time'] = self.d... | Implement a function in Python 3 to
run the steps via the SLURM queue. | You are a Python code analyst, evaluating scripts for potential improvements. |
def smart_generic_inlineformset_factory(model, request, form=ModelForm, formset=BaseGenericInlineFormSet,
ct_field='content_type', fk_field='object_id', fields=None, exclude=None,
extra=3, can_order=False, can_delete=True, min_num=None, max... | Write a Python 3 function that can
return a ``GenericInlineFormSet`` for the given kwargs. You must provide ``ct_field`` and ``fk_field`` if they are different from the defaults ``content_type`` and ``object_id`` respectively. | As a python code expert, you are capable of creating scripts from specifications. |
def rename(self, name):
"""Set the name of the machine."""
self.ec2.create_tags(Resources = [self.instance_id],
Tags = [{'Key': 'Name',
'Value': name}])
self.refresh_info() | How would you code a function in Python 3 to
set the name of the machine. | As a python code expert, you are capable of creating scripts from specifications. |
Update the SSH config file with the DNS. | Given the following Python 3 function, write the documentation
def update_ssh_config(self, path="~/.ssh/config"):
# Read the config file #
import sshconf
config = sshconf.read_ssh_config(os.path.expanduser(path))
# In case it doesn't exist #
if not config.host(self.instance_name)... | As a Python code composer, you craft elegant and concise scripts. |
def _update_widget_choices(self, widget):
"""
Updates widget choices with special choice iterator that removes blank values and adds none value to clear
filter data.
:param widget: widget with choices
:return: updated widget with filter choices
"""
widget.choices... | Can you implement a function in Python 3 that
updates widget. choices with special choice iterator that removes blank values and adds none values to clear filter data. | As a python code expert, you are capable of creating scripts from specifications. |
Returns the widget to use for this field. | Given the following Python 3 function, write the documentation
def get_widget(self, request):
return self._update_widget_choices(self.field.formfield(widget=RestrictedSelectWidget).widget) | You are a Python code generator, capable of creating scripts from specifications. |
Returns the widget for this field based on the current request. | Can you tell what is the following Python 3 function doing
def get_widget(self, request):
return self._update_widget_choices(
forms.ModelChoiceField(
widget=RestrictedSelectWidget, queryset=self.field.related_model._default_manager.all()
).widget
) | As a Python code analyst, you investigate and solve complex coding mysteries |
def strip_project_url(url):
"""strip proto:// | openstack/ prefixes and .git | -distgit suffixes"""
m = re.match(r'(?:[^:]+://)?(.*)', url)
if m:
url = m.group(1)
if url.endswith('.git'):
url, _, _ = url.rpartition('.')
if url.endswith('-distgit'):
url, _, _ = url.rpartition(... | Can you create a Python 3 function that
strips proto:// | openstack/ prefixes and .git | -distgit suffixes | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_rev_options(url, rev):
"""Return revision options.
from pip pip.vcs.subversion.
"""
if rev:
rev_options = ['-r', rev]
else:
rev_options = []
r = urlparse.urlsplit(url)
if hasattr(r, 'username'):
# >= Python-2.5
username, password = r.username, r.pas... | How would you code a function in Python 3 to
return revision options. from pip pip. vcs. subversion. | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_revision_file(self, location):
"""Return revision for a file."""
current_rev = self.run(['info', location])
_INI_RE = re.compile(r"^([^:]+):\s+(\S.*)$", re.M)
info_list = _INI_RE.findall(current_rev)
return int(dict(info_list)['Revision']) | Create a Python 3 function to
return revision for a file. | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_publish_path(self, obj):
"""
publish_path joins the publish_paths for the chat type and the channel.
"""
return os.path.join(
obj.chat_type.publish_path, obj.publish_path.lstrip("/")
) | Write a Python 3 script to
return the publish path for the given object. | You are a Python code generator, capable of creating scripts from specifications. |
def trans_attr(attr, lang):
"""
Returns the name of the translated attribute of the object <attribute>_<lang_iso_code>.
For example: name_es (name attribute in Spanish)
@param attr Attribute whose name will form the name translated attribute.
@param lang ISO Language code that will be the suffix of the translated ... | Write a Python 3 function for
returning the name of the translated attribute of the object <attribute >_ <lang_iso_code >. | You are a Python code analyst, evaluating scripts for potential improvements. |
def _init_module_cache():
"""
Module caching, it helps with not having to import again and again same modules.
@return: boolean, True if module caching has been done, False if module caching was already done.
"""
# While there are not loaded modules, load these ones
if len(FieldTranslation._modules) < len... | Can you create a Python 3 function that
initializes the module cache. | As a python code expert, you are capable of creating scripts from specifications. |
def _load_source_model(self):
"""
Loads and gets the source model of the FieldTranslation as a dynamic attribute. It is used only when deleting
orphan translations (translations without a parent object associated).
"""
# If source_model exists, return it
if hasattr(self, "source_model"):
return self.sou... | Can you create a Python 3 function that
loads the source model of the FieldTranslation object. | As a Python code analyst, you investigate and solve complex coding mysteries |
Loads related object in a dynamic attribute and returns it. | Can you generate the documentation for the following Python 3 function
def _load_source_object(self):
if hasattr(self, "source_obj"):
self.source_text = getattr(self.source_obj, self.field)
return self.source_obj
self._load_source_model()
self.source_obj = self.source_model.objects.get(id=self.object_id)
... | As a Python code analyst, you investigate and solve complex coding mysteries |
def delete_orphan_translations(condition=None):
"""
Delete orphan translations.
This method needs refactoring to be improve its performance.
"""
if condition is None:
condition = {}
# TODO: optimize using one SQL sentence
translations = FieldTranslation.objects.all()
for translation in translations:
... | Write a Python 3 function for
deleting orphan translations. This method needs refactoring to be improve its performance. | As a Python code analyst, you investigate and solve complex coding mysteries |
def update_translations(condition=None):
"""
Updates FieldTranslations table
"""
if condition is None:
condition = {}
# Number of updated translations
num_translations = 0
# Module caching
FieldTranslation._init_module_cache()
# Current languages dict
LANGUAGES = dict(lang for lang in MODELT... | How would you code a function in Python 3 to
update the FieldTranslations table with the given condition. | As a Python code composer, you craft elegant and concise scripts. |
def save(self, *args, **kwargs):
"""
Save object in database, updating the datetimes accordingly.
"""
# Now in UTC
now_datetime = timezone.now()
# If we are in a creation, assigns creation_datetime
if not self.id:
self.creation_datetime = now_datetime
# Las update datetime is always updated
se... | Write a Python 3 script to
save the object in database updating the datetimes accordingly. | As a Python code composer, you craft elegant and concise scripts. |
Parse raw rdoinfo metadata inplace. | Here you have a function in Python 3, explain what it does
def parse_info(raw_info, apply_tag=None):
parse_releases(raw_info)
parse_packages(raw_info, apply_tag=apply_tag)
return raw_info | You are a Python code generator, capable of creating scripts from specifications. |
def info2dicts(info, in_place=False):
"""
Return info with:
1) `packages` list replaced by a 'packages' dict indexed by 'project'
2) `releases` list replaced by a 'releases' dict indexed by 'name'
"""
if 'packages' not in info and 'releases' not in info:
return info
if in_place:
... | Can you write a function in Python 3 where it
converts a dictionary of info to a list of dicts indexed by project and name. | As a python code expert, you are capable of creating scripts from specifications. |
Convert info dict to lists of dicts. | Can you generate the documentation for the following Python 3 function
def info2lists(info, in_place=False):
"""
Return info with:
1) `packages` dict replaced by a 'packages' list with indexes removed
2) `releases` dict replaced by a 'releases' list with indexes removed
info2list(info2dicts(info)... | As a python code expert, you are capable of creating scripts from specifications. |
Make an ASCII version a string.
\ w matches any alphanumeric character and the underscore. | Here you have a function in Python 3, explain what it does
def alphanumeric(text):
return "".join([c for c in text if re.match(r'\w', c)]) | You are a Python code architect, reviewing and designing scalable and efficient code |
def sanitize_text(text):
"""Make a safe representation of a string.
Note: the `\s` special character matches any whitespace character.
This is equivalent to the set [\t\n\r\f\v] as well as ` ` (whitespace)."""
# First replace characters that have specific effects with their repr #
text = re.sub("(\s... | Implement a function in Python 3 to
make a safe representation of a string. | You are a Python code generator, capable of creating scripts from specifications. |
Converts a string from CamelCaseStrings to snake_case_strings. | How would you explain what the following Python 3 function does
def camel_to_snake(text):
step_one = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', text)
step_two = re.sub('([a-z0-9])([A-Z])', r'\1_\2', step_one)
return step_two.lower() | As a Python code analyst, you investigate and solve complex coding mysteries |
def bool_to_unicode(b):
"""Different possibilities for True: ☑️✔︎✓✅👍✔️
Different possibilities for False: ✕✖︎✗✘✖️❌⛔️❎👎🛑🔴"""
b = bool(b)
if b is True: return u"✅"
if b is False: return u"❎" | Write a Python 3 function that can
convert a boolean to a unicode string. | You are a Python code generator, capable of creating scripts from specifications. |
def access_dict_like_obj(obj, prop, new_value=None):
"""
Access a dictionary like if it was an object with properties.
If no "new_value", then it's a getter, otherwise it's a setter.
>>> {'characters': {'cast': 'Jean-Luc Picard', 'featuring': 'Deanna Troi'}}
>>> access_dict_like_obj(startrek, 'chara... | Implement a Python 3 function for
accessing a dictionary like if it was an object with properties. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def all_combinations(items):
"""Generate all combinations of a given list of items."""
return (set(compress(items,mask)) for mask in product(*[[0,1]]*len(items))) | Can you create a Python 3 function that
generates all combinations of a given list of items. | As a python code expert, you are capable of creating scripts from specifications. |
def pad_equal_whitespace(string, pad=None):
"""Given a multiline string, add whitespaces to every line
so that every line has the same length."""
if pad is None: pad = max(map(len, string.split('\n'))) + 1
return '\n'.join(('{0: <%i}' % pad).format(line) for line in string.split('\n')) | Implement a Python 3 function for
giving a multiline string add whitespaces to every line of the multiline string so that every line has the same length. | You are a Python code analyst, evaluating scripts for potential improvements. |
def concatenate_by_line(first, second):
"""Zip two strings together, line wise"""
return '\n'.join(x+y for x,y in zip(first.split('\n'), second.split('\n'))) | Create a Python 3 function for
zipping two strings together line wise | You are a Python code architect, reviewing and designing scalable and efficient code |
Group a list of strings by pairs by matching those with only
one character difference between each other together. | Can you tell what is the following Python 3 function doing
def sort_string_by_pairs(strings):
assert len(strings) % 2 == 0
pairs = []
strings = list(strings) # This shallow copies the list
while strings:
template = strings.pop()
for i, candidate in enumerate(strings):
if coun... | As a Python code composer, you craft elegant and concise scripts. |
def count_string_diff(a,b):
"""Return the number of characters in two strings that don't exactly match"""
shortest = min(len(a), len(b))
return sum(a[i] != b[i] for i in range(shortest)) | Can you create a Python 3 function that
returns the number of characters in two strings that don t exactly match | As a Python code analyst, you investigate and solve complex coding mysteries |
Same order unique list using only a list compression. | Can you tell what is the following Python 3 function doing
def uniquify_list(L):
return [e for i, e in enumerate(L) if L.index(e) == i] | You are a Python code analyst, evaluating scripts for potential improvements. |
Gets the next item of an iterable. | Here you have a function in Python 3, explain what it does
def get_next_item(iterable):
try: x = iterable.next()
except StopIteration: x = None
except AttributeError: x = None
return x | You are a Python code generator, capable of creating scripts from specifications. |
Returns some thing like 2011 - 02 - 15 - 58 CET + 0100 | Explain what the following Python 3 code does
def pretty_now():
import datetime, tzlocal
time_zone = tzlocal.get_localzone()
now = datetime.datetime.now(time_zone)
return now.strftime("%Y-%m-%d %H:%M:%S %Z%z") | As a Python code analyst, you investigate and solve complex coding mysteries |
Given a list of strings will join them with commas and a final and word. | Make a summary of the following Python 3 code
def andify(list_of_strings):
result = ', '.join(list_of_strings)
comma_index = result.rfind(',')
if comma_index > -1: result = result[:comma_index] + ' and' + result[comma_index+1:]
return result | As a Python code composer, you craft elegant and concise scripts. |
def num_to_ith(num):
"""1 becomes 1st, 2 becomes 2nd, etc."""
value = str(num)
before_last_digit = value[-2]
last_digit = value[-1]
if len(value) > 1 and before_last_digit == '1': return value +'th'
if last_digit == '1': return value + 'st'
if last_digit == '2': return val... | Can you write a function in Python 3 where it
converts a number to the th th. | You are a Python code analyst, evaluating scripts for potential improvements. |
def isubsample(full_sample, k, full_sample_len=None):
"""Down-sample an enumerable list of things"""
# Determine length #
if not full_sample_len: full_sample_len = len(full_sample)
# Check size coherence #
if not 0 <= k <= full_sample_len:
raise ValueError('Required that 0 <= k <= full_sampl... | How would you code a function in Python 3 to
down - sample an enumerable list of things | You are a Python code generator, capable of creating scripts from specifications. |
Wait until the predicate turns true and display a turning ball. | Here you have a function in Python 3, explain what it does
def wait(predicate, interval=1, message=lambda: "Waiting..."):
ball, next_ball = u"|/-\\", "|"
sys.stdout.write(" \033[K")
sys.stdout.flush()
while not predicate():
time.sleep(1)
next_ball = ball[(ball.index(next_ball) + 1) % ... | You are a Python code generator, capable of creating scripts from specifications. |
def natural_sort(item):
"""
Sort strings that contain numbers correctly. Works in Python 2 and 3.
>>> l = ['v1.3.12', 'v1.3.3', 'v1.2.5', 'v1.2.15', 'v1.2.3', 'v1.2.1']
>>> l.sort(key=natural_sort)
>>> l.__repr__()
"['v1.2.1', 'v1.2.3', 'v1.2.5', 'v1.2.15', 'v1.3.3', 'v1.3.12']"
"""
dre... | Write a Python 3 script to
sort strings that contain numbers correctly. Works in Python 2 and 3. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Splits a number on thousands. | Can you generate the documentation for the following Python 3 function
def split_thousands(s):
# Check input #
if s is None: return "0"
# If it's a string #
if isinstance(s, basestring): s = float(s)
# If it's a float that should be an int #
if isinstance(s, float) and s.is_integer(): s = int(s)... | You are a Python code analyst, evaluating scripts for potential improvements. |
Reverse a SeqIO sequence but keep its name intact. | Explain what the following Python 3 code does
def reverse_compl_with_name(old_seq):
new_seq = old_seq.reverse_complement()
new_seq.id = old_seq.id
new_seq.description = old_seq.description
return new_seq | As a Python code translator, you convert algorithms and pseudocode into Python. |
Load a file with the json module and return a dict. | Here you have a function in Python 3, explain what it does
def load_json_path(path):
with open(path) as handle:
try: return json.load(handle, object_pairs_hook=collections.OrderedDict)
except ValueError as error:
message = "Could not decode JSON file '%s'." % path
message = "... | You are a Python code analyst, evaluating scripts for potential improvements. |
def md5sum(file_path, blocksize=65536):
"""Compute the md5 of a file. Pretty fast."""
md5 = hashlib.md5()
with open(file_path, "rb") as f:
for block in iter(lambda: f.read(blocksize), ""):
md5.update(block)
return md5.hexdigest() | Write a Python 3 script to
compute the md5 of a file. Pretty fast. | You are a Python code analyst, evaluating scripts for potential improvements. |
Download a file from an URL and place it somewhere. | Make a summary of the following Python 3 code
def download_from_url(source, destination, progress=False, uncompress=False):
# Modules #
from tqdm import tqdm
import requests
from autopaths.file_path import FilePath
# Check destination exists #
destination = FilePath(destination)
destination.... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Generate the lines of file in reverse order. | Explain what the following Python 3 code does
def reversed_lines(path):
with open(path, 'r') as handle:
part = ''
for block in reversed_blocks(handle):
for c in reversed(block):
if c == '\n' and part:
yield part[::-1]
part = ''
... | As a Python code composer, you craft elegant and concise scripts. |
Generate blocks of file s contents in reverse order. | How would you explain what the following Python 3 function does
def reversed_blocks(handle, blocksize=4096):
handle.seek(0, os.SEEK_END)
here = handle.tell()
while 0 < here:
delta = min(blocksize, here)
here -= delta
handle.seek(here, os.SEEK_SET)
yield handle.read(delta) | As a python code expert, you are capable of creating scripts from specifications. |
Find the command path. | Can you tell what is the following Python 3 function doing
def which(cmd, safe=False):
from autopaths.file_path import FilePath
def is_executable(path):
return os.path.exists(path) and os.access(path, os.X_OK) and not os.path.isdir(path)
path, name = os.path.split(cmd)
if path:
if is_exe... | As a Python code composer, you craft elegant and concise scripts. |
def css_tag(parser, token):
"""
Renders a tag to include the stylesheet. It takes an optional second
parameter for the media attribute; the default media is "screen, projector".
Usage::
{% css "<somefile>.css" ["<projection type(s)>"] %}
Examples::
{% css "myfile.css" %}
... | Implement a function in Python 3 to
return a tag that includes the stylesheet. | You are a Python code analyst, evaluating scripts for potential improvements. |
Shortcut to render CSS as a print stylesheet. | Can you generate the documentation for the following Python 3 function
def css_print_tag(parser, token):
path = get_path_from_tokens(token)
# Hard wired media type, since this is for media type of 'print'.
media_type = "print"
return CssTagNode(path, media_type=media_type) | As a python code expert, you are capable of creating scripts from specifications. |
Returns True if the client supports gzip encoded content. | Explain what the following Python 3 code does
def supports_gzip(self, context):
if 'request' in context and client.supports_gzip():
enc = context['request'].META.get('HTTP_ACCEPT_ENCODING', '')
return 'gzip' in enc and msettings['SERVE_REMOTE']
return False | You are a Python code generator, capable of creating scripts from specifications. |
def get_media_url(self, context):
"""
Checks to see whether to use the normal or the secure media source,
depending on whether the current page view is being sent over SSL.
The USE_SSL setting can be used to force HTTPS (True) or HTTP (False).
NOTE: Not all backends impl... | Create a Python 3 function to
return the URL of the current media source for the given context. | As a Python code analyst, you investigate and solve complex coding mysteries |
def mkpath(self, url, path, filename=None, gzip=False):
"""
Assembles various components to form a complete resource URL.
args:
url: (str) A base media URL.
path: (str) The path on the host (specified in 'url') leading up
to the file.
... | Create a Python 3 function to
assemble various components to form a complete resource URL. | You are a Python code generator, capable of creating scripts from specifications. |
Renders a link tag for the stylesheet. | Can you tell what is the following Python 3 function doing
def linktag(self, url, path, filename, media, context):
if msettings['DOCTYPE'] == 'xhtml':
markup = """<link rel="stylesheet" href="%s" type="text/css" media="%s" />"""
elif msettings['DOCTYPE'] == 'html5':
markup = """<... | You are a Python code analyst, evaluating scripts for potential improvements. |
def scripttag(self, url, path, filename, context):
"""
Renders a <script> tag for the JS file(s).
"""
if msettings['DOCTYPE'] == 'html5':
markup = """<script src="%s"></script>"""
else:
markup = """<script type="text/javascript" charset="utf-8" src="%s"></... | Implement a Python 3 function for
rendering a script tag for the JS file. | You are a Python code analyst, evaluating scripts for potential improvements. |
Wrap a tornado application in a callback - aware wrapper. | Make a summary of the following Python 3 code
def wrap_application(application, before_run, on_start, shutdown):
before_run = [] if before_run is None else before_run
on_start = [] if on_start is None else on_start
shutdown = [] if shutdown is None else shutdown
if not isinstance(application, Applicat... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Run the ``before_run`` callbacks and queue to ``on_start`` callbacks.
:param tornado.ioloop.IOLoop io_loop: loop to start the app on. | Here you have a function in Python 3, explain what it does
def start(self, io_loop):
for callback in self.before_run_callbacks:
try:
callback(self.tornado_application, io_loop)
except Exception:
self.logger.error('before_run callback %r cancelled start',
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Asynchronously stop the application. | Can you generate a brief explanation for the following Python 3 code
def stop(self, io_loop):
running_async = False
shutdown = _ShutdownHandler(io_loop)
for callback in self.on_shutdown_callbacks:
try:
maybe_future = callback(self.tornado_application)
... | You are a Python code generator, capable of creating scripts from specifications. |
Combine a list of sourcefiles into a single
monolithic file. | Explain what the following Python 3 code does
def combine_files(joinfile, sourcefiles, client):
from mediasync.conf import msettings
joinfile = joinfile.strip('/')
if joinfile.endswith('.css'):
dirname = msettings['CSS_PATH'].strip('/')
separator = '\n'
elif joinfile.endswith('.js'):
... | As a Python code composer, you craft elegant and concise scripts. |
Enable all offline cpus | Here you have a function in Python 3, explain what it does
def enable_all_cpu(self):
'''
Enable all offline cpus
'''
for cpu in self.__get_ranges("offline"):
fpath = path.join("cpu%i"%cpu,"online")
self.__write_cpu_file(fpath, b"1") | You are a Python code analyst, evaluating scripts for potential improvements. |
def reset(self, rg=None):
'''
Enable all offline cpus, and reset max and min frequencies files
rg: range or list of threads to reset
'''
if type(rg) == int:
rg= [rg]
to_reset= rg if rg else self.__get_ranges("present")
self.enable_cpu(to_reset)
... | Write a Python 3 script to
enable all offline cpus and reset max and min frequencies files | As a python code expert, you are capable of creating scripts from specifications. |
Disable all threads attached to the same core | Explain what the following Python 3 code does
def disable_hyperthread(self):
'''
Disable all threads attached to the same core
'''
to_disable = []
online_cpus = self.__get_ranges("online")
for cpu in online_cpus:
fpath = path.join("cpu%i"%cpu,"topology","threa... | As a python code expert, you are capable of creating scripts from specifications. |
def disable_cpu(self, rg):
'''
Disable cpus
rg: range or list of threads to disable
'''
if type(rg) == int:
rg= [rg]
to_disable= set(rg) & set(self.__get_ranges("online"))
for cpu in to_disable:
fpath = path.join("cpu%i"%cpu,"online")
... | How would you implement a function in Python 3 that
disables the CPU for the specified threads. | As a python code expert, you are capable of creating scripts from specifications. |
def enable_cpu(self, rg):
'''
Enable cpus
rg: range or list of threads to enable
'''
if type(rg) == int:
rg= [rg]
to_disable= set(rg) & set(self.__get_ranges("offline"))
for cpu in to_disable:
fpath = path.join("cpu%i"%cpu,"online")
... | Write a Python 3 script to
enable the CPU for the specified threads. | You are a Python code analyst, evaluating scripts for potential improvements. |
Set the frequency of the cores in the specified RAM. | Given the following Python 3 function, write the documentation
def set_frequencies(self, freq, rg=None, setMaxfeq=True, setMinfreq=True, setSpeed=True):
'''
Set cores frequencies
freq: int frequency in KHz
rg: list of range of cores
setMaxfeq: set the maximum frequency, default ... | As a python code expert, you are capable of creating scripts from specifications. |
def set_governors(self, gov, rg=None):
'''
Set governors
gov: str name of the governor
rg: list of range of cores
'''
to_change = self.__get_ranges("online")
if type(rg) == int:
rg= [rg]
if rg: to_change= set(rg) & set(self.__get_ranges("onlin... | Can you create a Python 3 function that
sets the governors of the specified set of cores and governors of the specified set of cores. | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_available_frequencies(self):
'''
Get all possible frequencies
'''
fpath = path.join("cpu0","cpufreq","scaling_available_frequencies")
data = self.__read_cpu_file(fpath).rstrip("\n").split()
return data | How would you implement a function in Python 3 that
gets all possible frequencies | You are a Python code architect, reviewing and designing scalable and efficient code |
Configure a previously initialized instance of the class. | Can you generate a brief explanation for the following Python 3 code
def configure(self, endpoint=None, **kwargs):
if endpoint:
kwargs['endpoint'] = endpoint
keywords = self._keywords.copy()
keywords.update(kwargs)
if 'endpoint' in kwargs:
# Then we need to correc... | As a python code expert, you are capable of creating scripts from specifications. |
def _configure_endpoint(self, endpoint):
"""Configure the endpoint with a schema and end slash."""
if not endpoint.startswith('http'):
endpoint = 'https://' + endpoint
if not endpoint.endswith('/'):
endpoint += '/'
return endpoint | How would you implement a function in Python 3 that
configures the endpoint with a schema and end slash. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get(self, *args, **kwargs):
"""Perform a get request."""
if 'convert' in kwargs:
conversion = kwargs.pop('convert')
else:
conversion = True
kwargs = self._get_keywords(**kwargs)
url = self._create_path(*args)
request = self.session.get(url, par... | How would you code a function in Python 3 to
perform a get request. | You are a Python code architect, reviewing and designing scalable and efficient code |
def _get_keywords(self, **kwargs):
"""Format GET request parameters and keywords."""
if self.jurisdiction and 'jurisdiction_id' not in kwargs:
kwargs['jurisdiction_id'] = self.jurisdiction
if 'count' in kwargs:
kwargs['page_size'] = kwargs.pop('count')
if 'start' ... | Create a Python 3 function for
formatting GET request parameters and keywords. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Format start and end dates. | Make a summary of the following Python 3 code
def _format_dates(self, start, end):
start = self._split_date(start)
end = self._split_date(end)
return start, end | You are a Python code analyst, evaluating scripts for potential improvements. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.