text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def as_dict(self):
"""Returns a JSON-serializeable object representing this tree.""" |
def conv(v):
if isinstance(v, SerializableAttributesHolder):
return v.as_dict()
elif isinstance(v, list):
return [conv(x) for x in v]
elif isinstance(v, dict):
return {x:conv(y) for (x,y) in v.items()}
else:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_json(cls, data):
"""Decode a JSON string and inflate a node instance.""" |
# Decode JSON string
assert isinstance(data, str)
data = json.loads(data)
assert isinstance(data, dict)
return cls.from_dict(data) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_keywords(func):
""" Parses the keywords from the given function. :param func | <function> """ |
if hasattr(func, 'im_func'):
func = func.im_func
try:
return func.func_code.co_varnames[-len(func.func_defaults):]
except (TypeError, ValueError, IndexError):
return tuple() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def jtag_enable(self):
""" Enables JTAG output on the controller. JTAG operations executed before this function is called will return useless data or fail. Usage... |
status, _ = self.bulkCommand(_BMSG_ENABLE_JTAG)
if status == 0:
self._jtagon = True
elif status == 3:
self._jtagon = True
raise JTAGAlreadyEnabledError()
else:
raise JTAGEnableFailedError("Error enabling JTAG. Error code: %s." %status) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def jtag_disable(self):
""" Disables JTAG output on the controller. JTAG operations executed immediately after this function will return useless data or fail. Us... |
if not self._jtagon: return
status, _ = self.bulkCommand(_BMSG_DISABLE_JTAG)
if status == 0:
self._jtagon = False
elif status == 3:
raise JTAGControlError("Error Code %s"%status)
self.close_handle() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_tms_tdi_bits(self, tmsdata, tdidata, return_tdo=False):
""" Command controller to write arbitrary TDI and TMS data to the physical scan chain. Optional... |
self._check_jtag()
if len(tmsdata) != len(tdidata):
raise Exception("TMSdata and TDIData must be the same length")
self._update_scanchain(tmsdata)
count = len(tmsdata)
t = time()
outdata = bitarray([val for pair in zip(tmsdata, tdidata)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _readFastaFile(filepath):
"""Read a FASTA file and yields tuples of 'header' and 'sequence' entries. :param filepath: file path of the FASTA file :yields: FA... |
processSequences = lambda i: ''.join([s.rstrip() for s in i]).rstrip('*')
processHeaderLine = lambda line: line[1:].rstrip()
with io.open(filepath) as openfile:
#Iterate through lines until the first header is encountered
try:
line = next(openfile)
while line[0] != '... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fastaParseSgd(header):
"""Custom parser for fasta headers in the SGD format, see www.yeastgenome.org. :param header: str, protein entry header from a fasta f... |
rePattern = '([\S]+)\s([\S]+).+(\".+\")'
ID, name, description = re.match(rePattern, header).groups()
info = {'id':ID, 'name':name, 'description':description}
return info |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save(self, path, compress=True):
"""Writes the ``.proteins`` and ``.peptides`` entries to the hard disk as a ``proteindb`` file. .. note:: If ``.save()`` is ... |
with aux.PartiallySafeReplace() as msr:
filename = self.info['name'] + '.proteindb'
filepath = aux.joinpath(path, filename)
with msr.open(filepath, mode='w+b') as openfile:
self._writeContainer(openfile, compress=compress) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load(cls, path, name):
"""Imports the specified ``proteindb`` file from the hard disk. :param path: filedirectory of the ``proteindb`` file :param name: file... |
filepath = aux.joinpath(path, name + '.proteindb')
with zipfile.ZipFile(filepath, 'r', allowZip64=True) as containerZip:
#Convert the zipfile data into a str object, necessary since
#containerZip.read() returns a bytes object.
proteinsString = io.TextIOWrapper(conta... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch_keywords(codedata) : """ Fetch keywords by shaman.KeywordFetcher Get average probabilities of keyword and language """ |
# Read row in codedata and count keywords in codes with langauge
tmp = {}
language_counts = {}
for index, (language, code) in enumerate(codedata) :
if language not in shaman.SUPPORTING_LANGUAGES :
continue
if language not in tmp :
tmp[language] = {}
language_counts[language] = 0
language_counts[... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def match_patterns(codedata) : """ Match patterns by shaman.PatternMatcher Get average ratio of pattern and language """ |
ret = {}
for index1, pattern in enumerate(shaman.PatternMatcher.PATTERNS) :
print('Matching pattern %d "%s"' % (index1+1, pattern))
matcher = shaman.PatternMatcher(pattern)
tmp = {}
for index2, (language, code) in enumerate(codedata) :
if language not in shaman.SUPPORTING_LANGUAGES :
continue
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def facility(self, column=None, value=None, **kwargs):
""" Check information related to Radiation facilities. """ |
return self._resolve_call('RAD_FACILITY', column, value, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def geo(self, column=None, value=None, **kwargs):
""" Locate a facility through geographic location. """ |
return self._resolve_call('RAD_GEO_LOCATION', column, value, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def regulation(self, column=None, value=None, **kwargs):
""" Provides relevant information about applicable regulations. """ |
return self._resolve_call('RAD_REGULATION', column, value, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def regulatory_program(self, column=None, value=None, **kwargs):
""" Identifies the regulatory authority governing a facility, and, by virtue of that identificat... |
return self._resolve_call('RAD_REGULATORY_PROG', column,
value, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def collect_basic_info():
""" """ |
s = sys.version_info
_collect(json.dumps({'sys.version_info':tuple(s)}))
_collect(sys.version)
return sys.version |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def call(function):
""" decorator that collect function call count. """ |
message = 'call:%s.%s' % (function.__module__,function.__name__)
@functools.wraps(function)
def wrapper(*args, **kwargs):
_collect(message)
return function(*args, **kwargs)
return wrapper |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _parse_ip_addr_show(raw_result):
""" Parse the 'ip addr list dev' command raw output. :param str raw_result: os raw result string. :rtype: dict :return: The ... |
# does link exist?
show_re = (
r'"(?P<dev>\S+)"\s+does not exist'
)
re_result = search(show_re, raw_result)
result = None
if not (re_result):
# match top two lines for serveral 'always there' variables
show_re = (
r'\s*(?P<os_index>\d+):\s+(?P<dev>\S+):\s+<(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def interface(enode, portlbl, addr=None, up=None, shell=None):
""" Configure a interface. All parameters left as ``None`` are ignored and thus no configuration a... |
assert portlbl
port = enode.ports[portlbl]
if addr is not None:
assert ip_interface(addr)
cmd = 'ip addr add {addr} dev {port}'.format(addr=addr, port=port)
response = enode(cmd, shell=shell)
assert not response
if up is not None:
cmd = 'ip link set dev {port} ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_ip(enode, portlbl, addr, shell=None):
""" Remove an IP address from an interface. All parameters left as ``None`` are ignored and thus no configuratio... |
assert portlbl
assert ip_interface(addr)
port = enode.ports[portlbl]
cmd = 'ip addr del {addr} dev {port}'.format(addr=addr, port=port)
response = enode(cmd, shell=shell)
assert not response |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_route(enode, route, via, shell=None):
""" Add a new static route. :param enode: Engine node to communicate with. :type enode: topology.platforms.base.Bas... |
via = ip_address(via)
version = '-4'
if (via.version == 6) or \
(route != 'default' and ip_network(route).version == 6):
version = '-6'
cmd = 'ip {version} route add {route} via {via}'.format(
version=version, route=route, via=via
)
response = enode(cmd, shell=she... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_link_type_vlan(enode, portlbl, name, vlan_id, shell=None):
""" Add a new virtual link with the type set to VLAN. Creates a new vlan device {name} on devi... |
assert name
if name in enode.ports:
raise ValueError('Port {name} already exists'.format(name=name))
assert portlbl
assert vlan_id
port = enode.ports[portlbl]
cmd = 'ip link add link {dev} name {name} type vlan id {vlan_id}'.format(
dev=port, name=name, vlan_id=vlan_id)
r... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_link_type_vlan(enode, name, shell=None):
""" Delete a virtual link. Deletes a vlan device with the name {name}. Will raise an expection if the port is... |
assert name
if name not in enode.ports:
raise ValueError('Port {name} doesn\'t exists'.format(name=name))
cmd = 'ip link del link dev {name}'.format(name=name)
response = enode(cmd, shell=shell)
assert not response, 'Cannot remove virtual link {name}'.format(name=name)
del enode.port... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def show_interface(enode, dev, shell=None):
""" Show the configured parameters and stats of an interface. :param enode: Engine node to communicate with. :type en... |
assert dev
cmd = 'ip addr list dev {ldev}'.format(ldev=dev)
response = enode(cmd, shell=shell)
first_half_dict = _parse_ip_addr_show(response)
d = None
if (first_half_dict):
cmd = 'ip -s link list dev {ldev}'.format(ldev=dev)
response = enode(cmd, shell=shell)
second_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build_mmd(target_folder=DEFAULT_LIBRARY_DIR):
"""Build and install the MultiMarkdown shared library.""" |
mmd_dir = tempfile.mkdtemp()
mmd_repo = pygit2.clone_repository('https://github.com/jasedit/MultiMarkdown-5', mmd_dir,
checkout_branch='fix_windows')
mmd_repo.init_submodules()
mmd_repo.update_submodules()
build_dir = os.path.join(mmd_dir, 'build')
old_pwd... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_requirements_files(self, base_dir='.'):
""" Generate set of requirements files for config """ |
print("Creating requirements files\n")
# TODO How to deal with requirements that are not simple, e.g. a github url
shared = self._get_shared_section()
requirements_dir = self._make_requirements_directory(base_dir)
for section in self.config.sections():
if sectio... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _write_default_sections(self):
""" Starting from scratch, so create a default rc file """ |
self.config.add_section('metadata')
self.config.set('metadata', 'shared', 'common')
self.config.add_section('common')
self.config.add_section('development')
self.config.add_section('production') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _parse_requirements(self, input):
""" Parse a list of requirements specifications. Lines that look like "foobar==1.0" are parsed; all other lines are silentl... |
results = []
for line in input:
(package, version) = self._parse_line(line)
if package:
results.append((package, version))
return tuple(results) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_rc_file(self, packages):
""" Create a set of requirements files for config """ |
print("Creating rcfile '%s'\n" % self.rc_filename)
# TODO bug with == in config file
if not self.config.sections():
self._write_default_sections()
sections = {}
section_text = []
for i, section in enumerate(self.config.sections()):
if section ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def upgrade_packages(self, packages):
""" Upgrade all specified packages to latest version """ |
print("Upgrading packages\n")
package_list = []
requirements = self._parse_requirements(packages.readlines())
for (package, version) in requirements:
package_list.append(package)
if package_list:
args = [
"pip",
"install... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def determine_extra_packages(self, packages):
""" Return all packages that are installed, but missing from "packages". Return value is a tuple of the package nam... |
args = [
"pip",
"freeze",
]
installed = subprocess.check_output(args, universal_newlines=True)
installed_list = set()
lines = installed.strip().split('\n')
for (package, version) in self._parse_requirements(lines):
installed_list.add... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_extra_packages(self, packages, dry_run=False):
""" Remove all packages missing from list """ |
removal_list = self.determine_extra_packages(packages)
if not removal_list:
print("No packages to be removed")
else:
if dry_run:
print("The following packages would be removed:\n %s\n" %
"\n ".join(removal_list))
e... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rewrap(self, **kwargs):
"""Inplace constructor. Depending on `self.inplace`, rewrap `obj`, or just update internal vars, possibly including the `obj`. """ |
if self.inplace:
for key, val in kwargs.items():
setattr(self, key, val)
return self
else:
for key in ['obj', 'default', 'skipmissing', 'inplace', 'empty']:
kwargs.setdefault(key, getattr(self, key))
return pluckable(**kwar... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _sliced_list(self, selector):
"""For slice selectors operating on lists, we need to handle them differently, depending on ``skipmissing``. In explicit mode, ... |
if self.skipmissing:
return self.obj[selector]
# TODO: can be optimized by observing list bounds
keys = xrange(selector.start or 0,
selector.stop or sys.maxint,
selector.step or 1)
res = []
for key in keys:
sel... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def forceutc(t: Union[str, datetime.datetime, datetime.date, np.datetime64]) -> Union[datetime.datetime, datetime.date]: """ Add UTC to datetime-naive and convert... |
# need to passthrough None for simpler external logic.
# %% polymorph to datetime
if isinstance(t, str):
t = parse(t)
elif isinstance(t, np.datetime64):
t = t.astype(datetime.datetime)
elif isinstance(t, datetime.datetime):
pass
elif isinstance(t, datetime.date):
ret... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def step_a_new_working_directory(context):
""" Creates a new, empty working directory """ |
command_util.ensure_context_attribute_exists(context, "workdir", None)
command_util.ensure_workdir_exists(context)
shutil.rmtree(context.workdir, ignore_errors=True) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def step_use_curdir_as_working_directory(context):
""" Uses the current directory as working directory """ |
context.workdir = os.path.abspath(".")
command_util.ensure_workdir_exists(context) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def step_an_empty_file_named_filename(context, filename):
""" Creates an empty file. """ |
assert not os.path.isabs(filename)
command_util.ensure_workdir_exists(context)
filename2 = os.path.join(context.workdir, filename)
pathutil.create_textfile_with_contents(filename2, "") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def step_i_run_command(context, command):
""" Run a command as subprocess, collect its output and returncode. """ |
command_util.ensure_workdir_exists(context)
context.command_result = command_shell.run(command, cwd=context.workdir)
command_util.workdir_save_coverage_files(context.workdir)
if False and DEBUG:
print(u"run_command: {0}".format(command))
print(u"run_command.output {0}".format(context.co... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def step_command_output_should_contain_exactly_text(context, text):
""" Verifies that the command output of the last command contains the expected text. .. code-... |
expected_text = text
if "{__WORKDIR__}" in text or "{__CWD__}" in text:
expected_text = textutil.template_substitute(text,
__WORKDIR__ = posixpath_normpath(context.workdir),
__CWD__ = posixpath_normpath(os.getcwd())
)
actual_output = context.command_result.out... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_file_list(path, max_depth=1, cur_depth=0):
""" Recursively returns a list of all files up to ``max_depth`` in a directory. """ |
if os.path.exists(path):
for name in os.listdir(path):
if name.startswith('.'):
continue
full_path = os.path.join(path, name)
if os.path.isdir(full_path):
if cur_depth == max_depth:
continue
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_applied_migrations(databases=None):
""" Returns a dictionary containing lists of all applied migrations where the key is the database alias. """ |
if not databases:
databases = get_capable_databases()
else:
# We only loop through databases that are listed as "capable"
all_databases = list(get_capable_databases())
databases = list(
itertools.ifilter(lambda x: x in all_databases, databases)
)
res... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getContGroupArrays(arrays, groupPositions, arrayKeys=None):
"""Convinience function to generate a subset of arrays from specified array positions. :param arr... |
if arrayKeys is None:
arrayKeys = list(viewkeys(arrays))
matchingArrays = dict()
for key in arrayKeys:
matchingArrays[key] = arrays[key][groupPositions]
return matchingArrays |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calcDistMatchArr(matchArr, tKey, mKey):
"""Calculate the euclidean distance of all array positions in "matchArr". :param matchArr: a dictionary of ``numpy.ar... |
#Calculate all sorted list of all eucledian feature distances
matchArrSize = listvalues(matchArr)[0].size
distInfo = {'posPairs': list(), 'eucDist': list()}
_matrix = numpy.swapaxes(numpy.array([matchArr[tKey], matchArr[mKey]]), 0, 1)
for pos1 in range(matchArrSize-1):
for pos2 in range(p... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load(self, path, name):
"""Imports the specified ``fgic`` file from the hard disk. :param path: filedirectory to which the ``fgic`` file is written. :param n... |
filename = name + '.fgic'
filepath = aux.joinpath(path, filename)
with zipfile.ZipFile(filepath, 'r') as containerZip:
#Convert the zipfile data into a str object, necessary since
#containerZip.read() returns a bytes object.
jsonString = io.TextIOWrapper(con... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create(cls, path, encoding='utf-8'):
"""Create a new bare repository""" |
cmd = [GIT, 'init', '--quiet', '--bare', path]
subprocess.check_call(cmd)
return cls(path, encoding) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cache(self, dependency: Dependency, value):
""" Store an instance of dependency in the cache. Does nothing if dependency is NOT a threadlocal or a singleton.... |
if dependency.threadlocal:
setattr(self._local, dependency.name, value)
elif dependency.singleton:
self._singleton[dependency.name] = value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cached(self, dependency):
""" Get a cached instance of dependency. :param dependency: The ``Dependency`` to retrievie value for :type dependency: ``Dependenc... |
if dependency.threadlocal:
return getattr(self._local, dependency.name, None)
elif dependency.singleton:
return self._singleton.get(dependency.name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _set(self, name, factory, singleton=False, threadlocal=False):
""" Add a dependency factory to the registry :param name: Name of dependency :param factory: f... |
name = name or factory.__name__
factory._giveme_registered_name = name
dep = Dependency(name, factory, singleton, threadlocal)
self._registry[name] = dep |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register(self, function=None, *, singleton=False, threadlocal=False, name=None):
""" Add an object to the injector's registry. Can be used as a decorator lik... |
def decorator(function=None):
self._set(name, function, singleton, threadlocal)
return function
if function:
return decorator(function)
return decorator |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def inject(self, function=None, **names):
""" Inject dependencies into `funtion`'s arguments when called. The `Injector` will look for registered dependencies ma... |
def decorator(function):
@wraps(function)
def wrapper(*args, **kwargs):
sig = signature(function)
params = sig.parameters
bound = sig.bind_partial(*args, **kwargs)
bound.apply_defaults()
injected_kwargs = ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resolve(self, dependency):
""" Resolve dependency as instance attribute of given class. When the attribute is first accessed, it will be resolved from the co... |
if isinstance(dependency, str):
name = dependency
else:
name = dependency._giveme_registered_name
return DeferredProperty(
partial(self.get, name)
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _fetch_itemslist(self, current_item):
""" Get a all available apis """ |
if current_item.is_root:
html = requests.get(self.base_url).text
soup = BeautifulSoup(html, 'html.parser')
for item_html in soup.select(".row .col-md-6"):
try:
label = item_html.select_one("h2").text
except Exception:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _fetch_data(self, dataset, query={}, include_inactive_stations=False):
""" Should yield dataset rows """ |
data = []
parameter = dataset
station_dim = dataset.dimensions["station"]
all_stations = station_dim.allowed_values
# Step 1: Prepare query
if "station" not in query:
if include_inactive_stations:
# Get all stations
query["stat... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_example_csv(self):
"""For dimension parsing """ |
station_key = self.json["station"][0]["key"]
period = "corrected-archive"
url = self.url\
.replace(".json", "/station/{}/period/{}/data.csv"\
.format(station_key, period))
r = requests.get(url)
if r.status_code == 200:
return Data... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def plural(formatter, value, name, option, format):
"""Chooses different textension for locale-specific pluralization rules. Example:: There is an item. There ar... |
# Extract the plural words from the format string.
words = format.split('|')
# This extension requires at least two plural words.
if not name and len(words) == 1:
return
# This extension only formats numbers.
try:
number = decimal.Decimal(value)
except (ValueError, decimal.I... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_choice(value):
"""Gets a key to choose a choice from any value.""" |
if value is None:
return 'null'
for attr in ['__name__', 'name']:
if hasattr(value, attr):
return getattr(value, attr)
return str(value) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def choose(formatter, value, name, option, format):
"""Adds simple logic to format strings. Example:: u'one' u'other' """ |
if not option:
return
words = format.split('|')
num_words = len(words)
if num_words < 2:
return
choices = option.split('|')
num_choices = len(choices)
# If the words has 1 more item than the choices, the last word will be
# used as a default choice.
if num_words not ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_(formatter, value, name, option, format):
"""Repeats the items of an array. Spec: `{:[l[ist]:]item|spacer[|final_spacer[|two_spacer]]}` Example:: u'appl... |
if not format:
return
if not hasattr(value, '__getitem__') or isinstance(value, string_types):
return
words = format.split(u'|', 4)
num_words = len(words)
if num_words < 2:
# Require at least two words for item format and spacer.
return
num_items = len(value)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_months(datetime_like_object, n, return_date=False):
""" Returns a time that n months after a time. Notice: for example, the date that one month after 201... |
a_datetime = parser.parse_datetime(datetime_like_object)
month_from_ordinary = a_datetime.year * 12 + a_datetime.month
month_from_ordinary += n
year, month = divmod(month_from_ordinary, 12)
# try assign year, month, day
try:
a_datetime = datetime(
year, month, a_datetime.da... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _log(self, content):
""" Write a string to the log """ |
self._buffer += content
if self._auto_flush:
self.flush() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reset(self):
""" Erase the log and reset the timestamp """ |
self._buffer = ''
self._chars_flushed = 0
self._game_start_timestamp = datetime.datetime.now() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def logpath(self):
""" Return the logfile path and filename as a string. The file with name self.logpath() is written to on flush(). The filename contains the lo... |
name = '{}-{}.catan'.format(self.timestamp_str(),
'-'.join([p.name for p in self._players]))
path = os.path.join(self._log_dir, name)
if not os.path.exists(self._log_dir):
os.mkdir(self._log_dir)
return path |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def flush(self):
""" Append the latest updates to file, or optionally to stdout instead. See the constructor for logging options. """ |
latest = self._latest()
self._chars_flushed += len(latest)
if self._use_stdout:
file = sys.stdout
else:
file = open(self.logpath(), 'a')
print(latest, file=file, flush=True, end='')
if not self._use_stdout:
file.close() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def log_game_start(self, players, terrain, numbers, ports):
""" Begin a game. Erase the log, set the timestamp, set the players, and write the log header. The ro... |
self.reset()
self._set_players(players)
self._logln('{} v{}'.format(__name__, __version__))
self._logln('timestamp: {0}'.format(self.timestamp_str()))
self._log_players(players)
self._log_board_terrain(terrain)
self._log_board_numbers(numbers)
self._log_b... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _log_board_ports(self, ports):
""" A board with no ports is allowed. In the logfile, ports must be sorted - ascending by tile identifier (primary) - alphabet... |
ports = sorted(ports, key=lambda port: (port.tile_id, port.direction))
self._logln('ports: {0}'.format(' '.join('{}({} {})'.format(p.type.value, p.tile_id, p.direction)
for p in ports))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _SetGuide(self, guideName):
""" Select guide corresponding to guideName Parameters guideName : string Name of guide to use. Note Supported guide names are: E... |
if(guideName == epguides.EPGuidesLookup.GUIDE_NAME):
self._guide = epguides.EPGuidesLookup()
else:
raise Exception("[RENAMER] Unknown guide set for TVRenamer selection: Got {}, Expected {}".format(guideName, epguides.EPGuidesLookup.GUIDE_NAME)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _GetUniqueFileShowNames(self, tvFileList):
""" Return a list containing all unique show names from tvfile.TVFile object list. Parameters tvFileList : list Li... |
showNameList = [tvFile.fileInfo.showName for tvFile in tvFileList]
return(set(showNameList)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _GetShowInfo(self, stringSearch):
""" Calls GetShowID and does post processing checks on result. Parameters stringSearch : string String to look up in databa... |
goodlogging.Log.Info("RENAMER", "Looking up show info for: {0}".format(stringSearch))
goodlogging.Log.IncreaseIndent()
showInfo = self._GetShowID(stringSearch)
if showInfo is None:
goodlogging.Log.DecreaseIndent()
return None
elif showInfo.showID is None:
goodlogging.Log.DecreaseI... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _CreateNewShowDir(self, showName):
""" Create new directory name for show. An autogenerated choice, which is the showName input that has been stripped of spe... |
stripedDir = util.StripSpecialCharacters(showName)
goodlogging.Log.Info("RENAMER", "Suggested show directory name is: '{0}'".format(stripedDir))
if self._skipUserInput is False:
response = goodlogging.Log.Input('RENAMER', "Enter 'y' to accept this directory, 'x' to skip this show or enter a new dire... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _GenerateLibraryPath(self, tvFile, libraryDir):
""" Creates a full path for TV file in TV library. This initially attempts to directly match a show directory... |
goodlogging.Log.Info("RENAMER", "Looking up library directory in database for show: {0}".format(tvFile.showInfo.showName))
goodlogging.Log.IncreaseIndent()
showID, showName, showDir = self._db.SearchTVLibrary(showName = tvFile.showInfo.showName)[0]
if showDir is None:
goodlogging.Log.Info("RENAM... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def catch(ignore=[], was_doing="something important", helpfull_tips="you should use a debugger", gbc=None):
""" Catch, prepare and log error :param exc_cls: erro... |
exc_cls, exc, tb=sys.exc_info()
if exc_cls in ignore:
msg='exception in ignorelist'
gbc.say('ignoring caught:'+str(exc_cls))
return 'exception in ignorelist'
ex_message = traceback.format_exception_only(exc_cls, exc)[-1]
ex_message = ex_message.strip()
# TODO:... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_name(api_url, name, dry_run=False):
""" doesn't require a token config param as all of our data is currently public """ |
return DataSet(
'/'.join([api_url, name]).rstrip('/'),
token=None,
dry_run=dry_run
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def secured_clipboard(item):
"""This clipboard only allows 1 paste """ |
expire_clock = time.time()
def set_text(clipboard, selectiondata, info, data):
# expire after 15 secs
if 15.0 >= time.time() - expire_clock:
selectiondata.set_text(item.get_secret())
clipboard.clear()
def clear(clipboard, data):
"""Clearing of the buffer is d... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_active_window():
"""Get the currently focused window """ |
active_win = None
default = wnck.screen_get_default()
while gtk.events_pending():
gtk.main_iteration(False)
window_list = default.get_windows()
if len(window_list) == 0:
print "No Windows Found"
for win in window_list:
if win.is_active():
active_win = win.get... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(self):
"""Get quota from Cloud Provider.""" |
# get all network quota from Cloud Provider.
attrs = ("networks",
"security_groups",
"floating_ips",
"routers",
"internet_gateways")
for attr in attrs:
setattr(self, attr, eval("self.get_{}()". format(attr))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def join_css_class(css_class, *additional_css_classes):
""" Returns the union of one or more CSS classes as a space-separated string. Note that the order will no... |
css_set = set(chain.from_iterable(
c.split(' ') for c in [css_class, *additional_css_classes] if c))
return ' '.join(css_set) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _init_routes_and_middlewares(self):
"""Initialize hooks and URI routes to resources.""" |
self._init_middlewares()
self._init_endpoints()
self.app = falcon.API(middleware=self.middleware)
self.app.add_error_handler(Exception, self._error_handler)
for version_path, endpoints in self.catalog:
for route, resource in endpoints:
self.app.add_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def listen(self):
"""Self-host using 'bind' and 'port' from the WSGI config group.""" |
msgtmpl = (u'Serving on host %(host)s:%(port)s')
host = CONF.wsgi.wsgi_host
port = CONF.wsgi.wsgi_port
LOG.info(msgtmpl,
{'host': host, 'port': port})
server_cls = self._get_server_cls(host)
httpd = simple_server.make_server(host,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_promise(self):
"""Return the special set of promises for run_instruction. Run Instruction has to support multiple promises (one for reading data, and one... |
if self._promise is None:
promise = []
if self.read:
promise.append(TDOPromise(self._chain, 0, self.bitcount))
else:
promise.append(None)
if self.read_status:
promise.append(TDOPromise(self._chain, 0,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_dataset(self, dataset, name, color):
""" Encode a dataset """ |
global palette
html = "{"
html += '\t"label": "' + name + '",'
if color is not None:
html += '"backgroundColor": "' + color + '",\n'
else:
html += '"backgroundColor": ' + palette + ',\n'
html += '"data": ' + self._format_list(dataset) + ',\n'
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(self, slug, xdata, ydatasets, label, opts, style, ctype):
""" Returns html for a chart """ |
xdataset = self._format_list(xdata)
width = "100%"
height = "300px"
if opts is not None:
if "width" in opts:
width = str(opts["width"])
if "height" in opts:
height = str(opts["height"])
stylestr = '<style>#container_' + slu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _format_list(self, data):
""" Format a list to use in javascript """ |
dataset = "["
i = 0
for el in data:
if pd.isnull(el):
dataset += "null"
else:
dtype = type(data[i])
if dtype == int or dtype == float:
dataset += str(el)
else:
dataset... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def status(self, status, headers=None):
'''
Respond with given status and no content
:type status: int
:param status: status code to return
:type headers: dict
:param headers: dictionary of headers to add to response
:returns: itself
:rtype: Rule
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def text(self, text, status=200, headers=None):
'''
Respond with given status and text content
:type text: str
:param text: text to return
:type status: int
:param status: status code to return
:type headers: dict
:param headers: dictionary of headers t... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def matches(self, method, path, headers, bytes=None):
'''
Checks if rule matches given request parameters
:type method: str
:param method: HTTP method, e.g. ``'GET'``, ``'POST'``, etc.
Can take any custom string
:type path: str
:param path: request path incl... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def on(self, method, path=None, headers=None, text=None, json=None):
'''
Sends response to matching parameters one time and removes it from list of expectations
:type method: str
:param method: request method: ``'GET'``, ``'POST'``, etc. can be some custom string
:type path: st... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def stop(self):
'''
Shuts the server down and waits for server thread to join
'''
self._server.shutdown()
self._server.server_close()
self._thread.join()
self.running = False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def send(self, stats):
"Format stats and send to one or more Graphite hosts"
buf = cStringIO.StringIO()
now = int(time.time())
num_stats = 0
# timer stats
pct = stats.percent
timers = stats.timers
for key, vals in timers.iteritems():
if not va... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_payload(self, *args, **kwargs):
"""Receive all passed in args, kwargs, and combine them together with any required params""" |
if not kwargs:
kwargs = self.default_params
else:
kwargs.update(self.default_params)
for item in args:
if isinstance(item, dict):
kwargs.update(item)
if hasattr(self, 'type_params'):
kwargs.update(self.type_params(*args, **... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def read_frame(self) -> DataFrame: """Read a single frame from the local buffer. If no frames are available but the stream is still open, waits until more f... |
if self._data_frames.qsize() == 0 and self.closed:
raise StreamConsumedError(self.id)
frame = await self._data_frames.get()
self._data_frames.task_done()
if frame is None:
raise StreamConsumedError(self.id)
return frame |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_frame_nowait(self) -> Optional[DataFrame]: """Read a single frame from the local buffer immediately. If no frames are available but the stream is still o... |
try:
frame = self._data_frames.get_nowait()
except asyncio.QueueEmpty:
if self.closed:
raise StreamConsumedError(self.id)
return None
self._data_frames.task_done()
if frame is None:
raise StreamConsumedError(self.id)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def merge(a, b, op=None, recurse_list=False, max_depth=None):
"""Immutable merge ``a`` structure with ``b`` using binary operator ``op`` on leaf nodes. All nodes... |
if op is None:
op = operator.add
if max_depth is not None:
if max_depth < 1:
return op(a, b)
else:
max_depth -= 1
if isinstance(a, dict) and isinstance(b, dict):
result = {}
for key in set(chain(a.keys(), b.keys())):
if key in a... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _param_deprecation_warning(schema, deprecated, context):
"""Raises warning about using the 'old' names for some parameters.
The new naming scheme just ha... |
for i in deprecated:
if i in schema:
msg = 'When matching {ctx}, parameter {word} is deprecated, use __{word}__ instead'
msg = msg.format(ctx = context, word = i)
warnings.warn(msg, Warning) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def has_perm(self, user, perm, obj=None, *args, **kwargs):
"""Test user permissions for a single action and object. :param user: The user to test. :type user: ``... |
try:
if not self._obj_ok(obj):
if hasattr(obj, 'get_permissions_object'):
obj = obj.get_permissions_object(perm)
else:
raise InvalidPermissionObjectException
return user.permset_tree.allow(Action(perm), obj)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def permitted_actions(self, user, obj=None):
"""Determine list of permitted actions for an object or object pattern. :param user: The user to test. :type user: `... |
try:
if not self._obj_ok(obj):
raise InvalidPermissionObjectException
return user.permset_tree.permitted_actions(obj)
except ObjectDoesNotExist:
return [] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list(self, name, platform='', genre=''):
""" The name argument is required for this method as per the API server specification. This method also provides the... |
data_list = self.db.get_data(self.list_path, name=name,
platform=platform, genre=genre)
data_list = data_list.get('Data') or {}
games = data_list.get('Game') or []
return [self._build_item(**i) for i in games] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list(self):
""" No argument is required for this method as per the API server specification. """ |
data_list = self.db.get_data(self.list_path)
data_list = data_list.get('Data') or {}
platforms = (data_list.get('Platforms') or {}).get('Platform') or []
return [self._build_item(**i) for i in platforms] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_none_dict_values(obj):
""" Remove None values from dict. """ |
if isinstance(obj, (list, tuple, set)):
return type(obj)(remove_none_dict_values(x) for x in obj)
elif isinstance(obj, dict):
return type(obj)((k, remove_none_dict_values(v))
for k, v in obj.items()
if v is not None)
else:
return obj |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.