output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
Helper for Generic. __new__.
MimeType. _next_in_mro Returns the class after the last occurrence of Generic or Generic [... ] in cls.
MimeType. | How would you explain what the following Python 3 function does
def _next_in_mro(cls):
next_in_mro = object
# Look for the last occurrence of Generic or Generic[...].
for i, c in enumerate(cls.__mro__[:-1]):
if isinstance(c, GenericMeta) and _gorg(c) is Generic:
next_in_mro = cls.__mro__... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _make_subclasshook(cls):
"""Construct a __subclasshook__ callable that incorporates
the associated __extra__ class in subclass checks performed
against cls.
"""
if isinstance(cls.__extra__, abc.ABCMeta):
# The logic mirrors that of ABCMeta.__subclasscheck__.
# Registered classes ... | How would you code a function in Python 3 to
construct a __subclasshook__ callable that incorporates the associated __extra__ class in subclass checks performed against cls. | As a Python code composer, you craft elegant and concise scripts. |
def get_authorization(self, **kwargs):
"""Gets the authorization object for the view."""
if self.authorization is not None:
return self.authorization
auth_class = self.get_authorization_class()
auth_user = self.get_authorization_user()
auth_kwargs = {
'to... | How would you implement a function in Python 3 that
gets the authorization object for the view. | As a Python code composer, you craft elegant and concise scripts. |
def get_authorization_user(self, **kwargs):
"""Gets the user the authorization object is for."""
if self.authorization_user is not None:
return self.authorization_user
self.authorization_user = self.request.user
return self.request.user | Write a Python 3 function for
getting the user the authorization object is for. | As a Python code analyst, you investigate and solve complex coding mysteries |
Create a dictionary representation of object attributes. | Explain what the following Python 3 code does
def to_dict(self, dict_cls=FrozenOrderedDict):
# type: (Type[dict]) -> Dict[str, Any]
"""Create a dictionary representation of object attributes
Returns:
OrderedDict serialised version of self
"""
pairs = tuple((k, serial... | As a Python code composer, you craft elegant and concise scripts. |
def safe_redirect(next_url, default=None):
"""Makes sure it's a legit site to redirect to.
:param default: this is the default url or named url to redirect to in the
event where next_url is not legit.
"""
if is_legit_next_url(next_url):
return redirect(next_url)
if default:
... | Implement a Python 3 function for
making sure it s a legit site to redirect to. | As a Python code analyst, you investigate and solve complex coding mysteries |
Replace querystring values in a url string. | Given the following Python 3 function, write the documentation
def replace_url_query_values(url, replace_vals):
if '?' not in url:
return url
parsed_url = urlparse(url)
query = dict(parse_qsl(parsed_url.query))
query.update(replace_vals)
return '{0}?{1}'.format(url.split('?')[0], urlencode(... | As a python code expert, you are capable of creating scripts from specifications. |
Gets query string values from a url. | Given the following Python 3 function, write the documentation
def get_query_values_from_url(url, keys=None):
if not url or '?' not in url:
# no query params
return None
parsed_url = urlparse(url)
query = dict(parse_qsl(parsed_url.query))
if keys is None:
return query
if i... | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns a json response object. | Make a summary of the following Python 3 code
def get_json_response(self, content, **kwargs):
# Don't care to return a django form or view in the response here.
# Remove those from the context.
if isinstance(content, dict):
response_content = {k: deepcopy(v) for k, v in content.item... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def delete(self, request, *args, **kwargs):
"""
Calls the delete() method on the fetched object and then
redirects to the success URL.
"""
self.object = self.get_object()
success_url = self.get_success_url()
self.object.delete()
if self.request.is_ajax():... | Can you create a Python 3 function that
deletes the object and then redirects to the success URL. | You are a Python code architect, reviewing and designing scalable and efficient code |
Finds all the atomic formulas | Given the following Python 3 function, write the documentation
def find_atomics(formula: Formula) -> Set[PLAtomic]:
f = formula
res = set()
if isinstance(formula, PLFormula):
res = formula.find_atomics()
# elif isinstance(f, PLNot):
# res = res.union(find_atomics(f.f))
# elif isinsta... | As a Python code analyst, you investigate and solve complex coding mysteries |
From a Propositional Formula to a Propositional Formula
with non - propositional subformulas replaced with a freezed atomic formula. | Explain what the following Python 3 code does
def _transform_delta(f:Formula, formula2AtomicFormula):
t = type(f)
if t == PLNot:
return PLNot(_transform_delta(f, formula2AtomicFormula))
# elif isinstance(f, PLBinaryOperator): #PLAnd, PLOr, PLImplies, PLEquivalence
elif t == PLAnd or t == PLOr or... | You are a Python code generator, capable of creating scripts from specifications. |
DEPRECATED - Builds a NFA from a LDLfFormula. | Make a summary of the following Python 3 code
def to_automaton_(f, labels:Set[Symbol]=None):
nnf = f.to_nnf()
if labels is None:
# if the labels of the formula are not specified in input,
# retrieve them from the formula
labels = nnf.find_labels()
# the alphabet is the powerset of... | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_setting(key, **kwargs):
"""Gets a settings key or raises an improperly configured error.
:param key: the settings key to get.
:param default: the default value to return if no value is found
"""
has_default = 'default' in kwargs
default_val = kwargs.get('default')
try:
if h... | Implement a Python 3 function for
getting a setting from the settings file. | As a python code expert, you are capable of creating scripts from specifications. |
Gets a class from a setting key. | How would you explain what the following Python 3 function does
def get_class_from_settings(settings_key):
cls_path = getattr(settings, settings_key, None)
if not cls_path:
raise NotImplementedError()
try:
# First check to see if it's an installed model
return get_model_from_setting... | You are a Python code analyst, evaluating scripts for potential improvements. |
Return the django model from a settings key. | Can you tell what is the following Python 3 function doing
def get_model_from_settings(settings_key):
cls_path = getattr(settings, settings_key, None)
if not cls_path:
raise NotImplementedError()
try:
app_label, model_name = cls_path.split('.')
except ValueError:
raise Improperl... | As a python code expert, you are capable of creating scripts from specifications. |
def get_class_from_settings_from_apps(settings_key):
"""Try and get a class from a settings path by lookin in installed apps.
"""
cls_path = getattr(settings, settings_key, None)
if not cls_path:
raise NotImplementedError()
try:
app_label = cls_path.split('.')[-2]
model_nam... | Implement a Python 3 function for
trying and get a class from a settings key in the installed apps. | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_class_from_settings_full_path(settings_key):
"""Get a class from it's full path.
Example:
some.path.module.MyClass
"""
cls_path = getattr(settings, settings_key, None)
if not cls_path:
raise NotImplementedError()
try:
module_name, class_name = cls_path.rsplit('.',... | Implement a function in Python 3 to
get a class from it s full path. | As a python code expert, you are capable of creating scripts from specifications. |
def get_function_from_settings(settings_key):
"""Gets a function from the string path defined in a settings file.
Example:
# my_app/my_file.py
def some_function():
# do something
pass
# settings.py
SOME_FUNCTION = 'my_app.my_file.some_function'
> get_function_from_setting... | Create a Python 3 function to
get a function from the string path defined in a settings file. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Return the frame object for the caller s stack frame. | Can you generate a brief explanation for the following Python 3 code
def caller_locals():
# type: () -> Dict
"""Return the frame object for the caller's stack frame."""
try:
raise ValueError
except ValueError:
_, _, tb = sys.exc_info()
assert tb, "Can't get traceback, this should... | You are a Python code architect, reviewing and designing scalable and efficient code |
Create a repr from an instance of a class
| Can you tell what is the following Python 3 function doing
def make_repr(inst, attrs):
# type: (object, Sequence[str]) -> str
"""Create a repr from an instance of a class
Args:
inst: The class instance we are generating a repr of
attrs: The attributes that should appear in the repr
"""
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Default translation function for Fedora - RDO based systems | Explain what the following Python 3 code does
def default_rdo_tr(mod):
pkg = mod.rsplit('-python')[0]
pkg = pkg.replace('_', '-').replace('.', '-').lower()
if not pkg.startswith('python-'):
pkg = 'python-' + pkg
py2pkg = pkg
py3pkg = re.sub('python', 'python3', pkg)
return (pkg, py2pkg, ... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Default translation function for Ubuntu based systems | Explain what the following Python 3 code does
def default_ubuntu_tr(mod):
pkg = 'python-%s' % mod.lower()
py2pkg = pkg
py3pkg = 'python3-%s' % mod.lower()
return (pkg, py2pkg, py3pkg) | You are a Python code generator, capable of creating scripts from specifications. |
def default_suse_tr(mod):
"""
Default translation function for openSUSE, SLES, and other
SUSE based systems
Returns a tuple of 3 elements - the unversioned name, the python2 versioned
name and the python3 versioned name.
"""
pkg = 'python-%s' % mod
py2pkg = 'python2-%s' % mod
py3pkg... | Implement a function in Python 3 to
default translation function for openSUSE SLES and otherSUSE based systems | As a Python code analyst, you investigate and solve complex coding mysteries |
Return a corresponding package name for a python module. | Make a summary of the following Python 3 code
def module2package(mod, dist, pkg_map=None, py_vers=('py',)):
if not pkg_map:
pkg_map = get_pkg_map(dist)
for rule in pkg_map:
pkglist = rule(mod, dist)
if pkglist:
break
else:
tr_func = get_default_tr_func(dist)
... | You are a Python code generator, capable of creating scripts from specifications. |
def module2upstream(mod):
"""Return a corresponding OpenStack upstream name for a python module.
mod -- python module name
"""
for rule in OPENSTACK_UPSTREAM_PKG_MAP:
pkglist = rule(mod, dist=None)
if pkglist:
return pkglist[0]
return mod | Create a Python 3 function to
return a corresponding OpenStack upstream name for a python module. | As a Python code translator, you convert algorithms and pseudocode into Python. |
for resolving names from command line | How would you explain what the following Python 3 function does
def main():
parser = argparse.ArgumentParser(description='Python module name to'
'package name')
group = parser.add_mutually_exclusive_group()
group.add_argument('--dist', help='distribution style '
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Gets the paging values passed through the query string params. | Can you generate the documentation for the following Python 3 function
def get_paging(self):
orig_page_num = self.page_num
orig_page_size = self.page_size
try:
page_num = int(self.request.GET.get(self.page_kwarg or 'p'))
if page_num < 1:
page_num = orig... | As a python code expert, you are capable of creating scripts from specifications. |
def make_call_types(f, globals_d):
# type: (Callable, Dict) -> Tuple[Dict[str, Anno], Anno]
"""Make a call_types dictionary that describes what arguments to pass to f
Args:
f: The function to inspect for argument names (without self)
globals_d: A dictionary of globals to lookup annotation d... | Implement a Python 3 function for
making a call_types dictionary that describes what arguments to pass to f Taxonomy | As a Python code translator, you convert algorithms and pseudocode into Python. |
def make_annotations(f, globals_d=None):
# type: (Callable, Dict) -> Dict[str, Any]
"""Create an annotations dictionary from Python2 type comments
http://mypy.readthedocs.io/en/latest/python2.html
Args:
f: The function to examine for type comments
globals_d: The globals dictionary to g... | Write a Python 3 function that can
create an annotations dictionary from Python 2 type comments and type idents. | As a python code expert, you are capable of creating scripts from specifications. |
def get_object(self, **kwargs):
"""Sometimes preprocessing of a view need to happen before the object
attribute has been set for a view. In this case, just return the
object if it has already been set when it's called down the road since
there's no need to make another query.
""... | Can you write a function in Python 3 where it
overrides get_object to set the object in the object attribute. | As a Python code composer, you craft elegant and concise scripts. |
def hex_timestamp_to_datetime(hex_timestamp):
"""Converts hex timestamp to a datetime object.
>>> hex_timestamp_to_datetime('558BBCF9')
datetime.datetime(2015, 6, 25, 8, 34, 1)
>>> hex_timestamp_to_datetime('0x558BBCF9')
datetime.datetime(2015, 6, 25, 8, 34, 1)
>>> datetime.fromtimestamp(0x558B... | Write a Python 3 script to
convert a hex timestamp to a datetime object. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Gets the current datetime object by timezone. | Explain what the following Python 3 code does
def now_by_tz(tz='US/Central', ignoretz=True):
if isinstance(tz, string_types):
tz = pytz.timezone(tz)
if ignoretz:
return datetime.now(tz).replace(tzinfo=None)
return datetime.now(tz) | You are a Python code analyst, evaluating scripts for potential improvements. |
Converts a datetime object from the specified timezone to a UTC datetime. | Can you generate a brief explanation for the following Python 3 code
def tz_to_utc(dt, tz, ignoretz=True):
if isinstance(tz, string_types):
tz = pytz.timezone(tz)
dt = tz.localize(dt)
dt = datetime.astimezone(dt, pytz.timezone('UTC'))
if ignoretz:
return dt.replace(tzinfo=None)
ret... | As a python code expert, you are capable of creating scripts from specifications. |
Converts the given UTC datetime object to the specific timezone. | Make a summary of the following Python 3 code
def utc_to_tz(dt, tz, ignoretz=True):
if isinstance(tz, string_types):
tz = pytz.timezone(tz)
dt = pytz.utc.localize(dt)
dt = dt.astimezone(tz)
if ignoretz:
return dt.replace(tzinfo=None)
return dt | As a Python code composer, you craft elegant and concise scripts. |
Parse a date string into a date object. | How would you explain what the following Python 3 function does
def parse_date(dt, ignoretz=True, as_tz=None):
dttm = parse_datetime(dt, ignoretz=ignoretz)
return None if dttm is None else dttm.date() | As a Python code translator, you convert algorithms and pseudocode into Python. |
def parse_datetime(dt, ignoretz=True, **kwargs):
"""
:param dt: string datetime to convert into datetime object.
:return: datetime object if the string can be parsed into a datetime.
Otherwise, return None.
:see: http://labix.org/python-dateutil
Examples:
>>> parse_datetime('2011-12-3... | Can you create a Python 3 function that
parses a string datetime into a datetime object. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Turns emails off so no emails will be sent. | How would you explain what the following Python 3 function does
def turn_emails_off(view_func):
# Dummy email backend so no emails are sent.
EMAIL_BACKEND_DUMMY = 'django.core.mail.backends.dummy.EmailBackend'
def decorated(request, *args, **kwargs):
orig_email_backend = settings.EMAIL_BACKEND
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_md5_for_file(file):
"""Get the md5 hash for a file.
:param file: the file to get the md5 hash for
"""
md5 = hashlib.md5()
while True:
data = file.read(md5.block_size)
if not data:
break
md5.update(data)
return md5.hexdigest() | Implement a Python 3 function for
getting the md5 hash for a file. | As a python code expert, you are capable of creating scripts from specifications. |
Gets a dict of data form a json file. | Make a summary of the following Python 3 code
def get_dict_from_json_file(path, encoding='utf-8'):
with open(path, encoding=encoding) as data_file:
return json.loads(data_file.read()) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Adds linebreaks only for text that has a newline character. | Given the following Python 3 function, write the documentation
def linebreaks_safe(value, autoescape=True):
if isinstance(value, string_types) and '\n' in value:
return linebreaks_filter(value, autoescape=autoescape)
return value | You are a Python code generator, capable of creating scripts from specifications. |
Add a sub resource to the resource list | Can you tell what is the following Python 3 function doing
def add_sub_resource(self, relative_id, sub_resource):
existing_sub_resources = self.resources.get(sub_resource.RELATIVE_PATH_TEMPLATE, defaultdict(list))
existing_sub_resources[relative_id].append(sub_resource)
self.resources.update({su... | As a Python code composer, you craft elegant and concise scripts. |
def cloudshell_model_name(self):
"""Return the name of the CloudShell model"""
if self.shell_name:
return "{shell_name}.{resource_model}".format(shell_name=self.shell_name,
resource_model=self.RESOURCE_MODEL.replace(" ", ""))
... | Can you implement a function in Python 3 that
returns the name of the CloudShell model | You are a Python code generator, capable of creating scripts from specifications. |
def slice_yx(r, pval, ydim=1):
"""slice a correlation and p-value matrix of a (y,X) dataset
into a (y,x_i) vector and (x_j, x_k) matrices
Parameters
----------
r : ndarray
Correlation Matrix of a (y,X) dataset
pval : ndarray
p-values
ydim : int
Number of target var... | Implement a Python 3 function for
slicing a correlation matrix of a y - dimensional dataset and a p - value matrix of a y - dimensional dataset | As a python code expert, you are capable of creating scripts from specifications. |
Returns tuple with expression type and expression body | Can you tell what is the following Python 3 function doing
def parse_expression(source: str) -> ExpressionSource:
'''Returns tuple with expression type and expression body'''
if not is_expression(source):
msg = 'Expression is not valid. Expression should be matched with regular expression: {0}'\
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns a list of servers that have not errored in the last five minutes. | Given the following Python 3 function, write the documentation
def _server_whitelist(self):
'''
Returns list of servers that have not errored in the last five minutes.
If all servers have errored in the last five minutes, returns list with
one item, the server that errored least recently... | You are a Python code analyst, evaluating scripts for potential improvements. |
Creates an instance of Networking Resource by given context | Here you have a function in Python 3, explain what it does
def create_networking_resource_from_context(shell_name, supported_os, context):
result = GenericNetworkingResource(shell_name=shell_name, name=context.resource.name, supported_os=supported_os)
result.address = context.resource.address
result.family... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Find the N worst correlations in a given set of correlation coefficients. | Can you generate the documentation for the following Python 3 function
def find_worst(rho, pval, m=1, rlim=.10, plim=.35):
# convert to lists
n = len(rho)
r = list(np.abs(rho))
p = list(pval)
i = list(range(n))
# check m
if m > n:
warnings.warn(
'm is bigger than the ava... | As a Python code analyst, you investigate and solve complex coding mysteries |
Coerce value into a list. | Here you have a function in Python 3, explain what it does
def _parse_array(value):
value = value.lstrip()
if not value or value[0] not in _bracket_strings:
return None
return json.loads(value) | As a python code expert, you are capable of creating scripts from specifications. |
def _parse_boolean(value):
"""Coerce value into an bool.
:param str value: Value to parse.
:returns: bool or None if the value is not a boolean string.
"""
value = value.lower()
if value in _true_strings:
return True
elif value in _false_strings:
return False
else:
... | Create a Python 3 function to
coerce value into a boolean. | You are a Python code generator, capable of creating scripts from specifications. |
def _parse_object(value):
"""Coerce value into a dict.
:param str value: Value to parse.
:returns: dict or None if the value is not a JSON object
:raises: TypeError or ValueError if value appears to be an object but can't
be parsed as JSON.
"""
value = value.lstrip()
if not value or... | Implement a Python 3 function for
coercing value into a dict. | You are a Python code analyst, evaluating scripts for potential improvements. |
Parses a value into one of the allowed types. | Can you tell what is the following Python 3 function doing
def parse_value(value, allowed_types, name='value'):
if not isinstance(value, str):
raise ValueError('value for %r must be a string' % name)
if isinstance(allowed_types, str):
allowed_types = [allowed_types]
# Note that the order of... | As a python code expert, you are capable of creating scripts from specifications. |
Parse a value as JSON. | Given the following Python 3 function, write the documentation
def parse_json(value: str, sig_params: List[inspect.Parameter] = None) -> dict:
try:
loaded = json.loads(value)
except Exception as e:
message = 'Error parsing JSON: %r error: %s' % (value, e)
logging.debug(message, exc_info=... | As a python code expert, you are capable of creating scripts from specifications. |
def map_param_names(
req_params: dict, sig_params: List[inspect.Parameter]) -> dict:
"""Maps request param names to match logic function param names.
If a doctor type defined a `param_name` attribute for the name of the
parameter in the request, we should use that as the key when looking up
the... | Implement a function in Python 3 to
map request param names to match logic function param names. | You are a Python code generator, capable of creating scripts from specifications. |
Parses the form and query parameters from the input dict. | Here you have a function in Python 3, explain what it does
def parse_form_and_query_params(req_params: dict, sig_params: dict) -> dict:
# Importing here to prevent circular dependencies.
from doctor.types import SuperType, UnionType
errors = {}
parsed_params = {}
for param, value in req_params.items... | As a Python code analyst, you investigate and solve complex coding mysteries |
Pass the request info to the async framework. | Given the following Python 3 function, write the documentation
def _handle_task(self):
headers = self.request.headers
message = None
try:
status_code, output = process_async_task(
headers, self.request.body)
except AbortAndRestart as restart:
# As... | You are a Python code architect, reviewing and designing scalable and efficient code |
def migrate_autoload_details(autoload_details, shell_name, shell_type):
""" Migrate autoload details. Add namespace for attributes
:param autoload_details:
:param shell_name:
:param shell_type:
:return:
"""
mapping = {}
for resource in autoload_details.resources:
resource.model... | Can you implement a function in Python 3 that
migrates autoload details. Add namespace for resources and attributes. | You are a Python code analyst, evaluating scripts for potential improvements. |
Creates an instance of FirewallResource from given context | Can you tell what is the following Python 3 function doing
def create_firewall_resource_from_context(shell_name, supported_os, context):
result = GenericFirewallResource(shell_name=shell_name, name=context.resource.name, supported_os=supported_os)
result.address = context.resource.address
result.family = c... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Get right method to convert the value. | Can you generate a brief explanation for the following Python 3 code
def _get_convert_method(self):
for type_, method in self._map.items():
if type(self.value) is bool and type_ is not bool:
continue
if isinstance(self.value, type_):
return method
... | As a Python code composer, you craft elegant and concise scripts. |
def flatten(rho, pval, sortby="cor"):
"""Flatten correlation and p-value matrix
Parameters:
-----------
rho : ndarray
Correlation Matrix
pval : ndarray
Matrix with p-values
sortby : str
sort the output table by
- "cor" the highest absolute correlation coeffici... | Can you write a function in Python 3 where it
flattens correlation matrix and p - value matrix into a single table. | You are a Python code generator, capable of creating scripts from specifications. |
Get the maximum value this immediate can have
| Explain what the following Python 3 code does
def max(self) -> int:
if self.signed:
v = (1 << (self.bits - 1)) - 1
else:
v = (1 << self.bits) - 1
if self.lsb0:
v = v - (v % 2)
return v | As a Python code translator, you convert algorithms and pseudocode into Python. |
Sets the immediate value of the entry. | Can you generate a brief explanation for the following Python 3 code
def set(self, value: int):
if not isinstance(value, int):
raise self.exception("{} is not an integer".format(value))
if self.lsb0 and self.value % 2 == 1:
raise self.exception("{} not power of two".format(value)... | As a Python code analyst, you investigate and solve complex coding mysteries |
Set the immediate value from machine code bits. | Can you tell what is the following Python 3 function doing
def set_from_bits(self, value: int):
if self.signed:
value = -(value & self.tcmask) + (value & ~self.tcmask)
self.set(value) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Randomize this immediate to a legal value. | Here you have a function in Python 3, explain what it does
def randomize(self):
self.value = randint(self.min(), self.max())
if self.lsb0:
self.value = self.value - (self.value % 2) | You are a Python code architect, reviewing and designing scalable and efficient code |
Initialize the furious context and registry. | Can you generate the documentation for the following Python 3 function
def _init():
# If there is a context and it is initialized to this request,
# return, otherwise reinitialize the _local_context.
if (hasattr(_local_context, '_initialized') and
_local_context._initialized == os.environ.get('R... | You are a Python code analyst, evaluating scripts for potential improvements. |
def run_job():
"""Takes an async object and executes its job."""
async = get_current_async()
async_options = async.get_options()
job = async_options.get('job')
if not job:
raise Exception('This async contains no job to execute!')
__, args, kwargs = job
if args is None:
arg... | Create a Python 3 function to
take an async object and executes its job. | As a Python code analyst, you investigate and solve complex coding mysteries |
Process the results of executing the Async s target. | Can you tell what is the following Python 3 function doing
def _handle_results(options):
results_processor = options.get('_process_results')
if not results_processor:
results_processor = _process_results
processor_result = results_processor()
if isinstance(processor_result, (Async, Context)):
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def encode_exception(exception):
"""Encode exception to a form that can be passed around and serialized.
This will grab the stack, then strip off the last two calls which are
encode_exception and the function that called it.
"""
import sys
return AsyncException(unicode(exception),
... | How would you code a function in Python 3 to
encode an exception to a form that can be passed around and serialized. | You are a Python code generator, capable of creating scripts from specifications. |
Process the results from an Async job. | Can you generate a brief explanation for the following Python 3 code
def _process_results():
async = get_current_async()
callbacks = async.get_callbacks()
if not isinstance(async.result.payload, AsyncException):
callback = callbacks.get('success')
else:
callback = callbacks.get('error')... | You are a Python code analyst, evaluating scripts for potential improvements. |
def _execute_callback(async, callback):
"""Execute the given callback or insert the Async callback, or if no
callback is given return the async.result.
"""
from furious.async import Async
if not callback:
return async.result.payload
if isinstance(callback, Async):
return callba... | Can you write a function in Python 3 where it
executes the given callback or insert the Async callback or return the result. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_example_curl_lines(method: str, url: str, params: dict,
headers: dict) -> List[str]:
"""Render a cURL command for the given request.
:param str method: HTTP request method (e.g. "GET").
:param str url: HTTP request URL.
:param dict params: JSON body, for POST and PUT ... | Write a Python 3 script for
rendering a cURL command for the given request. | As a python code expert, you are capable of creating scripts from specifications. |
Render a reStructuredText example for the given request and response. | Here you have a function in Python 3, explain what it does
def get_example_lines(headers: Dict[str, str], method: str, url: str,
params: Dict[str, Any], response: str) -> List[str]:
"""Render a reStructuredText example for the given request and response.
:param dict headers: A dict of HTT... | As a python code expert, you are capable of creating scripts from specifications. |
def get_object_reference(obj: Object) -> str:
"""Gets an object reference string from the obj instance.
This adds the object type to ALL_RESOURCES so that it gets documented and
returns a str which contains a sphinx reference to the documented object.
:param obj: The Object instance.
:returns: A s... | Can you implement a function in Python 3 that
gets an object reference string from the obj instance. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_array_items_description(item: Array) -> str:
"""Returns a description for an array's items.
:param item: The Array type whose items should be documented.
:returns: A string documenting what type the array's items should be.
"""
desc = ''
if isinstance(item.items, list):
# This m... | Write a Python 3 function for
returning a string documenting what types the array s items should be documented. | As a Python code composer, you craft elegant and concise scripts. |
def get_json_types(annotated_type: SuperType) -> List[str]:
"""Returns the json types for the provided annotated type.
This handles special cases for when we encounter UnionType and an Array.
UnionType's will have all valid types returned. An Array will document
what the items type is by placing that ... | Can you implement a function in Python 3 that
returns the json types for the provided annotated type. | As a python code expert, you are capable of creating scripts from specifications. |
Generates the documentation for the given object annotation. | Can you generate the documentation for the following Python 3 function
def get_json_object_lines(annotation: ResourceAnnotation,
properties: Dict[str, Any], field: str,
url_params: Dict, request: bool = False,
object_property: bool = False) -... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_json_lines(annotation: ResourceAnnotation, field: str, route: str,
request: bool = False) -> List:
"""Generate documentation lines for the given annotation.
This only documents schemas of type "object", or type "list" where each
"item" is an object. Other types are ignored (but a... | Create a Python 3 function for
generating documentation lines for the given annotation. | You are a Python code generator, capable of creating scripts from specifications. |
Generate documentation lines for all collected resource objects. | Make a summary of the following Python 3 code
def get_resource_object_doc_lines() -> List[str]:
# First loop through all resources and make sure to add any properties that
# are objects and not already in `ALL_RESOURCES`. We iterate over a copy
# since we will be modifying the dict during the loop.
fo... | As a Python code composer, you craft elegant and concise scripts. |
Return a best guess at the qualified name for a class or function object. | Can you tell what is the following Python 3 function doing
def get_name(value) -> str:
if value.__module__ == '__builtin__':
return value.__name__
else:
return '.'.join((value.__module__, value.__name__)) | You are a Python code analyst, evaluating scripts for potential improvements. |
Normalize the given route. | Here you have a function in Python 3, explain what it does
def normalize_route(route: str) -> str:
normalized_route = str(route).lstrip('^').rstrip('$').rstrip('?')
normalized_route = normalized_route.replace('<', '(').replace('>', ')')
return normalized_route | You are a Python code architect, reviewing and designing scalable and efficient code |
Add the prefix to each of the lines. | Can you tell what is the following Python 3 function doing
def prefix_lines(lines, prefix):
if isinstance(lines, bytes):
lines = lines.decode('utf-8')
if isinstance(lines, str):
lines = lines.splitlines()
return [prefix + line for line in lines] | As a python code expert, you are capable of creating scripts from specifications. |
def class_name_to_resource_name(class_name: str) -> str:
"""Converts a camel case class name to a resource name with spaces.
>>> class_name_to_resource_name('FooBarObject')
'Foo Bar Object'
:param class_name: The name to convert.
:returns: The resource name.
"""
s = re.sub('(.)([A-Z][a-z]+... | Can you implement a function in Python 3 that
converts a camel case class name to a resource name with spaces. | As a python code expert, you are capable of creating scripts from specifications. |
def _render_rst(self): # pragma: no cover
"""Render lines of reStructuredText for items yielded by
:meth:`~doctor.docs.base.BaseHarness.iter_annotations`.
"""
# Create a mapping of headers to annotations. We want to group
# all annotations by a header, but they could be in mult... | Write a Python 3 function that can
render lines of reStructuredText for items yielded by baseHarness. iter_annotations. | You are a Python code analyst, evaluating scripts for potential improvements. |
def run(self): # pragma: no cover
"""Called by Sphinx to generate documentation for this directive."""
if self.directive_name is None:
raise NotImplementedError('directive_name must be implemented by '
'subclasses of BaseDirective')
env, state =... | Create a Python 3 function for
calling by Sphinx to generate documentation for this directive. | You are a Python code generator, capable of creating scripts from specifications. |
Handler for Sphinx s env - purge - doc event. | Can you generate the documentation for the following Python 3 function
def purge_docs(cls, app, env, docname): # pragma: no cover
state = getattr(env, cls.directive_name, None)
if state and docname in state.doc_names:
state.doc_names.remove(docname) | You are a Python code analyst, evaluating scripts for potential improvements. |
def setup(cls, app): # pragma: no cover
"""Called by Sphinx to setup an extension."""
if cls.directive_name is None:
raise NotImplementedError('directive_name must be set by '
'subclasses of BaseDirective')
if not app.registry.has_domain('http')... | Write a Python 3 script to
call by Sphinx to setup an extension. | You are a Python code generator, capable of creating scripts from specifications. |
def define_header_values(self, http_method, route, values, update=False):
"""Define header values for a given request.
By default, header values are determined from the class attribute
`headers`. But if you want to change the headers used in the
documentation for a specific route, this ... | Create a Python 3 function to
define header values for a given request. | You are a Python code generator, capable of creating scripts from specifications. |
Define example values for a given request. | How would you explain what the following Python 3 function does
def define_example_values(self, http_method, route, values, update=False):
self.defined_example_values[(http_method.lower(), route)] = {
'update': update,
'values': values
} | You are a Python code generator, capable of creating scripts from specifications. |
def _get_annotation_heading(self, handler, route, heading=None):
"""Returns the heading text for an annotation.
Attempts to get the name of the heading from the handler attribute
`schematic_title` first.
If `schematic_title` it is not present, it attempts to generate
the title ... | Can you write a function in Python 3 where it
gets the text for an annotation heading. | You are a Python code generator, capable of creating scripts from specifications. |
Gets the headers for the provided route. | Can you generate a brief explanation for the following Python 3 code
def _get_headers(self, route: str, annotation: ResourceAnnotation) -> Dict:
headers = self.headers.copy()
defined_header_values = self.defined_header_values.get(
(annotation.http_method.lower(), str(route)))
if defi... | You are a Python code analyst, evaluating scripts for potential improvements. |
Gets the example values for all properties in the schema. | Given the following Python 3 function, write the documentation
def _get_example_values(self, route: str,
annotation: ResourceAnnotation) -> Dict[str, Any]:
"""Gets example values for all properties in the annotation's schema.
:param route: The route to get example values for... | As a python code expert, you are capable of creating scripts from specifications. |
Get the device name by its SNMP sysObjectID property from the file map
| Given the following Python 3 function, write the documentation
def get_device_name(file_name, sys_obj_id, delimiter=":"):
try:
with open(file_name, "rb") as csv_file:
csv_reader = csv.reader(csv_file, delimiter=delimiter)
for row in csv_reader:
if len(row) >= 2 and r... | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns True if querypart_name with value is set. | Make a summary of the following Python 3 code
def has(self, querypart_name, value=None):
if super().has(querypart_name, value):
return True
if not value:
return super().has('select_options', querypart_name)
return False | As a Python code analyst, you investigate and solve complex coding mysteries |
def group_by(self, *args, **kwds):
"""
Default ordering is ``ASC``.
``group_by`` accept ``dict`` as you would expect, but note that ``dict``
does not have same order. Same for named arguments.
.. code-block:: python
>>> sqlpuzzle.select('c').from_('t').group_by('a'... | Can you create a Python 3 function that
groups by a set of attributes. | You are a Python code generator, capable of creating scripts from specifications. |
Order by a key. | Can you generate a brief explanation for the following Python 3 code
def order_by(self, *args, **kwds):
self._order_by.order_by(*args, **kwds)
return self | You are a Python code architect, reviewing and designing scalable and efficient code |
Log out that the context is complete. | Make a summary of the following Python 3 code
def context_complete(context_id):
logging.info('Context %s is.......... DONE.', context_id)
from furious.context import get_current_async_with_context
_, context = get_current_async_with_context()
if not context:
logging.error("Could not load cont... | As a Python code composer, you craft elegant and concise scripts. |
def process_messages(tag, retries=0):
"""Processes the messages pulled fromm a queue based off the tag passed in.
Will insert another processor if any work was processed or the retry count
is under the max retry count. Will update a aggregated stats object with
the data in the payload of the messages pr... | Write a Python 3 script to
process the messages pulled from a queue based off the passed in. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Updates the stats with the value passed in. | Make a summary of the following Python 3 code
def set_stats(stats, value):
stats["total_count"] += 1
stats["value"] += value
stats["average"] = stats["value"] / stats["total_count"]
# this is just a basic example and not the best way to track aggregation.
# for max and min old there are cases where... | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_default_stats():
"""Returns a :class: `dict` of the default stats structure."""
default_stats = {
"total_count": 0,
"max": 0,
"min": 0,
"value": 0,
"average": 0,
"last_update": None,
}
return {
"totals": default_stats,
"colors": {... | Write a Python 3 function that can
return a : class : dict of the default stats structure. | You are a Python code architect, reviewing and designing scalable and efficient code |
Serializes output as JSON and writes it to console output wrapped with special prefix and suffix | Given the following Python 3 function, write the documentation
def serialize_to_json(result, unpicklable=False):
json = jsonpickle.encode(result, unpicklable=unpicklable)
result_for_output = str(json)
return result_for_output | As a Python code analyst, you investigate and solve complex coding mysteries |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.