output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def getZoom(self, resolution):
"Return the zoom level for a given resolution"
assert resolution in self.RESOLUTIONS
return self.RESOLUTIONS.index(resolution) | Can you implement a function in Python 3 that
returns the zoom level for a given resolution | You are a Python code architect, reviewing and designing scalable and efficient code |
Return lower and higher zoom level given a resolution | Given the following Python 3 function, write the documentation
def _getZoomLevelRange(self, resolution, unit='meters'):
"Return lower and higher zoom level given a resolution"
assert unit in ('meters', 'degrees')
if unit == 'meters' and self.unit == 'degrees':
resolution = resolution... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def getClosestZoom(self, resolution, unit='meters'):
"""
Return the closest zoom level for a given resolution
Parameters:
resolution -- max. resolution
unit -- unit for output (default='meters')
"""
lo, hi = self._getZoomLevelRange(resolution, unit)
... | Create a Python 3 function for
returning the closest zoom level for a given resolution | You are a Python code generator, capable of creating scripts from specifications. |
Returns the highest zoom level for a given resolution | How would you explain what the following Python 3 function does
def getCeilingZoom(self, resolution, unit='meters'):
if resolution in self.RESOLUTIONS:
return self.getZoom(resolution)
lo, hi = self._getZoomLevelRange(resolution, unit)
if lo == 0 or lo == hi:
return lo
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def getScale(self, zoom):
"""Returns the scale at a given zoom level"""
if self.unit == 'degrees':
resolution = self.getResolution(zoom) * EPSG4326_METERS_PER_UNIT
else:
resolution = self.getResolution(zoom)
return resolution / STANDARD_PIXEL_SIZE | Can you implement a function in Python 3 that
returns the scale at a given zoom level | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns the bounding addresses of the current instance based on the extent. | Explain what the following Python 3 code does
def getExtentAddress(self, zoom, extent=None, contained=False):
if extent:
bbox = extent
else:
bbox = self.extent
minX = bbox[0]
maxX = bbox[2]
if self.originCorner == 'bottom-left':
minY = bbox[3]
... | As a Python code composer, you craft elegant and concise scripts. |
Returns the parent tile addresses for an irregular tiling scheme. | Given the following Python 3 function, write the documentation
def getParentTiles(self, zoom, col, row, zoomParent):
assert zoomParent <= zoom
if zoomParent == zoom:
return [[zoom, col, row]]
extent = self.tileBounds(zoom, col, row)
minRow, minCol, maxRow, maxCol = self.getEx... | As a Python code composer, you craft elegant and concise scripts. |
def enable_loggly(graph):
"""
Enable loggly if it is configured and not debug/testing.
"""
if graph.metadata.debug or graph.metadata.testing:
return False
try:
if not graph.config.logging.loggly.token:
return False
if not graph.config.logging.loggly.environment... | Implement a Python 3 function for
enabling loggly if it is configured and not debug or testing. | As a Python code composer, you craft elegant and concise scripts. |
Build a dictionary configuration from conventions and configuration. | Can you generate a brief explanation for the following Python 3 code
def make_dict_config(graph):
formatters = {}
handlers = {}
loggers = {}
# create the console handler
formatters["ExtraFormatter"] = make_extra_console_formatter(graph)
handlers["console"] = make_stream_handler(graph, formatter... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Create the default json formatter. | Explain what the following Python 3 code does
def make_json_formatter(graph):
return {
"()": graph.config.logging.json_formatter.formatter,
"fmt": graph.config.logging.json_required_keys,
} | As a Python code composer, you craft elegant and concise scripts. |
Create the stream handler. Used for console output. | Make a summary of the following Python 3 code
def make_stream_handler(graph, formatter):
return {
"class": graph.config.logging.stream_handler.class_,
"formatter": formatter,
"level": graph.config.logging.level,
"stream": graph.config.logging.stream_handler.stream,
} | You are a Python code analyst, evaluating scripts for potential improvements. |
Create the loggly handler. | Here you have a function in Python 3, explain what it does
def make_loggly_handler(graph, formatter):
base_url = graph.config.logging.loggly.base_url
loggly_url = "{}/inputs/{}/tag/{}".format(
base_url,
graph.config.logging.loggly.token,
",".join([
graph.metadata.name,
... | As a Python code composer, you craft elegant and concise scripts. |
Create third party library logging level configurations. | Can you generate a brief explanation for the following Python 3 code
def make_library_levels(graph):
# inject the default components; these can, but probably shouldn't, be overridden
levels = {}
for level in ["DEBUG", "INFO", "WARN", "ERROR"]:
levels.update({
component: {
... | As a python code expert, you are capable of creating scripts from specifications. |
Process the request and return a new URL if there is a matching Redirect model
with the current request URL as the new_path field. | How would you explain what the following Python 3 function does
def process_request(self, request):
site = request.site
cache_key = '{prefix}-{site}'.format(prefix=settings.REDIRECT_CACHE_KEY_PREFIX, site=site.domain)
redirects = cache.get(cache_key)
if redirects is None:
red... | As a Python code composer, you craft elegant and concise scripts. |
Monkey patched version of Django s SiteManager. get_current function. | Can you generate the documentation for the following Python 3 function
def patched_get_current(self, request=None):
# Imported here to avoid circular import
from django.conf import settings
if request:
try:
return self._get_site_by_request(request) # pylint: disable=protected-access
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Monkey patched version of Django s SiteManager. _get_site_by_id method. | Can you tell what is the following Python 3 function doing
def patched_get_site_by_id(self, site_id):
now = datetime.datetime.utcnow()
site = models.SITE_CACHE.get(site_id)
cache_timeout = SITE_CACHE_TIMEOUTS.get(site_id, now)
if not site or cache_timeout <= now:
site = self.get(pk=site_id)
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def patched_get_site_by_request(self, request):
"""
Monkey patched version of Django's SiteManager._get_site_by_request() function.
Adds a configurable timeout to the in-memory SITE_CACHE for each cached Site.
This allows for the use of an in-memory cache for Site models, avoiding one
or more DB hi... | How would you implement a function in Python 3 that
monkeys patched version of Django s SiteManager. _get_site_by_request function. | As a python code expert, you are capable of creating scripts from specifications. |
def str_brief(obj, lim=20, dots='...', use_repr=True):
"""Truncates a string, starting from 'lim' chars. The given object
can be a string, or something that can be casted to a string.
>>> import string
>>> str_brief(string.uppercase)
'ABCDEFGHIJKLMNOPQRST...'
>>> str_brief(2 ** 50, lim=10, dots... | Can you implement a function in Python 3 that
truncates a string starting from lim chars. | You are a Python code generator, capable of creating scripts from specifications. |
returns a map volume_name -> volume cg_name -> cg | How would you explain what the following Python 3 function does
def get_mirror_resources_by_name_map(self, scope=None):
volumes_mirrors_by_name = dict()
cgs_mirrors_by_name = dict()
if ((scope is None) or (scope.lower() == 'volume')):
mirror_list = self.xcli_client.cmd.mirror_lis... | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_host_port_names(self, host_name):
""" return a list of the port names of XIV host """
port_names = list()
host = self.get_hosts_by_name(host_name)
fc_ports = host.fc_ports
iscsi_ports = host.iscsi_ports
port_names.extend(fc_ports.split(',') if fc_ports != ''... | Implement a Python 3 function for
returning a list of the port names of a XIV host | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_cluster_port_names(self, cluster_name):
""" return a list of the port names under XIV CLuster """
port_names = list()
for host_name in self.get_hosts_by_clusters()[cluster_name]:
port_names.extend(self.get_hosts_by_name(host_name))
return port_names | Implement a function in Python 3 to
return a list of the port names under a given cluster | As a Python code translator, you convert algorithms and pseudocode into Python. |
def flush(self):
"""remove all stale clients from pool"""
now = time.time()
to_remove = []
for k, entry in self.pool.items():
if entry.timestamp < now:
entry.client.close()
to_remove.append(k)
for k in to_remove:
del self.po... | Create a Python 3 function to
remove all stale clients from pool | You are a Python code analyst, evaluating scripts for potential improvements. |
def get(self, user, password, endpoints):
"""Gets an existing connection or opens a new one
"""
now = time.time()
# endpoints can either be str or list
if isinstance(endpoints, str):
endpoints = [endpoints]
for ep in endpoints:
if ep not in self.po... | Can you write a function in Python 3 where it
gets an existing connection or opens a new one | As a python code expert, you are capable of creating scripts from specifications. |
Returns a size string for the given integer. | Explain what the following Python 3 code does
def size(value: int, suffixes: list = None) -> str:
suffixes = suffixes or [
'bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
order = int(log2(value) / 10) if value else 0
return '{:.4g} {}'.format(value / (1 << (order * 10)), suffixes[order]) | As a Python code translator, you convert algorithms and pseudocode into Python. |
def parse_size(value):
"""
>>> parse_size('1M')
1048576
>>> parse_size('512K512K')
1048576
>>> parse_size('512K 512K')
1048576
>>> parse_size('512K 512K 4')
1048580
"""
if isinstance(value, (int, float)):
return value
elif not pattern_valid.fullmatch(value):
... | Implement a function in Python 3 to
parse the size of a single object. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def parse_duration(value):
"""
>>> parse_duration('1h')
3600
>>> parse_duration('1m')
60
>>> parse_duration('1m 2s')
62
>>> parse_duration('1')
1
"""
if isinstance(value, (int, float)):
return value
elif not pattern_valid.fullmatch(value):
raise ValueErro... | Write a Python 3 function for
parsing duration from a string | You are a Python code analyst, evaluating scripts for potential improvements. |
send an event to the available media modules | Can you generate the documentation for the following Python 3 function
def send_event(self, action, properties, event_severity=EVENT_SEVERITY):
# verify properties
event_properties = dict() if (properties is None) else properties
if type(event_properties) is not dict:
raise TypeError... | You are a Python code architect, reviewing and designing scalable and efficient code |
def _create_mirror(self, resource_type, resource_name, target_name,
mirror_type, slave_resource_name, create_slave='no',
remote_pool=None, rpo=None, remote_rpo=None,
schedule=None, remote_schedule=None,
activate_mirror='no')... | Write a Python 3 script to
create a mirror and returns a new mirror object. | You are a Python code analyst, evaluating scripts for potential improvements. |
def chained(wrapping_exc):
# pylint: disable=W0212
"""
Embeds the current exception information into the given one (which
will replace the current one).
For example::
try:
...
except OSError as ex:
raise chained(MyError("database not found!"))
"""
t, ... | Write a Python 3 script for
embedding the current exception information into the given one (which will replace the current one). For example:: try: ... except OSError as ex: raise chained(MyError("database not found!")) | As a Python code composer, you craft elegant and concise scripts. |
def get_user(self, username, *, mode=OsuMode.osu, event_days=31):
"""Get a user profile.
Parameters
----------
username : str or int
A `str` representing the user's username, or an `int` representing the user's id.
mode : :class:`osuapi.enums.OsuMode`
The... | Create a Python 3 function for
getting a user profile. | You are a Python code generator, capable of creating scripts from specifications. |
Get a user s best scores. | How would you explain what the following Python 3 function does
def get_user_best(self, username, *, mode=OsuMode.osu, limit=50):
return self._make_req(endpoints.USER_BEST, dict(
k=self.key,
u=username,
type=_username_type(username),
m=mode.value,
limi... | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_user_recent(self, username, *, mode=OsuMode.osu, limit=10):
"""Get a user's most recent scores, within the last 24 hours.
Parameters
----------
username : str or int
A `str` representing the user's username, or an `int` representing the user's id.
mode : :cla... | Create a Python 3 function to
get a user s most recent scores within the last 24 hours. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Get the top scores for a given beatmap. | Make a summary of the following Python 3 code
def get_scores(self, beatmap_id, *, username=None, mode=OsuMode.osu, mods=None, limit=50):
return self._make_req(endpoints.SCORES, dict(
k=self.key,
b=beatmap_id,
u=username,
type=_username_type(username),
... | As a Python code composer, you craft elegant and concise scripts. |
Get a specific set of beatmaps. | Can you generate a brief explanation for the following Python 3 code
def get_beatmaps(self, *, since=None, beatmapset_id=None, beatmap_id=None, username=None, mode=None,
include_converted=False, beatmap_hash=None, limit=500):
"""Get beatmaps.
Parameters
----------
s... | As a python code expert, you are capable of creating scripts from specifications. |
Get a multiplayer match. | Can you generate a brief explanation for the following Python 3 code
def get_match(self, match_id):
return self._make_req(endpoints.MATCH, dict(
k=self.key,
mp=match_id), Match) | You are a Python code architect, reviewing and designing scalable and efficient code |
async def copy(self, key_source, storage_dest, key_dest):
""" Return True if data are copied
* optimized for http->fs copy
* not supported return_status
"""
from aioworkers.storage.filesystem import FileSystemStorage
if not isinstance(storage_dest, FileSystemStorage):
... | Can you write a function in Python 3 where it
copies the data from key_source to key_dest. | As a Python code composer, you craft elegant and concise scripts. |
def import_name(stref: str):
"""
>>> import_name('datetime.datetime.utcnow') is not None
True
>>> import_name('aioworkers.utils.import_name') is not None
True
"""
h = stref
p = []
m = None
try:
r = importlib.util.find_spec(stref)
except (AttributeError, ImportError):
... | Can you implement a function in Python 3 that
imports a name from sys. modules. | You are a Python code architect, reviewing and designing scalable and efficient code |
def set_options(self, **options):
"""Sets the value of the given options (as keyword arguments).
Note that underscored in the option's name will be replaced with
hyphens (i.e., ``c.set_options(gui_mode = True)``
will set the option ``gui-mode``)
"""
opt2 = self._contexts[... | Write a Python 3 function for
setting the value of the options keyword arguments. | You are a Python code architect, reviewing and designing scalable and efficient code |
Creates an SSL transport to the first endpoint that we successfully connect to. | Can you generate the documentation for the following Python 3 function
def connect_ssl(cls, user, password, endpoints,
ca_certs=None, validate=None):
"""
Creates an SSL transport to the first endpoint (aserver) to which
we successfully connect
"""
if isinstanc... | You are a Python code architect, reviewing and designing scalable and efficient code |
Creates a MultiEndpointTransport for the given list of endpoints. | How would you explain what the following Python 3 function does
def connect_multiendpoint_ssl(cls, user, password, endpoints,
auto_discover=True, ca_certs=None,
validate=None):
"""
Creates a MultiEndpointTransport, so that if the curren... | You are a Python code analyst, evaluating scripts for potential improvements. |
def execute_remote(self, remote_target, cmd, **kwargs):
"""
Executes the given command (with the given arguments)
on the given remote target of the connected machine
"""
data = self._build_command(cmd, kwargs, self._contexts[-1],
remote_target)
... | Can you create a Python 3 function that
executes the given command on the given remote target. | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_user_client(self, user, password, populate=True):
"""
Returns a new client for the given user. This is a lightweight
client that only uses different credentials and shares the transport
with the underlying client
"""
return XCLIClientForUser(weakproxy(self), user,... | Create a Python 3 function for
returning a new client for the given user. | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns a new RemoteXCLIClient for the remote target. | Can you tell what is the following Python 3 function doing
def get_remote_client(self, target_name, user=None, password=None):
if user:
base = self.get_user_client(user, password, populate=False)
else:
base = weakproxy(self)
return RemoteXCLIClient(base, target_name, popu... | You are a Python code architect, reviewing and designing scalable and efficient code |
Calculates the accuracy of the current log entry. | How would you explain what the following Python 3 function does
def accuracy(self, mode: OsuMode):
if mode is OsuMode.osu:
return (
(6 * self.count300 + 2 * self.count100 + self.count50) /
(6 * (self.count300 + self.count100 + self.count50 + self.countmiss)))
... | As a python code expert, you are capable of creating scripts from specifications. |
creates a mirror and returns a mirror object | Can you tell what is the following Python 3 function doing
def create_mirror(self, resource_name, target_name, mirror_type,
slave_resource_name, rpo=None, remote_rpo=None,
schedule=None, remote_schedule=None,
activate_mirror='no'):
'''creates... | You are a Python code architect, reviewing and designing scalable and efficient code |
Get all non snapshots volumes in a group | Can you tell what is the following Python 3 function doing
def get_cg_volumes(self, group_id):
for volume in self.xcli_client.cmd.vol_list(cg=group_id):
if volume.snapshot_of == '':
yield volume.name | As a Python code analyst, you investigate and solve complex coding mysteries |
Add a converter to the list of converters. | Can you tell what is the following Python 3 function doing
def add_converter(cls, klass, conv, score=0):
if isinstance(klass, str):
klass = import_name(klass)
item = klass, conv, score
cls.converters.append(item)
cls.converters.sort(key=lambda x: x[0])
return cls | As a Python code analyst, you investigate and solve complex coding mysteries |
Generates Bunches each representing a single subelement of the response. | Make a summary of the following Python 3 code
def all(self, element_type=None, response_path=None):
path = self.RETURN_PATH
if response_path is not None:
path += "/" + response_path
response_element = self.response_etree.find(path)
if response_element is None:
ret... | You are a Python code architect, reviewing and designing scalable and efficient code |
Processes the response as a single - element response | Can you generate the documentation for the following Python 3 function
def as_single_element(self):
if self.as_return_etree is None:
return None
if len(self.as_return_etree.getchildren()) == 1:
return _populate_bunch_with_element(self.as_return_etree.
... | You are a Python code generator, capable of creating scripts from specifications. |
def enabled_flags(self):
"""Return the objects for each individual set flag."""
if not self.value:
yield self.__flags_members__[0]
return
val = self.value
while val:
lowest_bit = val & -val
val ^= lowest_bit
yield self.__flags_... | How would you code a function in Python 3 to
return the objects for each individual set flag. | You are a Python code generator, capable of creating scripts from specifications. |
Check if any of the attributes is set. | Make a summary of the following Python 3 code
def contains_any(self, other):
return self.value == other.value or self.value & other.value | You are a Python code generator, capable of creating scripts from specifications. |
Get the cumulative time percentage of each stopwatch including the current split. | Explain what the following Python 3 code does
def get_percentage(self):
cumulative_elapsed_time = self.get_cumulative_elapsed_time()
sum_elapsed_time = sum(cumulative_elapsed_time, datetime.timedelta())
if not sum_elapsed_time:
raise ValueError("cannot get percentage if there is no a... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_mean_per_split(self):
"""Get the mean elapsed time per split of each stopwatch (excluding the current split).
Returns
-------
mean_elapsed_time_per_split : List[datetime.timedelta]
"""
return [div_timedelta(sum(stopwatch.split_elapsed_time, datetime.timedelta()),... | Write a Python 3 function that can
return the mean elapsed time per split of each stopwatch. | You are a Python code generator, capable of creating scripts from specifications. |
def get_statistics(self):
"""Get all statistics as a dictionary.
Returns
-------
statistics : Dict[str, List]
"""
return {
'cumulative_elapsed_time': self.get_cumulative_elapsed_time(),
'percentage': self.get_percentage(),
'n_splits': ... | Write a Python 3 script to
get all statistics as a dictionary. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Converts the query string from a target uri uses cls. default_query to populate default arguments. | Make a summary of the following Python 3 code
def conform_query(cls, query):
query = parse_qs(query, keep_blank_values=True)
# Load yaml of passed values
for key, vals in query.items():
# Multiple values of the same name could be passed use first
# Also params without st... | You are a Python code analyst, evaluating scripts for potential improvements. |
def load_target(cls, scheme, path, fragment, username,
password, hostname, port, query,
load_method, **kwargs):
"""Override this method to use values from the parsed uri to initialize
the expected target.
"""
raise NotImplementedError("load_target... | Implement a Python 3 function for
overriding this method to use values from the parsed uri to initialize the expected target. | You are a Python code analyst, evaluating scripts for potential improvements. |
Send multiple HTTP requests ON green thread | Explain what the following Python 3 code does
def hog(concurrency, requests, limit, timeout,
params, paramfile, headers, headerfile, method, url):
'''Sending multiple `HTTP` requests `ON` `GREEN` thread'''
params = parse_from_list_and_file(params, paramfile)
headers = parse_from_list_and_file(heade... | As a Python code analyst, you investigate and solve complex coding mysteries |
Append a value to the contents of the current dict. | Make a summary of the following Python 3 code
def _append_value(self, value, _file, _name):
_tabs = '\t' * self._tctr
_keys = '{tabs}<key>{name}</key>\n'.format(tabs=_tabs, name=_name)
_file.seek(self._sptr, os.SEEK_SET)
_file.write(_keys)
self._append_dict(value, _file) | As a Python code analyst, you investigate and solve complex coding mysteries |
def _append_array(self, value, _file):
"""Call this function to write array contents.
Keyword arguments:
* value - dict, content to be dumped
* _file - FileIO, output file
"""
_tabs = '\t' * self._tctr
_labs = '{tabs}<array>\n'.format(tabs=_tabs)
... | Write a Python 3 function for
appending array contents to the file. | As a Python code composer, you craft elegant and concise scripts. |
def _append_dict(self, value, _file):
"""Call this function to write dict contents.
Keyword arguments:
* value - dict, content to be dumped
* _file - FileIO, output file
"""
_tabs = '\t' * self._tctr
_labs = '{tabs}<dict>\n'.format(tabs=_tabs)
_f... | Write a Python 3 script to
append dict contents to the file. | As a Python code analyst, you investigate and solve complex coding mysteries |
def _append_data(self, value, _file):
"""Call this function to write data contents.
Keyword arguments:
* value - dict, content to be dumped
* _file - FileIO, output file
"""
# binascii.b2a_base64(value) -> plistlib.Data
# binascii.a2b_base64(Data) -> val... | Can you create a Python 3 function that
appends data to the end of the list. | As a python code expert, you are capable of creating scripts from specifications. |
Write the date contents of the object to the file. | Make a summary of the following Python 3 code
def _append_date(self, value, _file):
_tabs = '\t' * self._tctr
_text = value.strftime('%Y-%m-%dT%H:%M:%S.%fZ')
_labs = '{tabs}<date>{text}</date>\n'.format(tabs=_tabs, text=_text)
_file.write(_labs) | You are a Python code generator, capable of creating scripts from specifications. |
def _append_integer(self, value, _file):
"""Call this function to write integer contents.
Keyword arguments:
* value - dict, content to be dumped
* _file - FileIO, output file
"""
_tabs = '\t' * self._tctr
_text = value
_labs = '{tabs}<integer>{t... | Implement a function in Python 3 to
write integer contents to file. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def register_output_name(self, input_folder, rel_name, rel_output_name):
"""Register proper and improper file mappings."""
self.improper_input_file_mapping[rel_name].add(rel_output_name)
self.proper_input_file_mapping[os.path.join(input_folder, rel_name)] = rel_output_name
self.proper_in... | Implement a function in Python 3 to
register proper and improper file mappings. | You are a Python code architect, reviewing and designing scalable and efficient code |
Find and install all extensions | How would you explain what the following Python 3 function does
def _discover(self):
for ep in pkg_resources.iter_entry_points('yamlsettings10'):
ext = ep.load()
if callable(ext):
ext = ext()
self.add(ext) | You are a Python code architect, reviewing and designing scalable and efficient code |
Retrieve the extension for the given protocol | How would you explain what the following Python 3 function does
def get_extension(self, protocol):
if protocol not in self.registry:
raise NoProtocolError("No protocol for %s" % protocol)
index = self.registry[protocol]
return self.extensions[index] | As a Python code translator, you convert algorithms and pseudocode into Python. |
def add(self, extension):
"""Adds an extension to the registry
:param extension: Extension object
:type extension: yamlsettings.extensions.base.YamlSettingsExtension
"""
index = len(self.extensions)
self.extensions[index] = extension
for protocol in extension.pr... | How would you code a function in Python 3 to
add an extension to the registry. | As a python code expert, you are capable of creating scripts from specifications. |
Load first yamldict target found in uri list. | How would you explain what the following Python 3 function does
def _load_first(self, target_uris, load_method, **kwargs):
if isinstance(target_uris, string_types):
target_uris = [target_uris]
# TODO: Move the list logic into the extension, otherwise a
# load will always try all mis... | You are a Python code generator, capable of creating scripts from specifications. |
Load first yamldict target found in uri. | How would you explain what the following Python 3 function does
def load(self, target_uris, fields=None, **kwargs):
yaml_dict = self._load_first(
target_uris, yamlsettings.yamldict.load, **kwargs
)
# TODO: Move this into the extension, otherwise every load from
# a persistant... | You are a Python code architect, reviewing and designing scalable and efficient code |
Load all YAML settings from a list of file paths given. | Can you generate the documentation for the following Python 3 function
def load_all(self, target_uris, **kwargs):
'''
Load *all* YAML settings from a list of file paths given.
- File paths in the list gets the priority by their orders
of the list.
'''
yaml_series... | You are a Python code analyst, evaluating scripts for potential improvements. |
Parse all YAML documents in a stream and produce corresponding YAMLDict objects. | Given the following Python 3 function, write the documentation
def load_all(stream):
loader = YAMLDictLoader(stream)
try:
while loader.check_data():
yield loader.get_data()
finally:
loader.dispose() | As a Python code analyst, you investigate and solve complex coding mysteries |
def dump(data, stream=None, **kwargs):
"""
Serialize YAMLDict into a YAML stream.
If stream is None, return the produced string instead.
"""
return yaml.dump_all(
[data],
stream=stream,
Dumper=YAMLDictDumper,
**kwargs
) | How would you implement a function in Python 3 that
serializes a dictionary into a YAML stream. | As a Python code analyst, you investigate and solve complex coding mysteries |
def dump_all(data_list, stream=None, **kwargs):
"""
Serialize YAMLDict into a YAML stream.
If stream is None, return the produced string instead.
"""
return yaml.dump_all(
data_list,
stream=stream,
Dumper=YAMLDictDumper,
**kwargs
) | Implement a Python 3 function for
serializing a list of data into a YAML stream. | You are a Python code analyst, evaluating scripts for potential improvements. |
def traverse(self, callback):
''' Traverse through all keys and values (in-order)
and replace keys and values with the return values
from the callback function.
'''
def _traverse_node(path, node, callback):
ret_val = callback(path, node)
if ret_val... | Write a Python 3 script for
traversing through all keys and values of the object and replace keys and values with the return values from the callback function. | As a python code expert, you are capable of creating scripts from specifications. |
Update the content of the object with the given YAMLDict. | How would you explain what the following Python 3 function does
def update(self, yaml_dict):
''' Update the content (i.e. keys and values) with yaml_dict.
'''
def _update_node(base_node, update_node):
if isinstance(update_node, YAMLDict) or \
isinstance(update_nod... | As a python code expert, you are capable of creating scripts from specifications. |
Use yaml_dict as self s new base and update with existing
reverse of update. | Explain what the following Python 3 code does
def rebase(self, yaml_dict):
''' Use yaml_dict as self's new base and update with existing
reverse of update.
'''
base = yaml_dict.clone()
base.update(self)
self.clear()
self.update(base) | You are a Python code analyst, evaluating scripts for potential improvements. |
Remove all keys other than the keys specified. | Here you have a function in Python 3, explain what it does
def limit(self, keys):
''' Remove all keys other than the keys specified.
'''
if not isinstance(keys, list) and not isinstance(keys, tuple):
keys = [keys]
remove_keys = [k for k in self.keys() if k not in keys]
... | You are a Python code generator, capable of creating scripts from specifications. |
Save YAML settings to the specified file path. | Make a summary of the following Python 3 code
def save(yaml_dict, filepath):
'''
Save YAML settings to the specified file path.
'''
yamldict.dump(yaml_dict, open(filepath, 'w'), default_flow_style=False) | You are a Python code architect, reviewing and designing scalable and efficient code |
def save_all(yaml_dicts, filepath):
'''
Save *all* YAML settings to the specified file path.
'''
yamldict.dump_all(yaml_dicts, open(filepath, 'w'),
default_flow_style=False) | Create a Python 3 function for
saving all YAML settings to a file. | As a Python code analyst, you investigate and solve complex coding mysteries |
def update_from_file(yaml_dict, filepaths):
'''
Override YAML settings with loaded values from filepaths.
- File paths in the list gets the priority by their orders of the list.
'''
# load YAML settings with only fields in yaml_dict
yaml_dict.update(registry.load(filepaths, list(yaml_dict))... | Write a Python 3 script for
updating the YAML settings with loaded values from filepaths. | You are a Python code analyst, evaluating scripts for potential improvements. |
Update the YAML settings with values from the environment variables. | Can you tell what is the following Python 3 function doing
def update_from_env(yaml_dict, prefix=None):
'''
Override YAML settings with values from the environment variables.
- The letter '_' is delimit the hierarchy of the YAML settings such
that the value of 'config.databases.local' will be... | As a Python code composer, you craft elegant and concise scripts. |
Draw a line on the current canvas. | Can you generate a brief explanation for the following Python 3 code
def line(x, y, width=0.1):
ctx = _state["ctx"]
ctx.move_to(0, 0)
ctx.line_to(x, y)
ctx.close_path()
# _ctx.set_source_rgb (0.3, 0.2, 0.5)
ctx.set_line_width(width)
ctx.stroke() | As a python code expert, you are capable of creating scripts from specifications. |
Simulate behaviour of from package_name. _version import VERSION and return VERSION. | Here you have a function in Python 3, explain what it does
def find_version(
package_name: str, version_module_name: str = '_version',
version_variable_name: str = 'VERSION') -> str:
"""Simulate behaviour of "from package_name._version import VERSION", and return VERSION."""
version_module = imp... | As a python code expert, you are capable of creating scripts from specifications. |
Find packages to pack. | Make a summary of the following Python 3 code
def find_packages(root_directory: str = '.') -> t.List[str]:
exclude = ['test*', 'test.*'] if ('bdist_wheel' in sys.argv or 'bdist' in sys.argv) else []
packages_list = setuptools.find_packages(root_directory, exclude=exclude)
return packages_list | As a Python code composer, you craft elegant and concise scripts. |
Read contents of requirements. txt file and return data from relevant lines. | Given the following Python 3 function, write the documentation
def parse_requirements(
requirements_path: str = 'requirements.txt') -> t.List[str]:
"""Read contents of requirements.txt file and return data from its relevant lines.
Only non-empty and non-comment lines are relevant.
"""
requireme... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Given a list of version number classifiers find version number classifiers in given list and partition them into 2 groups. | Can you generate the documentation for the following Python 3 function
def partition_version_classifiers(
classifiers: t.Sequence[str], version_prefix: str = 'Programming Language :: Python :: ',
only_suffix: str = ' :: Only') -> t.Tuple[t.List[str], t.List[str]]:
"""Find version number classifiers ... | You are a Python code architect, reviewing and designing scalable and efficient code |
def find_required_python_version(
classifiers: t.Sequence[str], version_prefix: str = 'Programming Language :: Python :: ',
only_suffix: str = ' :: Only') -> t.Optional[str]:
"""Determine the minimum required Python version."""
versions_min, versions_only = partition_version_classifiers(
... | Write a Python 3 function for
determining the minimum required Python version. | You are a Python code generator, capable of creating scripts from specifications. |
Parse text assuming it s an RST markup. | Explain what the following Python 3 code does
def parse_rst(text: str) -> docutils.nodes.document:
parser = docutils.parsers.rst.Parser()
components = (docutils.parsers.rst.Parser,)
settings = docutils.frontend.OptionParser(components=components).get_default_values()
document = docutils.utils.new_docume... | You are a Python code analyst, evaluating scripts for potential improvements. |
Resolve all relative links in a given RST document. | Can you tell what is the following Python 3 function doing
def resolve_relative_rst_links(text: str, base_link: str):
document = parse_rst(text)
visitor = SimpleRefCounter(document)
document.walk(visitor)
for target in visitor.references:
name = target.attributes['name']
uri = target.att... | As a python code expert, you are capable of creating scripts from specifications. |
def visit_reference(self, node: docutils.nodes.reference) -> None:
"""Called for "reference" nodes."""
# if len(node.children) != 1 or not isinstance(node.children[0], docutils.nodes.Text) \
# or not all(_ in node.attributes for _ in ('name', 'refuri')):
# return
path... | Create a Python 3 function to
call for reference nodes. | You are a Python code analyst, evaluating scripts for potential improvements. |
Try to find first existing of given class field names. | Can you generate a brief explanation for the following Python 3 code
def try_fields(cls, *names) -> t.Optional[t.Any]:
for name in names:
if hasattr(cls, name):
return getattr(cls, name)
raise AttributeError((cls, names)) | You are a Python code architect, reviewing and designing scalable and efficient code |
Parse a README file and return its contents as a string. | Here you have a function in Python 3, explain what it does
def parse_readme(cls, readme_path: str = 'README.rst', encoding: str = 'utf-8') -> str:
with HERE.joinpath(readme_path).open(encoding=encoding) as readme_file:
long_description = readme_file.read() # type: str
if readme_path.endswi... | You are a Python code architect, reviewing and designing scalable and efficient code |
def prepare(cls) -> None:
"""Fill in possibly missing package metadata."""
if cls.version is None:
cls.version = find_version(cls.name)
if cls.long_description is None:
cls.long_description = cls.parse_readme()
if cls.packages is None:
cls.packages = f... | Can you create a Python 3 function that
fills in possibly missing package metadata. | You are a Python code architect, reviewing and designing scalable and efficient code |
def setup(cls) -> None:
"""Run setuptools.setup() with correct arguments."""
cls.prepare()
setuptools.setup(
name=cls.name, version=cls.version, description=cls.description,
long_description=cls.long_description, url=cls.url, download_url=cls.download_url,
aut... | How would you implement a function in Python 3 that
runs setuptools. setup with correct arguments. | As a python code expert, you are capable of creating scripts from specifications. |
Renders current buffer surface to IPython image | Can you tell what is the following Python 3 function doing
def surface_to_image(surface):
from IPython.display import Image
buf = BytesIO()
surface.write_to_png(buf)
data = buf.getvalue()
buf.close()
return Image(data=data) | You are a Python code generator, capable of creating scripts from specifications. |
Returns a numpy array representing the RGB picture. | Can you tell what is the following Python 3 function doing
def get_npimage(transparent=False, y_origin="top"):
image_surface = render_record_surface()
img = 0 + np.frombuffer(image_surface.get_data(), np.uint8)
img.shape = (HEIGHT, WIDTH, 4)
img = img[:, :, [2, 1, 0, 3]]
if y_origin == "bottom":
... | As a python code expert, you are capable of creating scripts from specifications. |
def check_limits(user_rule):
"""Stop recursion if resolution is too low on number of components is too high """
def wrapper(*args, **kwargs):
"""The body of the decorator """
global _state
_state["cnt_elements"] += 1
_state["depth"] += 1
matrix = _state["ctx"].get_matrix... | Write a Python 3 script for
stopping recursion if resolution is too low on number of components is too high on number of components is too high | You are a Python code analyst, evaluating scripts for potential improvements. |
def init(canvas_size=(512, 512), max_depth=12, face_color=None, background_color=None):
"""Initializes global state"""
global _background_color
_background_color = background_color
global _ctx
global cnt_elements
global MAX_DEPTH
global WIDTH
global HEIGHT
_init_state()
sys.setr... | How would you code a function in Python 3 to
initialize the base state of the base class. | As a Python code translator, you convert algorithms and pseudocode into Python. |
function to convert HTML - styly color string to RGB values | Given the following Python 3 function, write the documentation
def htmlcolor_to_rgb(str_color):
if not (str_color.startswith('#') and len(str_color) == 7):
raise ValueError("Bad html color format. Expected: '#RRGGBB' ")
result = [1.0 * int(n, 16) / 255 for n in (str_color[1:3], str_color[3:5], str_color... | As a Python code composer, you craft elegant and concise scripts. |
def compile_string(self, data, source_path=None, is_two_file=True, post=None, lang=None):
"""Compile docstrings into HTML strings, with shortcode support."""
if not is_two_file:
_, data = self.split_metadata(data, None, lang)
new_data, shortcodes = sc.extract_shortcodes(data)
... | Implement a function in Python 3 to
compile docstrings into HTML strings with shortcode support. | As a Python code composer, you craft elegant and concise scripts. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.