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 schedule(demand: dict, alterations: set, looped: set=None, altered: set=None):
"""Prioritizes Triggers called from outside.""" |
if looped is not None and len(demand) != len(looped):
for func in looped: del demand[func]
if keep_temp in demand:
demand.pop(increase_temp, None)
demand.pop(lower_temp, None)
elif lower_temp in demand:
demand.pop(increase_temp, None)
return demand, alterations |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def d(msg, *args, **kwargs):
'''
log a message at debug level;
'''
return logging.log(DEBUG, msg, *args, **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 v(msg, *args, **kwargs):
'''
log a message at verbose level;
'''
return logging.log(VERBOSE, msg, *args, **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 i(msg, *args, **kwargs):
'''
log a message at info level;
'''
return logging.log(INFO, msg, *args, **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 w(msg, *args, **kwargs):
'''
log a message at warn level;
'''
return logging.log(WARN, msg, *args, **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 e(msg, *args, **kwargs):
'''
log a message at error level;
'''
return logging.log(ERROR, msg, *args, **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 getLogger(name=None):
'''
return a logger instrumented with additional 1-letter logging methods;
'''
logger = logging.getLogger(name=name)
if not hasattr(logger, 'd'):
def d(self, msg, *args, **kwargs):
return self.log(DEBUG, msg, *args, **kwargs)
logger.d = types.... |
<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_instances(configuration):
"""Create necessary class instances from a configuration with no argument to the constructor :param dict configuration: conf... |
instances = {}
for methods in configuration.itervalues():
for element in methods.itervalues():
if not isinstance(element, tuple):
continue
cls, _ = element
if cls not in instances:
instances[cls] = cls()
return instances |
<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(self, request):
"""Call the appropriate function :param dict request: request that describes the function to call :return: response linked to the reques... |
result = None
try:
if 'extAction' in request: # DirectSubmit method
tid = request['extTID']
action = request['extAction']
method = request['extMethod']
else:
tid = request['tid']
action = request['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 url_to_filename(url):
""" Safely translate url to relative filename Args: url (str):
A target url string Returns: str """ |
# remove leading/trailing slash
if url.startswith('/'):
url = url[1:]
if url.endswith('/'):
url = url[:-1]
# remove pardir symbols to prevent unwilling filesystem access
url = remove_pardir_symbols(url)
# replace dots to underscore in filename part
url = replace_dots_to_unde... |
<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_pardir_symbols(path, sep=os.sep, pardir=os.pardir):
""" Remove relative path symobls such as '..' Args: path (str):
A target path string sep (str):
... |
bits = path.split(sep)
bits = (x for x in bits if x != pardir)
return sep.join(bits) |
<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(root):
"""Load from an xml.etree.ElementTree""" |
types = _load_types(root)
enums = _load_enums(root)
commands = _load_commands(root)
features = _load_features(root)
extensions = _load_extensions(root)
return Registry(None, types, enums, commands, features, extensions) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def import_type(dest, src, name, api=None, filter_symbol=None):
"""Import Type `name` and its dependencies from Registry `src` to Registry `dest`. :param Registr... |
if not filter_symbol:
filter_symbol = _default_filter_symbol
type = src.get_type(name, api)
for x in type.required_types:
if not filter_symbol('type', x):
continue
import_type(dest, src, x, api, filter_symbol)
dest.types[(type.name, type.api)] = type |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def import_command(dest, src, name, api=None, filter_symbol=None):
"""Import Command `name` and its dependencies from Registry `src` to Registry `dest` :param Re... |
if not filter_symbol:
filter_symbol = _default_filter_symbol
cmd = src.commands[name]
for x in cmd.required_types:
if not filter_symbol('type', x):
continue
import_type(dest, src, x, api, filter_symbol)
dest.commands[name] = cmd |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def import_enum(dest, src, name):
"""Import Enum `name` from Registry `src` to Registry `dest`. :param Registry dest: Destination Registry :param Registry src: S... |
dest.enums[name] = src.enums[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 import_feature(dest, src, name, api=None, profile=None, filter_symbol=None):
"""Imports Feature `name`, and all its dependencies, from Registry `src` to Regi... |
if filter_symbol is None:
filter_symbol = _default_filter_symbol
ft = src.features[name] if isinstance(name, str) else name
# Gather symbols to remove from Feature
remove_symbols = set()
for x in src.get_removes(api, profile):
remove_symbols.update(x.as_symbols())
def my_filter... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def import_extension(dest, src, name, api=None, profile=None, filter_symbol=None):
"""Imports Extension `name`, and all its dependencies. :param Registry dest: D... |
if filter_symbol is None:
filter_symbol = _default_filter_symbol
ext = src.extensions[name] if isinstance(name, str) else name
for req in ext.get_requires(api, profile):
for x in req.types:
if not filter_symbol('type', x):
continue
import_type(dest, 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 import_registry(dest, src, api=None, profile=None, support=None, filter_symbol=None):
"""Imports all features and extensions and all their dependencies. :par... |
if filter_symbol is None:
filter_symbol = _default_filter_symbol
for x in src.get_features(api):
import_feature(dest, src, x.name, api, profile, filter_symbol)
for x in src.get_extensions(support):
import_extension(dest, src, x.name, api, profile, filter_symbol) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extension_sort_key(extension):
"""Returns the sorting key for an extension. The sorting key can be used to sort a list of extensions into the order that is u... |
name = extension.name
category = name.split('_', 2)[1]
return (0, name) if category in ('ARB', 'KHR', 'OES') else (1, 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 group_apis(reg, features=None, extensions=None, api=None, profile=None, support=None):
"""Groups Types, Enums, Commands with their respective Features, Exten... |
features = (reg.get_features(api) if features is None
else [reg.features[x] for x in features])
if extensions is None:
extensions = sorted(reg.get_extensions(support),
key=extension_sort_key)
else:
extensions = [reg.extensions[x] for x in extensio... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main(args=None, prog=None):
"""Generates a C header file""" |
args = args if args is not None else sys.argv[1:]
prog = prog if prog is not None else sys.argv[0]
# Prevent broken pipe exception from being raised.
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
stdin = sys.stdin.buffer if hasattr(sys.stdin, 'buffer') else sys.stdin
p = argparse.ArgumentParser... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def required_types(self):
"""Set of names of types which the Command depends on. """ |
required_types = set(x.type for x in self.params)
required_types.add(self.type)
required_types.discard(None)
return required_types |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def proto_text(self):
"""Formatted Command identifier. Equivalent to ``self.proto_template.format(type=self.type, name=self.name)``. """ |
return self.proto_template.format(type=self.type, name=self.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 text(self):
"""Formatted Command declaration. This is the C declaration for the command. """ |
params = ', '.join(x.text for x in self.params)
return '{0} ({1})'.format(self.proto_text, params) |
<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):
"""Formatted param definition Equivalent to ``self.template.format(name=self.name, type=self.type)``. """ |
return self.template.format(name=self.name, type=self.type) |
<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_symbols(self):
"""Set of symbols required by this Require :return: set of ``(symbol type, symbol name)`` tuples """ |
out = set()
for name in self.types:
out.add(('type', name))
for name in self.enums:
out.add(('enum', name))
for name in self.commands:
out.add(('command', name))
return 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_profiles(self):
"""Returns set of profile names referenced in this Feature :returns: set of profile names """ |
out = set(x.profile for x in self.requires if x.profile)
out.update(x.profile for x in self.removes if x.profile)
return 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_requires(self, profile=None):
"""Get filtered list of Require objects in this Feature :param str profile: Return Require objects with this profile or Non... |
out = []
for req in self.requires:
# Filter Require by profile
if ((req.profile and not profile) or
(req.profile and profile and req.profile != profile)):
continue
out.append(req)
return 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_removes(self, profile=None):
"""Get filtered list of Remove objects in this Feature :param str profile: Return Remove objects with this profile or None t... |
out = []
for rem in self.removes:
# Filter Remove by profile
if ((rem.profile and not profile) or
(rem.profile and profile and rem.profile != profile)):
continue
out.append(rem)
return 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_apis(self):
"""Returns set of api names referenced in this Extension :return: set of api name strings """ |
out = set()
out.update(x.api for x in self.requires if x.api)
return 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_profiles(self):
"""Returns set of profile names referenced in this Extension :return: set of profile name strings """ |
return set(x.profile for x in self.requires if x.profile) |
<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_requires(self, api=None, profile=None):
"""Return filtered list of Require objects in this Extension :param str api: Return Require objects with this api... |
out = []
for req in self.requires:
# Filter Remove by API
if (req.api and not api) or (req.api and api and req.api != api):
continue
# Filter Remove by profile
if ((req.profile and not profile) or
(req.profile and profile an... |
<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):
"""Formatted API declarations. Equivalent to the concatenation of `text` attributes of types, enums and commands in this Registry. """ |
out = []
out.extend(x.text for x in self.types.values())
out.extend(x.text for x in self.enums.values())
out.extend('extern {0};'.format(x.text)
for x in self.commands.values())
return '\n'.join(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_type(self, name, api=None):
"""Returns Type `name`, with preference for the Type of `api`. :param str name: Type name :param str api: api name to prefer,... |
k = (name, api)
if k in self.types:
return self.types[k]
else:
return self.types[(name, None)] |
<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_features(self, api=None):
"""Returns filtered list of features in this registry :param str api: Return only features with this api name, or None to retur... |
return [x for x in self.features.values()
if api and x.api == api or not api] |
<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_extensions(self, support=None):
"""Returns filtered list of extensions in this registry :param support: Return only extensions with this extension suppor... |
return [x for x in self.extensions.values() if support
and support in x.supported or not support] |
<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_requires(self, api=None, profile=None, support=None):
"""Returns filtered list of Require objects in this registry :param str api: Return Require objects... |
out = []
for ft in self.get_features(api):
out.extend(ft.get_requires(profile))
for ext in self.extensions.values():
# Filter extension support
if support and support not in ext.supported:
continue
out.extend(ext.get_requires(api, ... |
<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_removes(self, api=None, profile=None):
"""Returns filtered list of Remove objects in this registry :param str api: Return Remove objects with this api na... |
out = []
for ft in self.get_features(api):
out.extend(ft.get_removes(profile))
return 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_apis(self):
"""Returns set of api names referenced in this Registry :return: set of api name strings """ |
out = set(x.api for x in self.types.values() if x.api)
for ft in self.features.values():
out.update(ft.get_apis())
for ext in self.extensions.values():
out.update(ext.get_apis())
return 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_profiles(self):
"""Returns set of profile names referenced in this Registry :return: set of profile name strings """ |
out = set()
for ft in self.features.values():
out.update(ft.get_profiles())
for ext in self.extensions.values():
out.update(ext.get_profiles())
return 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_supports(self):
"""Returns set of extension support strings referenced in this Registry :return: set of extension support strings """ |
out = set()
for ext in self.extensions.values():
out.update(ext.get_supports())
return 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_open_window_names():
'''
Return a dict with open program names and their corresponding decimal ids
'''
raw_names = subprocess.check_output(['wmctrl', '-l']).decode('utf8').split('\n')
split_names = [name.split() for name in raw_names if name]
name_dict = {}
for name in split_names:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resource_row_set(package, resource):
""" Generate an iterator over all the rows in this resource's source data. """ |
# This is a work-around because messytables hangs on boto file
# handles, so we're doing it via plain old HTTP.
table_set = any_tableset(resource.fh(),
extension=resource.meta.get('extension'),
mimetype=resource.meta.get('mime_type'))
tables = l... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def column_alias(cell, names):
""" Generate a normalized version of the column name. """ |
column = slugify(cell.column or '', sep='_')
column = column.strip('_')
column = 'column' if not len(column) else column
name, i = column, 2
# de-dupe: column, column_2, column_3, ...
while name in names:
name = '%s_%s' % (name, i)
i += 1
return 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 random_sample(value, field, row, num=10):
""" Collect a random sample of the values in a particular field based on the reservoir sampling technique. """ |
# TODO: Could become a more general DQ piece.
if value is None:
field['has_nulls'] = True
return
if value in field['samples']:
return
if isinstance(value, basestring) and not len(value.strip()):
field['has_empty'] = True
return
if len(field['samples']) < num:... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_unique_ngrams(s, n):
"""Make a set of unique n-grams from a string.""" |
return set(s[i:i + n] for i in range(len(s) - n + 1)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check(self, s, instant_exact=True):
"""Check if a string is in the DB. :param s: str, string to check against the DB. :param instant_exact: bool, look up exa... |
all_sets = self._get_comparison_strings(s)
if instant_exact and s in all_sets: # exact match
return True
for comparison_string in all_sets:
if self.comparison_func(s, comparison_string) >= self.cutoff:
return True
return 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 insert(self, seq):
""" Populates the DB from a sequence of strings, ERASING PREVIOUS STATE. :param seq: an iterable """ |
# erase previous elements and make defaultdict for easier insertion.
self._els_idxed = defaultdict(lambda: defaultdict(set))
if type(seq) is str:
raise ValueError('Provided argument should be a sequence of strings'
', but not a string itself.')
f... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _finalize_db(self):
"""Convert defaultdicts to regular dicts.""" |
for k, v in self._els_idxed.items():
self._els_idxed[k] = dict(v)
self._els_idxed = dict(self._els_idxed) |
<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_comparison_strings(self, s):
"""Find all similar strings""" |
str_len = len(s)
comparison_idxs = make_unique_ngrams(s, self.idx_size)
min_len = len(s) - self.plus_minus
if min_len < 0:
min_len = 0
if self._els_idxed is None:
raise UnintitializedError('Database not created')
all_sets = set()
for 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 _load_methods(package):
"""Loads the mappings from method call result to analysis. Args: package (str):
name of the package to load for. """ |
global _methods
_methods[package] = None
from acorn.config import settings
from acorn.logging.descriptors import _obj_getattr
spack = settings(package)
if spack is not None:
if spack.has_section("analysis.methods"):
_methods[package] = {}
from 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 analyze(fqdn, result, argl, argd):
"""Analyzes the result from calling the method with the specified FQDN. Args: fqdn (str):
full-qualified name of the meth... |
package = fqdn.split('.')[0]
if package not in _methods:
_load_methods(package)
if _methods[package] is not None and fqdn in _methods[package]:
return _methods[package][fqdn](fqdn, result, *argl, **argd) |
<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(station: str, txt: str) -> TafData: """ Returns TafData and Units dataclasses with parsed data and their associated units """ |
core.valid_station(station)
while len(txt) > 3 and txt[:4] in ('TAF ', 'AMD ', 'COR '):
txt = txt[4:]
_, station, time = core.get_station_and_time(txt[:20].split(' '))
retwx = {
'end_time': None,
'raw': txt,
'remarks': None,
'start_time': None,
'station':... |
<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_lines(lines: [str], units: Units, use_na: bool = True) -> [dict]: # type: ignore """ Returns a list of parsed line dictionaries """ |
parsed_lines = []
prob = ''
while lines:
raw_line = lines[0].strip()
line = core.sanitize_line(raw_line)
# Remove prob from the beginning of a line
if line.startswith('PROB'):
# Add standalone prob to next line
if len(line) == 6:
prob ... |
<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_na_line(txt: str, units: Units) -> typing.Dict[str, str]: """ Parser for the North American TAF forcast varient """ |
retwx = {}
wxdata = txt.split(' ')
wxdata, _, retwx['wind_shear'] = core.sanitize_report_list(wxdata)
wxdata, retwx['type'], retwx['start_time'], retwx['end_time'] = core.get_type_and_times(wxdata)
wxdata, retwx['wind_direction'], retwx['wind_speed'], \
retwx['wind_gust'], _ = core.get_wind... |
<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_in_line(txt: str, units: Units) -> typing.Dict[str, str]: """ Parser for the International TAF forcast varient """ |
retwx = {}
wxdata = txt.split(' ')
wxdata, _, retwx['wind_shear'] = core.sanitize_report_list(wxdata)
wxdata, retwx['type'], retwx['start_time'], retwx['end_time'] = core.get_type_and_times(wxdata)
wxdata, retwx['wind_direction'], retwx['wind_speed'], \
retwx['wind_gust'], _ = core.get_wind... |
<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):
""" Fill the screen with black pixels """ |
surface = Surface(self.width, self.height)
surface.fill(BLACK)
self.matrix = surface.matrix |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(self):
""" Sends the current screen contents to Mate Light """ |
display_data = []
for y in range(self.height):
for x in range(self.width):
for color in self.matrix[x][y]:
display_data.append(int(color))
checksum = bytearray([0, 0, 0, 0])
data_as_bytes = bytearray(display_data)
data = data_as_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 blit(self, surface, pos=(0, 0)):
""" Blits a surface on the screen at pos :param surface: Surface to blit :param pos: Top left corner to start blitting :type... |
for x in range(surface.width):
for y in range(surface.height):
point = (x + pos[0], y + pos[1])
if self.point_on_screen(point):
self.matrix[point[0]][point[1]] = surface.matrix[x][y] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def point_on_screen(self, pos):
""" Is the point still on the screen? :param pos: Point :type pos: tuple :return: Is it? :rtype: bool """ |
if 0 <= pos[0] < self.width and 0 <= pos[1] < self.height:
return True
else:
return 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 get(self, word):
""" Obtains the definition of a word from Urban Dictionary. :param word: word to be searched for :type word: str :return: a result set with ... |
url = "https://mashape-community-urban-dictionary.p.mashape.com/define?term=%s" % word
try:
res = requests.get(url,
headers = {"X-Mashape-Key": self.api_key,
"Accept": "text/plain"})
except requests.ConnectionError:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def estimate(self, upgrades):
"""Estimate the time needed to apply upgrades. If an upgrades does not specify and estimate it is assumed to be in the order of 1 s... |
val = 0
for u in upgrades:
val += u.estimate()
return val |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def human_estimate(self, upgrades):
"""Make a human readable estimated time to completion string. :param upgrades: List of upgrades sorted in topological order. ... |
val = self.estimate(upgrades)
if val < 60:
return "less than 1 minute"
elif val < 300:
return "less than 5 minutes"
elif val < 600:
return "less than 10 minutes"
elif val < 1800:
return "less than 30 minutes"
elif val < 360... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _setup_log_prefix(self, plugin_id=''):
"""Setup custom warning notification.""" |
self._logger_console_fmtter.prefix = '%s: ' % plugin_id
self._logger_console_fmtter.plugin_id = plugin_id
self._logger_file_fmtter.prefix = '*'
self._logger_file_fmtter.plugin_id = '%s: ' % plugin_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 _teardown_log_prefix(self):
"""Tear down custom warning notification.""" |
self._logger_console_fmtter.prefix = ''
self._logger_console_fmtter.plugin_id = ''
self._logger_file_fmtter.prefix = ' '
self._logger_file_fmtter.plugin_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 pre_upgrade_checks(self, upgrades):
"""Run upgrade pre-checks prior to applying upgrades. Pre-checks should in general be fast to execute. Pre-checks may the... |
errors = []
for check in self.global_pre_upgrade:
self._setup_log_prefix(plugin_id=check.__name__)
try:
check()
except RuntimeError as e:
errors.append((check.__name__, e.args))
for u in upgrades:
self._setup_log_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _check_errors(self, errors, prefix):
"""Check for errors and possible raise and format an error message. :param errors: List of error messages. :param prefix... |
args = []
for uid, messages in errors:
error_msg = []
error_msg.append(prefix % uid)
for msg in messages:
error_msg.append(" (-) %s" % msg)
args.append("\n".join(error_msg))
if args:
raise RuntimeError(*args) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def post_upgrade_checks(self, upgrades):
"""Run post-upgrade checks after applying all pending upgrades. Post checks may be used to emit warnings encountered whe... |
errors = []
for u in upgrades:
self._setup_log_prefix(plugin_id=u.name)
try:
u.post_upgrade()
except RuntimeError as e:
errors.append((u.name, e.args))
for check in self.global_post_upgrade:
self._setup_log_prefix... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def apply_upgrade(self, upgrade):
"""Apply a upgrade and register that it was successful. A upgrade may throw a RuntimeError, if an unrecoverable error happens. ... |
self._setup_log_prefix(plugin_id=upgrade.name)
try: # Nested due to Python 2.4
try:
upgrade.do_upgrade()
self.register_success(upgrade)
except RuntimeError as e:
msg = ["Upgrade error(s):"]
for m in e.args:
... |
<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_history(self):
"""Load upgrade history from database table. If upgrade table does not exists, the history is assumed to be empty. """ |
if not self.history:
query = Upgrade.query.order_by(desc(Upgrade.applied))
for u in query.all():
self.history[u.upgrade] = u.applied
self.ordered_history.append(u.upgrade) |
<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_success(self, upgrade):
"""Register a successful upgrade.""" |
u = Upgrade(upgrade=upgrade.name, applied=datetime.now())
db.session.add(u)
db.session.commit() |
<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_history(self):
"""Get history of applied upgrades.""" |
self.load_history()
return map(lambda x: (x, self.history[x]), self.ordered_history) |
<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_upgrades(self, remove_applied=True):
"""Load upgrade modules. :param remove_applied: if True, already applied upgrades will not be included, if False t... |
if remove_applied:
self.load_history()
for entry_point in iter_entry_points('invenio_upgrader.upgrades'):
upgrade = entry_point.load()()
self.__class__._upgrades[upgrade.name] = upgrade
return self.__class__._upgrades |
<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_graph(self, upgrades, history=None):
"""Create dependency graph from upgrades. :param upgrades: Dict of upgrades :param history: Dict of applied upgr... |
history = history or {}
graph_incoming = {} # nodes their incoming edges
graph_outgoing = {} # nodes their outgoing edges
# Create graph data structure
for mod in six.itervalues(upgrades):
# Remove all incoming edges from already applied upgrades
graph... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def order_upgrades(self, upgrades, history=None):
"""Order upgrades according to their dependencies. (topological sort using Kahn's algorithm - http://en.wikiped... |
history = history or {}
graph_incoming, graph_outgoing = self._create_graph(upgrades, history)
# Removed already applied upgrades (assumes all dependencies prior to
# this upgrade has been applied).
for node_id in six.iterkeys(history):
start_nodes = [node_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 _parse_plugin_id(self, plugin_id):
"""Determine repository from plugin id.""" |
m = re.match("(.+)(_\d{4}_\d{2}_\d{2}_)(.+)", plugin_id)
if m:
return m.group(1)
m = re.match("(.+)(_release_)(.+)", plugin_id)
if m:
return m.group(1)
raise RuntimeError("Repository could not be determined from "
"the upgrade ... |
<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_metar_from_mission( mission_file: str, icao: str = 'XXXX', time: str = None, ) -> str: """ Builds a dummy METAR string from a mission file Args: mission_f... |
return _MetarFromMission(
mission_file=mission_file,
icao=icao,
time=time,
).metar |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def metar(self) -> str: """ Builds a METAR string from a MIZ file A lots of information is inferred from what information we have available in DCS. There constrai... |
metar = f'{self._icao} ' \
f'{self._time} ' \
f'{self._wind} ' \
f'{self._visibility} ' \
f'{self._precipitations} ' \
f'{self._clouds} ' \
f'{self._temperature} ' \
f'{self._pressure} ' \
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def subtopics(store, folders, folder_id, subfolder_id, ann_id=None):
'''Yields an unordered generator of subtopics in a subfolder.
Each item of the generator is a 4-tuple of ``content_id``,
``subtopic_id``, ``subtopic_type`` and ``data``. Subtopic type
is one of the following Unicode strings: ``text``,... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def typed_subtopic_data(fc, subid):
'''Returns typed subtopic data from an FC.'''
# I don't think this code will change after we fix the data race bug. ---AG
ty = subtopic_type(subid)
data = get_unicode_feature(fc, subid)
assert isinstance(data, unicode), \
'data should be `unicode` but is %... |
<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(el, strip=True):
""" Return the text of a ``BeautifulSoup`` element """ |
if not el:
return ""
text = el.text
if strip:
text = text.strip()
return text |
<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(el, typ):
""" Parse a ``BeautifulSoup`` element as the given type. """ |
if not el:
return typ()
txt = text(el)
if not txt:
return typ()
return typ(txt) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parsebool(el):
""" Parse a ``BeautifulSoup`` element as a bool """ |
txt = text(el)
up = txt.upper()
if up == "OUI":
return True
if up == "NON":
return False
return bool(parseint(el)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def authenticate_device(self, api_token, device_token, email=None, user_url=None, override=False, fetch=True):
"""Set credentials for Device authentication. Args... |
if (self.context.has_auth_params('Gem-Device') and not override):
raise OverrideError('Gem-Device')
if (not api_token or
not device_token or
(not email and not user_url) or
not self.context.authorize('Gem-Device',
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 authenticate_identify(self, api_token, override=True):
"""Set credentials for Identify authentication. Args: api_token (str):
Token issued to your Applicati... |
if (self.context.has_auth_params('Gem-Identify') and not override):
raise OverrideError('Gem-Identify')
if (not api_token or
not self.context.authorize('Gem-Identify', api_token=api_token)):
raise AuthUsageError(self.context, 'Gem-Identify')
return 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 parse_options(arguments=None):
""" Reads command-line arguments """ |
if arguments is None:
arguments = sys.argv[1:]
if isinstance(arguments, str):
arguments = arguments.split()
if isinstance(arguments, argparse.Namespace):
return arguments
parser = create_args_parser()
args = parser.parse_args(arguments)
# pprint(args.__dict__)
args.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def assign_indent_numbers(lst, inum, dic=collections.defaultdict(int)):
""" Associate keywords with their respective indentation numbers """ |
for i in lst:
dic[i] = inum
return dic |
<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_url( width, height=None, background_color="cccccc", text_color="969696", text=None, random_background_color=False ):
""" Craft the URL for a placeholder ... |
if random_background_color:
background_color = _get_random_color()
# If height is not provided, presume it is will be a square
if not height:
height = width
d = dict(
width=width,
height=height,
bcolor=background_color,
tcolor=text_color
)
url = ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def preserve_builtin_query_params(url, request=None):
""" Given an incoming request, and an outgoing URL representation, append the value of any built-in query p... |
if request is None:
return url
overrides = [
api_settings.URL_FORMAT_OVERRIDE,
]
for param in overrides:
if param and (param in request.GET):
value = request.GET[param]
url = replace_query_param(url, param, value)
return url |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reverse(viewname, args=None, kwargs=None, request=None, format=None, **extra):
""" If versioning is being used then we pass any `reverse` calls through to th... |
scheme = getattr(request, 'versioning_scheme', None)
if scheme is not None:
try:
url = scheme.reverse(viewname, args, kwargs, request, format, **extra)
except NoReverseMatch:
# In case the versioning scheme reversal fails, fallback to the
# default implementa... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _reverse(viewname, args=None, kwargs=None, request=None, format=None, **extra):
""" Same as `django.core.urlresolvers.reverse`, but optionally takes a reques... |
if format is not None:
kwargs = kwargs or {}
kwargs['format'] = format
url = django_reverse(viewname, args=args, kwargs=kwargs, **extra)
if request:
return request.build_absolute_uri(url)
return url |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decompose(miz_file: Path, output_folder: Path):
""" Decompose this Miz into json Args: output_folder: folder to output the json structure as a Path miz_file:... |
mission_folder, assets_folder = NewMiz._get_subfolders(output_folder)
NewMiz._wipe_folders(mission_folder, assets_folder)
LOGGER.info('unzipping mission file')
with Miz(miz_file) as miz:
version = miz.mission.d['version']
LOGGER.debug(f'mission version: "%s"', ve... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def recompose(src: Path, target_file: Path):
""" Recompose a Miz from json object Args: src: folder containing the json structure target_file: target Miz file ""... |
mission_folder, assets_folder = NewMiz._get_subfolders(src)
# pylint: disable=c-extension-no-member
base_info = ujson.loads(Path(mission_folder, 'base_info.json').read_text(encoding=ENCODING))
version = base_info['__version__']
with Miz(target_file) as miz:
LOGGER.in... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle(self, *args, **options):
""" Sets options common to all commands. Any command subclassing this object should implement its own handle method, as is st... |
# Create a data directory
self.data_dir = os.path.join(
settings.BASE_DIR,
'data')
if not os.path.exists(self.data_dir):
os.makedirs(self.data_dir)
# Start the clock
self.start_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 _save_file(self, filename, contents):
"""write the html file contents to disk""" |
with open(filename, 'w') as f:
f.write(contents) |
<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_session(url):
"""Get db session. :param url: URL for connect with DB :type url: :class:`str` :returns: A sqlalchemy db session :rtype: :class:`sqlalchemy... |
engine = create_engine(url)
db_session = scoped_session(sessionmaker(engine))
Base.metadata.create_all(engine)
return db_session |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _AsynchronouslyGetProcessOutput(formattedCmd, printStdOut, printStdErr, **kwargs):
''' Asynchronously read the process '''
opts = filterKWArgsForFunc(kwargs, subprocess.Popen)
opts['stdout'] = subprocess.PIPE
opts['stderr'] = subprocess.PIPE
process = subprocess.Popen(formattedCmd, **opts)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def execute(cmd, verbosityThreshold = 1, **kwargs):
'''execute the passed in command in the shell'''
global exectue_defaults
opts = merge(exectue_defaults, kwargs) # the options computed from the default options together with the passed in options.
subopts = filterKWArgsForFunc(opts, subpro... |
<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_columns(self, table_name):
''' a method to extract the column properties of an existing table '''
import re
from sqlalchemy import MetaData, VARCHAR, INTEGER, BLOB, BOOLEAN, FLOAT
from sqlalchemy.dialects.postgresql import DOUBLE_PRECISION, BIT, BYTEA
... |
<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_columns(self):
''' a helper method for parsing the column properties from the record schema '''
# construct column list
column_map = {}
for key, value in self.model.keyMap.items():
record_key = key[1:]
if record_key:
if self.it... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.