output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
Check if enough time has elapsed to perform a sync. | Explain what the following Python 3 code does
def needs_sync(self):
if self.lastforce is None:
self.lastforce = time.time()
return time.time() - self.lastforce >= self.forceipchangedetection_sleep | As a Python code analyst, you investigate and solve complex coding mysteries |
def check(self):
"""
Check if the detector changed and call sync() accordingly.
If the sleep time has elapsed, this method will see if the attached
detector has had a state change and call sync() accordingly.
"""
if self.needs_check():
if self.has_state_chang... | Implement a Python 3 function for
checking if the detector has changed and call sync if it has changed. | As a Python code composer, you craft elegant and concise scripts. |
Parse response text like the one returned by http://jsonip. com /. | Given the following Python 3 function, write the documentation
def _parser_jsonip(text):
import json
try:
return str(json.loads(text).get("ip"))
except ValueError as exc:
LOG.debug("Text '%s' could not be parsed", exc_info=exc)
return None | As a Python code analyst, you investigate and solve complex coding mysteries |
def detect(self):
"""
Try to contact a remote webservice and parse the returned output.
Determine the IP address from the parsed output and return.
"""
if self.opts_url and self.opts_parser:
url = self.opts_url
parser = self.opts_parser
else:
... | Implement a Python 3 function for
trying to contact a remote webservice and parse the returned output and return the IP address. | You are a Python code architect, reviewing and designing scalable and efficient code |
Add a plugin to the list of plugins. | Can you tell what is the following Python 3 function doing
def add_plugin(self, plugin, call):
meth = getattr(plugin, call, None)
if meth is not None:
self.plugins.append((plugin, meth)) | You are a Python code architect, reviewing and designing scalable and efficient code |
Call each plugin sequentially. | Make a summary of the following Python 3 code
def listcall(self, *arg, **kw):
final_result = None
for _, meth in self.plugins:
result = meth(*arg, **kw)
if final_result is None and result is not None:
final_result = result
return final_result | As a Python code composer, you craft elegant and concise scripts. |
Add the given plugin to the internal list of plugins. | Can you generate the documentation for the following Python 3 function
def add_plugin(self, plugin):
# allow plugins loaded via entry points to override builtin plugins
new_name = self.plugin_name(plugin)
self._plugins[:] = [p for p in self._plugins
if self.plugin_nam... | You are a Python code generator, capable of creating scripts from specifications. |
def configure(self, args):
"""Configure the set of plugins with the given args.
After configuration, disabled plugins are removed from the plugins list.
"""
for plug in self._plugins:
plug_name = self.plugin_name(plug)
plug.enabled = getattr(args, "plugin_%s" % p... | Write a Python 3 script for
configuring the set of plugins with the given args. | As a Python code composer, you craft elegant and concise scripts. |
Register commandline options with the given parser. | Can you generate a brief explanation for the following Python 3 code
def options(self, parser, env):
def get_help(plug):
"""Extract the help docstring from the given plugin."""
import textwrap
if plug.__class__.__doc__:
# doc sections are often indented; compr... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def load_plugins(self):
"""Load plugins from entry point(s)."""
from pkg_resources import iter_entry_points
seen = set()
for entry_point in self.entry_points:
for ep in iter_entry_points(entry_point):
if ep.name in seen:
continue
... | Can you implement a function in Python 3 that
loads plugins from entry point ( s ). | As a Python code translator, you convert algorithms and pseudocode into Python. |
def load_plugins(self):
"""Load plugins from `dyndnsc.plugins.builtin`."""
from dyndnsc.plugins.builtin import PLUGINS
for plugin in PLUGINS:
self.add_plugin(plugin())
super(BuiltinPluginManager, self).load_plugins() | Write a Python 3 function that can
load plugins from dyndnsc. plugins. builtin. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Update the IP on the remote service. | Can you generate a brief explanation for the following Python 3 code
def update(self, ip):
return self.handler.update_record(name=self._recordname,
address=ip) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Load config file and set prefix. | Can you generate a brief explanation for the following Python 3 code
def load(self):
try:
with open(self.config_file) as configfile:
self.config = yaml.load(configfile)
except TypeError:
# no config file (use environment variables)
pass
if self... | You are a Python code generator, capable of creating scripts from specifications. |
Retrieve a config var. | Given the following Python 3 function, write the documentation
def get(self, var, section=None, **kwargs):
# default is not a specified keyword argument so we can distinguish
# between a default set to None and no default sets
if not section and self.section:
section = self.section
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Provide dict like keys method | Make a summary of the following Python 3 code
def keys(self, section=None):
if not section and self.section:
section = self.section
config = self.config.get(section, {}) if section else self.config
return config.keys() | As a Python code analyst, you investigate and solve complex coding mysteries |
def items(self, section=None):
"""Provide dict like items method"""
if not section and self.section:
section = self.section
config = self.config.get(section, {}) if section else self.config
return config.items() | Implement a function in Python 3 to
provide dict like items method | As a Python code translator, you convert algorithms and pseudocode into Python. |
Provide dict like values method | How would you explain what the following Python 3 function does
def values(self, section=None):
if not section and self.section:
section = self.section
config = self.config.get(section, {}) if section else self.config
return config.values() | As a python code expert, you are capable of creating scripts from specifications. |
def _get_filepath(self, filename=None, config_dir=None):
"""
Get config file.
:param filename: name of config file (not path)
:param config_dir: dir name prepended to file name.
Note: we use e.g. GBR_CONFIG_DIR here, this is the default
value in GBR but it is ac... | Can you create a Python 3 function that
gets filepath of the config file. | As a python code expert, you are capable of creating scripts from specifications. |
Update the IP on the remote service. | Can you generate the documentation for the following Python 3 function
def update(self, ip):
timeout = 60
LOG.debug("Updating '%s' to '%s' at service '%s'", self.hostname, ip, self._updateurl)
params = {"domains": self.hostname.partition(".")[0], "token": self.__token}
if ip is None:
... | As a python code expert, you are capable of creating scripts from specifications. |
Resolve hostname to one or more IP addresses through the operating system. | Can you generate a brief explanation for the following Python 3 code
def resolve(hostname, family=AF_UNSPEC):
af_ok = (AF_INET, AF_INET6)
if family != AF_UNSPEC and family not in af_ok:
raise ValueError("Invalid family '%s'" % family)
ips = ()
try:
addrinfo = socket.getaddrinfo(hostname,... | You are a Python code generator, capable of creating scripts from specifications. |
Resolve the hostname to an IP address through the operating system. | Given the following Python 3 function, write the documentation
def detect(self):
theip = next(iter(resolve(self.opts_hostname, self.opts_family)), None)
self.set_current_value(theip)
return theip | You are a Python code generator, capable of creating scripts from specifications. |
Write a human readable list of available presets to out. | Can you generate a brief explanation for the following Python 3 code
def list_presets(cfg, out=sys.stdout):
for section in cfg.sections():
if section.startswith("preset:"):
out.write((section.replace("preset:", "")) + os.linesep)
for k, v in cfg.items(section):
out.wr... | As a Python code composer, you craft elegant and concise scripts. |
def run_forever(dyndnsclients):
"""
Run an endless loop accross the give dynamic dns clients.
:param dyndnsclients: list of DynDnsClients
"""
while True:
try:
# Do small sleeps in the main loop, needs_check() is cheap and does
# the rest.
time.sleep(15)
... | Create a Python 3 function for
running an endless loop accross the give dynamic dns clients. | You are a Python code generator, capable of creating scripts from specifications. |
def main():
"""
Run the main CLI program.
Initializes the stack, parses command line arguments, and fires requested
logic.
"""
plugins = DefaultPluginManager()
plugins.load_plugins()
parser, _ = create_argparser()
# add the updater protocol options to the CLI:
for kls in update... | Can you write a function in Python 3 where it
runs the main CLI program. Initializes the stack, parses command line arguments, and fires requested logic. | You are a Python code analyst, evaluating scripts for potential improvements. |
def tidy_ssh_user(url=None, user=None):
"""make sure a git repo ssh:// url has a user set"""
if url and url.startswith('ssh://'):
# is there a user already ?
match = re.compile('ssh://([^@]+)@.+').match(url)
if match:
ssh_user = match.group(1)
if user and ssh_user... | Write a Python 3 script to
make sure a git repo ssh:// url has a user set | You are a Python code generator, capable of creating scripts from specifications. |
Return the value of a git configuration option. This will
return the value of the default parameter. | Explain what the following Python 3 code does
def config_get(self, param, default=None):
'''Return the value of a git configuration option. This will
return the value of the default parameter (which defaults to
None) if the given option does not exist.'''
try:
return self("... | You are a Python code generator, capable of creating scripts from specifications. |
def get_configuration(config_file=None):
"""Return an initialized ConfigParser.
If no config filename is presented, `DEFAULT_USER_INI` is used if present.
Also reads the built-in presets.
:param config_file: string path
"""
parser = configparser.ConfigParser()
if config_file is None:
... | How would you implement a function in Python 3 that
returns an initialized ConfigParser. | You are a Python code generator, capable of creating scripts from specifications. |
Generator for client_name client_cfg_dict | Explain what the following Python 3 code does
def _iraw_client_configs(cfg):
client_names = cfg.get("dyndnsc", "configs").split(",")
_preset_prefix = "preset:"
_use_preset = "use_preset"
for client_name in (x.strip() for x in client_names if x.strip()):
client_cfg_dict = dict(cfg.items(client_na... | You are a Python code generator, capable of creating scripts from specifications. |
def collect_config(cfg):
"""
Construct configuration dictionary from configparser.
Resolves presets and returns a dictionary containing:
.. code-block:: bash
{
"client_name": {
"detector": ("detector_name", detector_opts),
"updater": [
... | Write a Python 3 script to
collect the configuration dictionary from configparser. ConfigParser and returns a dictionary containing the relevant configuration values. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Detect and return the IP address. | Can you generate the documentation for the following Python 3 function
def detect(self):
if PY3: # py23
import subprocess # noqa: S404 @UnresolvedImport pylint: disable=import-error
else:
import commands as subprocess # @UnresolvedImport pylint: disable=import-error
tr... | As a Python code composer, you craft elegant and concise scripts. |
Find the publicly visible IP address of the current system. | Explain what the following Python 3 code does
def find_ip(family=AF_INET, flavour="opendns"):
flavours = {
"opendns": {
AF_INET: {
"@": ("resolver1.opendns.com", "resolver2.opendns.com"),
"qname": "myip.opendns.com",
"rdtype": "A",
},
... | As a python code expert, you are capable of creating scripts from specifications. |
def detect(self):
"""
Detect the WAN IP of the current process through DNS.
Depending on the 'family' option, either ipv4 or ipv6 resolution is
carried out.
:return: ip address
"""
theip = find_ip(family=self.opts_family)
self.set_current_value(theip)
... | Write a Python 3 function that can
detect the WAN IP of the current process through DNS. | You are a Python code architect, reviewing and designing scalable and efficient code |
def set_current_value(self, value):
"""Set the detected IP in the current run (if any)."""
self._oldvalue = self.get_current_value()
self._currentvalue = value
if self._oldvalue != value:
# self.notify_observers("new_ip_detected", {"ip": value})
LOG.debug("%s.set_... | Can you create a Python 3 function that
sets the detected IP in the current run ( if any. | As a Python code analyst, you investigate and solve complex coding mysteries |
Parse all updater and detector related arguments from args. | Make a summary of the following Python 3 code
def parse_cmdline_args(args, classes):
if args is None:
raise ValueError("args must not be None")
parsed_args = {}
for kls in classes:
prefix = kls.configuration_key_prefix()
name = kls.configuration_key
if getattr(args, "%s_%s" %... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def register_arguments(cls, parser):
"""Register command line options.
Implement this method for normal options behavior with protection from
OptionConflictErrors. If you override this method and want the default
--$name option(s) to be registered, be sure to call super().
"""
... | Write a Python 3 script for
registering command line options. | You are a Python code architect, reviewing and designing scalable and efficient code |
Tag the local_patches_branch with this package s NVR. | How would you explain what the following Python 3 function does
def tag_patches_branch(package, local_patches_branch, patches_branch,
force=False, push=False):
""" Tag the local_patches_branch with this package's NVR. """
vr = specfile.Spec().get_vr(epoch=False)
nvr_tag = package + '-... | As a Python code analyst, you investigate and solve complex coding mysteries |
Load a class from a module. | Can you generate a brief explanation for the following Python 3 code
def load_class(module_name, class_name):
try:
plugmod = import_module(module_name)
except Exception as exc:
warn("Importing built-in plugin %s.%s raised an exception: %r" %
(module_name, class_name, repr(exc)), Imp... | You are a Python code generator, capable of creating scripts from specifications. |
Return class in classes identified by configuration key name. | Can you generate the documentation for the following Python 3 function
def find_class(name, classes):
name = name.lower()
cls = next((c for c in classes if c.configuration_key == name), None)
if cls is None:
raise ValueError("No class named '%s' could be found" % name)
return cls | As a python code expert, you are capable of creating scripts from specifications. |
Convert to snakecase removing non alpha numerics
Word | Make a summary of the following Python 3 code
def alphasnake(string):
if string:
string = " ".join(
[re.sub(r'\W+', '', word) for word in string.split()]
)
string = decamel_to_snake(string)
return string | You are a Python code analyst, evaluating scripts for potential improvements. |
def decamel(string):
""""Split CamelCased words.
CamelCase -> Camel Case, dromedaryCase -> dromedary Case.
"""
regex = re.compile(r'(\B[A-Z][a-z]*)')
return regex.sub(r' \1', string) | Can you implement a function in Python 3 that
splits CamelCased words. CamelCase -> Camel Case dromedaryCase -> dromedary Case | You are a Python code architect, reviewing and designing scalable and efficient code |
def decamel_to_snake(string):
"""Convert to lower case, join camel case with underscore.
CamelCase -> camel_case. Camel Case -> camel_case.
"""
strings = [decamel(word) if not word.isupper() else word.lower()
for word in string.split()]
return "_".join([snake(dstring)for dstring in st... | Create a Python 3 function for
converting to lower case join camel case with underscore. | As a Python code composer, you craft elegant and concise scripts. |
def info_file(distro=None):
"""Return default distroinfo info file"""
if not distro:
distro = cfg['DISTRO']
info_file_conf = distro.upper() + 'INFO_FILE'
try:
return cfg[info_file_conf]
except KeyError:
raise exception.InvalidUsage(
why="Couldn't find config optio... | Can you create a Python 3 function that
returns default distroinfo info file | You are a Python code analyst, evaluating scripts for potential improvements. |
Get DistroInfo initialized from configuration | Explain what the following Python 3 code does
def get_distroinfo(distro=None):
if not distro:
distro = cfg['DISTRO']
_info_file = info_file(distro)
# prefer git fetcher if available
git_info_url_conf = distro.upper() + 'INFO_REPO'
try:
remote_git_info = cfg[git_info_url_conf]
... | As a python code expert, you are capable of creating scripts from specifications. |
This function splits a rpm filename into name version epoch and arch. | Can you generate a brief explanation for the following Python 3 code
def split_filename(filename):
# Remove .rpm suffix
if filename.endswith('.rpm'):
filename = filename.split('.rpm')[0]
# is there an epoch?
components = filename.split(':')
if len(components) > 1:
epoch = component... | As a Python code analyst, you investigate and solve complex coding mysteries |
def string_to_version(verstring):
"""
Return a tuple of (epoch, version, release) from a version string
This function replaces rpmUtils.miscutils.stringToVersion, see
https://bugzilla.redhat.com/1364504
"""
# is there an epoch?
components = verstring.split(':')
if len(components) > 1:
... | Can you write a function in Python 3 where it
returns a tuple of epoch version and release from a version string | As a Python code analyst, you investigate and solve complex coding mysteries |
Return the filename for a. spec file in this directory. | Can you generate the documentation for the following Python 3 function
def spec_fn(spec_dir='.'):
specs = [f for f in os.listdir(spec_dir)
if os.path.isfile(f) and f.endswith('.spec')]
if not specs:
raise exception.SpecFileNotFound()
if len(specs) != 1:
raise exception.MultipleS... | You are a Python code architect, reviewing and designing scalable and efficient code |
Split a version string into numeric X. Y. Z part and the rest. | Can you generate a brief explanation for the following Python 3 code
def version_parts(version):
m = re.match(r'(\d+(?:\.\d+)*)([.%]|$)(.*)', version)
if m:
numver = m.group(1)
rest = m.group(2) + m.group(3)
return numver, rest
else:
return version, '' | You are a Python code analyst, evaluating scripts for potential improvements. |
def release_parts(version):
"""
Split RPM Release string into (numeric X.Y.Z part, milestone, rest).
:returns: a three-element tuple (number, milestone, rest). If we cannot
determine the "milestone" or "rest", those will be an empty
string.
"""
numver, tail = version_par... | Can you create a Python 3 function that
splits RPM Release string into number milestone and rest. | You are a Python code generator, capable of creating scripts from specifications. |
def get_magic_comment(self, name, expand_macros=False):
"""Return a value of # name=value comment in spec or None."""
match = re.search(r'^#\s*?%s\s?=\s?(\S+)' % re.escape(name),
self.txt, flags=re.M)
if not match:
return None
val = match.group(1)
... | Write a Python 3 script to
return a value of name = value comment in spec or None. | As a Python code composer, you craft elegant and concise scripts. |
Return a tuple of version number_of_commits that are parsed
from the patches_base in the specfile. | Explain what the following Python 3 code does
def get_patches_base(self, expand_macros=False):
match = re.search(r'(?<=patches_base=)[\w.+?%{}]+', self.txt)
if not match:
return None, 0
patches_base = match.group()
if expand_macros and has_macros(patches_base):
#... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_patches_ignore_regex(self):
"""Returns a string representing a regex for filtering out patches
This string is parsed from a comment in the specfile that contains the
word filter-out followed by an equal sign.
For example, a comment as such:
# patches_ignore=(regex)
... | How would you code a function in Python 3 to
return a string representing a regex for filtering out patches | As a Python code composer, you craft elegant and concise scripts. |
Check if this release value is something we can parse. | Can you tell what is the following Python 3 function doing
def recognized_release(self):
_, _, rest = self.get_release_parts()
# If "rest" is not a well-known value here, then this package is
# using a Release value pattern we cannot recognize.
if rest == '' or re.match(r'%{\??dist}', re... | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_vr(self, epoch=None):
"""get VR string from .spec Version, Release and Epoch
epoch is None: prefix epoch if present (default)
epoch is True: prefix epoch even if not present (0:)
epoch is False: omit epoch even if present
"""
version = self.get_tag('Version', exp... | Write a Python 3 script to
get VR string from. spec Version Release and Epoch | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_nvr(self, epoch=None):
"""get NVR string from .spec Name, Version, Release and Epoch"""
name = self.get_tag('Name', expand_macros=True)
vr = self.get_vr(epoch=epoch)
return '%s-%s' % (name, vr) | Create a Python 3 function for
getting NVR string from. spec Name Version Release and Epoch | As a Python code analyst, you investigate and solve complex coding mysteries |
def save(self):
""" Write the textual content (self._txt) to .spec file (self.fn). """
if not self.txt:
# no changes
return
if not self.fn:
raise exception.InvalidAction(
"Can't save .spec file without its file name specified.")
f = cod... | Can you write a function in Python 3 where it
writes the textual content to the. spec file. | As a python code expert, you are capable of creating scripts from specifications. |
def detect_ip(kind):
"""
Detect IP address.
kind can be:
IPV4 - returns IPv4 address
IPV6_ANY - returns any IPv6 address (no preference)
IPV6_PUBLIC - returns public IPv6 address
IPV6_TMP - returns temporary IPV6 address (privacy extensions)
This function either returns... | How would you implement a function in Python 3 that
detects the IP address of a specific kind of IPv4 or IPv6 address. | As a Python code analyst, you investigate and solve complex coding mysteries |
Setup koji client session | Here you have a function in Python 3, explain what it does
def setup_kojiclient(profile):
opts = koji.read_config(profile)
for k, v in opts.iteritems():
opts[k] = os.path.expanduser(v) if type(v) is str else v
kojiclient = koji.ClientSession(opts['server'], opts=opts)
kojiclient.ssl_login(opts['... | You are a Python code analyst, evaluating scripts for potential improvements. |
Retrieve sources using spectool
| Make a summary of the following Python 3 code
def retrieve_sources():
spectool = find_executable('spectool')
if not spectool:
log.warn('spectool is not installed')
return
try:
specfile = spec_fn()
except Exception:
return
cmd = [spectool, "-g", specfile]
output =... | You are a Python code architect, reviewing and designing scalable and efficient code |
Create an srpm file for the current package. | How would you explain what the following Python 3 function does
def create_srpm(dist='el7'):
if not RPM_AVAILABLE:
raise RpmModuleNotAvailable()
path = os.getcwd()
try:
specfile = spec_fn()
spec = Spec(specfile)
except Exception:
return
rpmdefines = ["--define 'dist ... | As a Python code composer, you craft elegant and concise scripts. |
Compute the authentication key for freedns. afraid. org. | Given the following Python 3 function, write the documentation
def compute_auth_key(userid, password):
import sys
if sys.version_info >= (3, 0):
return hashlib.sha1(b"|".join((userid.encode("ascii"), # noqa: S303
password.encode("ascii")))).hexdigest()
return ... | As a Python code analyst, you investigate and solve complex coding mysteries |
def records(credentials, url="https://freedns.afraid.org/api/"):
"""
Yield the dynamic DNS records associated with this account.
:param credentials: an AfraidCredentials instance
:param url: the service URL
"""
params = {"action": "getdyndns", "sha": credentials.sha}
req = requests.get(
... | Create a Python 3 function to
yield the dynamic DNS records associated with this account. | As a python code expert, you are capable of creating scripts from specifications. |
def update(url):
"""
Update remote DNS record by requesting its special endpoint URL.
This automatically picks the IP address using the HTTP connection: it is not
possible to specify the IP address explicitly.
:param url: URL to retrieve for triggering the update
:return: IP address
"""
... | Create a Python 3 function to
update the remote DNS record by requesting its special endpoint URL. | You are a Python code architect, reviewing and designing scalable and efficient code |
def sha(self):
"""Return sha, lazily compute if not done yet."""
if self._sha is None:
self._sha = compute_auth_key(self.userid, self.password)
return self._sha | How would you implement a function in Python 3 that
returns sha of the user s user. | You are a Python code architect, reviewing and designing scalable and efficient code |
def update(self, *args, **kwargs):
"""Update the IP on the remote service."""
# first find the update_url for the provided account + hostname:
update_url = next((r.update_url for r in
records(self._credentials, self._url)
if r.hostname == sel... | Implement a Python 3 function for
updating the IP on the remote service. | As a Python code analyst, you investigate and solve complex coding mysteries |
Register a listener function. | How would you explain what the following Python 3 function does
def register_observer(self, observer, events=None):
if events is not None and not isinstance(events, (tuple, list)):
events = (events,)
if observer in self._observers:
LOG.warning("Observer '%r' already registered, ... | You are a Python code generator, capable of creating scripts from specifications. |
Notify observers of a specific event. | Explain what the following Python 3 code does
def notify_observers(self, event=None, msg=None):
for observer, events in list(self._observers.items()):
# LOG.debug("trying to notify the observer")
if events is None or event is None or event in events:
try:
... | You are a Python code generator, capable of creating scripts from specifications. |
def detect(self):
"""Detect the IP address."""
if self.opts_family == AF_INET6:
kind = IPV6_PUBLIC
else: # 'INET':
kind = IPV4
theip = None
try:
theip = detect_ip(kind)
except GetIpException:
LOG.exception("socket detector ... | Can you write a function in Python 3 where it
detects the IP address. | As a python code expert, you are capable of creating scripts from specifications. |
def _detect(self):
"""Use the netifaces module to detect ifconfig information."""
theip = None
try:
if self.opts_family == AF_INET6:
addrlist = netifaces.ifaddresses(self.opts_iface)[netifaces.AF_INET6]
else:
addrlist = netifaces.ifaddresse... | Create a Python 3 function for
using the netifaces module to detect ifconfig information. | As a Python code analyst, you investigate and solve complex coding mysteries |
def clean_tempdir(context, scenario):
"""
Clean up temporary test dirs for passed tests.
Leave failed test dirs for manual inspection.
"""
tempdir = getattr(context, 'tempdir', None)
if tempdir and scenario.status == 'passed':
shutil.rmtree(tempdir)
del(context.tempdir) | Implement a Python 3 function for
cleaning up temporary test dirs for passed tests. | You are a Python code analyst, evaluating scripts for potential improvements. |
def is_reserved_ip(self, ip):
"""Check if the given ip address is in a reserved ipv4 address space.
:param ip: ip address
:return: boolean
"""
theip = ipaddress(ip)
for res in self._reserved_netmasks:
if theip in ipnetwork(res):
return True
... | Can you implement a function in Python 3 that
checks if the given ip address is in a reserved ipv4 address space. | As a python code expert, you are capable of creating scripts from specifications. |
Return a randomly generated public IPv4 address. | Make a summary of the following Python 3 code
def random_public_ip(self):
randomip = random_ip()
while self.is_reserved_ip(randomip):
randomip = random_ip()
return randomip | You are a Python code analyst, evaluating scripts for potential improvements. |
def detect(self):
"""Detect IP and return it."""
for theip in self.rips:
LOG.debug("detected %s", str(theip))
self.set_current_value(str(theip))
return str(theip) | Can you create a Python 3 function that
detects IP and return it. | As a Python code composer, you craft elegant and concise scripts. |
def update(self, ip):
"""Update the IP on the remote service."""
timeout = 60
LOG.debug("Updating '%s' to '%s' at service '%s'", self.hostname, ip, self._updateurl)
params = {"myip": ip, "hostname": self.hostname}
req = requests.get(self._updateurl, params=params, headers=constan... | Implement a function in Python 3 to
update the IP on the remote service. | As a python code expert, you are capable of creating scripts from specifications. |
Return a git reference to the patches branch base. | How would you explain what the following Python 3 function does
def patches_base_ref(default=exception.CantGuess):
ref = None
try:
spec = specfile.Spec()
ref, _ = spec.get_patches_base(expand_macros=True)
if ref:
ref, _ = tag2version(ref)
else:
ref = spec.... | You are a Python code analyst, evaluating scripts for potential improvements. |
Displays a list of items along with the index to enable a user
to select an item. | Can you generate a brief explanation for the following Python 3 code
def display_listitems(items, url):
'''Displays a list of items along with the index to enable a user
to select an item.
'''
if (len(items) == 2 and items[0].get_label() == '..'
and items[1].get_played()):
display_video(... | You are a Python code analyst, evaluating scripts for potential improvements. |
def display_video(items):
'''Prints a message for a playing video and displays the parent
listitem.
'''
parent_item, played_item = items
title_line = 'Playing Media %s (%s)' % (played_item.get_label(),
played_item.get_path())
parent_line = '[0] %s (%s... | Write a Python 3 function for
printing a message for a playing video and displays the parent listitem. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns the selected item from provided items or None if the user has entered quit. | Can you tell what is the following Python 3 function doing
def get_user_choice(items):
'''Returns the selected item from provided items or None if 'q' was
entered for quit.
'''
choice = raw_input('Choose an item or "q" to quit: ')
while choice != 'q':
try:
item = items[int(choice... | As a Python code analyst, you investigate and solve complex coding mysteries |
def decode(data):
"""
Decode data employing some charset detection and including unicode BOM
stripping.
"""
if isinstance(data, unicode):
return data
# Detect standard unicode BOMs.
for bom, encoding in UNICODE_BOMS:
if data.startswith(bom):
return data[len(bom)... | Implement a Python 3 function for
decoding data into a single object. | You are a Python code generator, capable of creating scripts from specifications. |
Returns a tuple containing the context for a line | Make a summary of the following Python 3 code
def get_context(self, line=1, column=0):
'Returns a tuple containing the context for a line'
line -= 1 # The line is one-based
# If there is no data in the file, there can be no context.
datalen = len(self.data)
if datalen <= line:... | You are a Python code architect, reviewing and designing scalable and efficient code |
Formats a line from the data to be the appropriate length | Make a summary of the following Python 3 code
def _format_line(self, data, column=0, rel_line=1):
'Formats a line from the data to be the appropriate length'
line_length = len(data)
if line_length > 140:
if rel_line == 0:
# Trim from the beginning
dat... | As a Python code composer, you craft elegant and concise scripts. |
def get_line(self, position):
'Returns the line number that the given string position is found on'
datalen = len(self.data)
count = len(self.data[0])
line = 1
while count < position:
if line >= datalen:
break
count += len(self.data[line]) ... | Write a Python 3 script to
return the line number that the given string position is found on | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_addon_id(addonxml):
'''Parses an addon id from the given addon.xml filename.'''
xml = parse(addonxml)
addon_node = xml.getElementsByTagName('addon')[0]
return addon_node.getAttribute('id') | Implement a Python 3 function for
parsing an addon id from the given addon. xml filename. | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_addon_name(addonxml):
'''Parses an addon name from the given addon.xml filename.'''
xml = parse(addonxml)
addon_node = xml.getElementsByTagName('addon')[0]
return addon_node.getAttribute('name') | Implement a function in Python 3 to
parse an addon name from the given addon. xml filename. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _create_dir(path):
'''Creates necessary directories for the given path or does nothing
if the directories already exist.
'''
try:
os.makedirs(path)
except OSError, exc:
if exc.errno == errno.EEXIST:
pass
else:
raise | Can you implement a function in Python 3 that
creates necessary directories for the given path or does nothing. | As a python code expert, you are capable of creating scripts from specifications. |
def translatePath(path):
'''Creates folders in the OS's temp directory. Doesn't touch any
possible XBMC installation on the machine. Attempting to do as
little work as possible to enable this function to work seamlessly.
'''
valid_dirs = ['xbmc', 'home', 'temp', 'masterprofile', 'profile',
'... | Implement a function in Python 3 to
translate a path into a valid XBMC file. | As a Python code analyst, you investigate and solve complex coding mysteries |
Handles setup of the plugin state including request
arguments handle mode. | Can you generate a brief explanation for the following Python 3 code
def _parse_request(self, url=None, handle=None):
'''Handles setup of the plugin state, including request
arguments, handle, mode.
This method never needs to be called directly. For testing, see
plugin.test()
''... | You are a Python code generator, capable of creating scripts from specifications. |
Registers a module with a plugin. Requires a url_prefix that is used to register all urls for that module. | Make a summary of the following Python 3 code
def register_module(self, module, url_prefix):
'''Registers a module with a plugin. Requires a url_prefix that
will then enable calls to url_for.
:param module: Should be an instance `xbmcswift2.Module`.
:param url_prefix: A url prefix to us... | As a Python code composer, you craft elegant and concise scripts. |
A decorator to add a route to a view and also apply caching. | Given the following Python 3 function, write the documentation
def cached_route(self, url_rule, name=None, options=None, TTL=None):
'''A decorator to add a route to a view and also apply caching. The
url_rule, name and options arguments are the same arguments for the
route function. The TTL argu... | As a Python code composer, you craft elegant and concise scripts. |
A decorator to add a route to a view. name is used to
differentiate when there are multiple routes for a given view. options is used to
differentiate when there are multiple routes for a given view. | Can you generate the documentation for the following Python 3 function
def route(self, url_rule, name=None, options=None):
'''A decorator to add a route to a view. name is used to
differentiate when there are multiple routes for a given view.'''
# TODO: change options kwarg to defaults
d... | As a Python code analyst, you investigate and solve complex coding mysteries |
def url_for(self, endpoint, **items):
'''Returns a valid XBMC plugin URL for the given endpoint name.
endpoint can be the literal name of a function, or it can
correspond to the name keyword arguments passed to the route
decorator.
Raises AmbiguousUrlException if there is more t... | Write a Python 3 function that can
return a valid XBMC plugin URL for the given endpoint name. | You are a Python code generator, capable of creating scripts from specifications. |
Used when you need to redirect to another view and you only have the final plugin:// url. | Can you generate the documentation for the following Python 3 function
def redirect(self, url):
'''Used when you need to redirect to another view, and you only
have the final plugin:// url.'''
# TODO: Should we be overriding self.request with the new request?
new_request = self._parse_re... | As a Python code analyst, you investigate and solve complex coding mysteries |
The main entry point for a plugin. | Explain what the following Python 3 code does
def run(self, test=False):
'''The main entry point for a plugin.'''
self._request = self._parse_request()
log.debug('Handling incoming request for %s', self.request.path)
items = self._dispatch(self.request.path)
# Close any open sto... | You are a Python code analyst, evaluating scripts for potential improvements. |
The main function of xbcmswift2. | Make a summary of the following Python 3 code
def main():
'''The entry point for the console script xbmcswift2.
The 'xbcmswift2' script is command bassed, so the second argument is always
the command to execute. Each command has its own parser options and usages.
If no command is provided or the -h fla... | As a python code expert, you are capable of creating scripts from specifications. |
def colorize_text(self, text):
"""Adds escape sequences to colorize text and make it
beautiful. To colorize text, prefix the text you want to color
with the color (capitalized) wrapped in double angle brackets
(i.e.: <<GREEN>>). End your string with <<NORMAL>>. If you
don't, it w... | Write a Python 3 script for
adding escape sequences to colorize text and make it beautiful. | As a python code expert, you are capable of creating scripts from specifications. |
def write(self, text):
'Uses curses to print in the fanciest way possible.'
# Add color to the terminal.
if not self.no_color:
text = self.colorize_text(text)
else:
pattern = re.compile('\<\<[A-Z]*?\>\>')
text = pattern.sub('', text)
text += ... | Create a Python 3 function for
using curses to print in the fanciest way possible. | As a Python code analyst, you investigate and solve complex coding mysteries |
Talk to Cleverbot.
Arguments:
input: The input argument is what you want to say to Cleverbot,
such as "hello".
tweak1-3: Changes Cleverbot's mood.
**kwargs: Keyword arguments to update the request parameters with.
Returns:
Cleverbot's rep... | Explain what the following Python 3 code does
def say(self, input=None, **kwargs):
params = self._get_params(input, kwargs)
try:
reply = self.session.get(
self.url, params=params, timeout=self.timeout)
except requests.Timeout:
raise Timeout(self.timeout)
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def live_pidfile(pidfile): # pragma: no cover
"""(pidfile:str) -> int | None
Returns an int found in the named file, if there is one,
and if there is a running process with that process id.
Return None if no such process exists.
"""
pid = read_pidfile(pidfile)
if pid:
try:
... | Implement a Python 3 function for
returning an int found in the named file if there is one and if there is a running process with that process id. | You are a Python code generator, capable of creating scripts from specifications. |
Turn a SIGTERM exception into a SystemExit exception. | Given the following Python 3 function, write the documentation
def _turn_sigterm_into_systemexit(): # pragma: no cover
try:
import signal
except ImportError:
return
def handle_term(signo, frame):
raise SystemExit
signal.signal(signal.SIGTERM, handle_term) | As a Python code analyst, you investigate and solve complex coding mysteries |
This function is the main function for the wsgiref server. | Can you generate the documentation for the following Python 3 function
def wsgiref_server_runner(wsgi_app, global_conf, **kw): # pragma: no cover
from wsgiref.simple_server import make_server, WSGIServer
host = kw.get('host', '0.0.0.0')
port = int(kw.get('port', 8080))
threaded = asbool(kw.get('wsgiref... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def parse_vars(self, args):
"""
Given variables like ``['a=b', 'c=d']`` turns it into ``{'a':
'b', 'c': 'd'}``
"""
result = {}
for arg in args:
if '=' not in arg:
raise ValueError(
'Variable assignment %r invalid (no "=")'
... | Can you implement a function in Python 3 that
parses the given variables like a = b c = d into a dictionary of key = value. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.