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 get_work_unit_status(self, work_spec_name, work_unit_key):
'''Get a high-level status for some work unit.
The return value is a dictionary. The only required key is
``status``, which could be any of:
``missing``
The work unit does not exist anywhere
``available``... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def inspect_work_unit(self, work_spec_name, work_unit_key):
'''Get the data for some work unit.
Returns the data for that work unit, or `None` if it really
can't be found.
:param str work_spec_name: name of the work spec
:param str work_unit_key: name of the work unit
:... |
<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_all(self, work_spec_name):
'''Restart a work spec.
This calls :meth:`idle_all_workers`, then moves all finished
jobs back into the available queue.
.. deprecated:: 0.4.5
See :meth:`idle_all_workers` for problems with that method.
This also ignores fail... |
<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_dependent_work_units(self, work_unit, depends_on, hard=True):
"""Add work units, where one prevents execution of the other. The two work units may be att... |
# There's no good, not-confusing terminology here.
# I'll call work_unit "later" and depends_on "earlier"
# consistently, because that at least makes the time flow
# correct.
later_spec, later_unit, later_unitdef = work_unit
earlier_spec, earlier_unit, earlier_unitdef = ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def nice(self, work_spec_name, nice):
'''Change the priority of an existing work spec.'''
with self.registry.lock(identifier=self.worker_id) as session:
session.update(NICE_LEVELS, dict(work_spec_name=nice)) |
<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_assigned_work_unit(self, worker_id, work_spec_name,
work_unit_key):
'''get a specific WorkUnit that has already been assigned to a
particular worker_id
'''
with self.registry.lock(identifier=self.worker_id) as session:
assigned_work_unit... |
<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_child_work_units(self, worker_id):
'''Get work units assigned to a worker's children.
Returns a dictionary mapping worker ID to :class:`WorkUnit`.
If a child exists but is idle, that worker ID will map to
:const:`None`. The work unit may already be expired or
assigned 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 plotPlainImg(sim, cam, rawdata, t, odir):
""" No subplots, just a plan http://stackoverflow.com/questions/22408237/named-colors-in-matplotlib """ |
for R, C in zip(rawdata, cam):
fg = figure()
ax = fg.gca()
ax.set_axis_off() # no ticks
ax.imshow(R[t, :, :],
origin='lower',
vmin=max(C.clim[0], 1), vmax=C.clim[1],
cmap='gray')
ax.text(0.05, 0.075, datetime.utcfromtime... |
<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_nodes(api_url=None, verify=False, cert=list()):
""" Returns info for all Nodes :param api_url: Base PuppetDB API url """ |
return utils._make_api_request(api_url, '/nodes', verify, cert) |
<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_node(api_url=None, node_name=None, verify=False, cert=list()):
""" Returns info for a Node :param api_url: Base PuppetDB API url :param node_name: Name o... |
return utils._make_api_request(api_url, '/nodes/{0}'.format(node_name), verify, cert) |
<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_node_fact_by_name(api_url=None, node_name=None, fact_name=None, verify=False, cert=list()):
""" Returns specified fact for a Node :param api_url: Base Pu... |
return utils._make_api_request(api_url, '/nodes/{0}/facts/{1}'.format(node_name,
fact_name), verify, cert) |
<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_node_resource_by_type(api_url=None, node_name=None, type_name=None, verify=False, cert=list()):
""" Returns specified resource for a Node :param api_url:... |
return utils._make_api_request(api_url, '/nodes/{0}/resources/{1}'.format(node_name,
type_name), verify, cert) |
<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=None, *args, **kwargs):
""" Calls multiple time - with retry. :param request: :return: response """ |
if request is not None:
self.request = request
retry = self.request.configuration.retry
if not isinstance(retry, SimpleRetry):
raise Error('Currently only the fast retry strategy is supported')
last_exception = None
for i in range(0, retry.max_retry):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def field_to_long(value):
""" Converts given value to long if possible, otherwise None is returned. :param value: :return: """ |
if isinstance(value, (int, long)):
return long(value)
elif isinstance(value, basestring):
return bytes_to_long(from_hex(value))
else:
return 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 call_once(self, request=None, *args, **kwargs):
""" Performs one API request. Raises exception on failure. :param request: :param args: :param kwargs: :retur... |
if request is not None:
self.request = request
config = self.request.configuration
if config.http_method != EBConsts.HTTP_METHOD_POST or config.method != EBConsts.METHOD_REST:
raise Error('Not implemented yet, only REST POST method is allowed')
url = self.reque... |
<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_response(self, resp):
""" Checks response after request was made. Checks status of the response, mainly :param resp: :return: """ |
# For successful API call, response code will be 200 (OK)
if resp.ok:
json = resp.json()
self.response = ResponseHolder()
self.response.response = json
# Check the code
if 'status' not in json:
raise InvalidResponse('No statu... |
<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_email(filepaths, collection_name):
"""Create an email message object which implements the email.message.Message interface and which has the files to b... |
gallery = minus.CreateGallery()
if collection_name is not None:
gallery.SaveGallery(collection_name)
interface = TerminalInterface()
interface.new_section()
interface.message(\
'Uploading files to http://min.us/m%s...' % (gallery.reader_id,))
item_map = { }
for path in fi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def account_overview(object):
"""Create layout for user profile""" |
return Layout(
Container(
Row(
Column2(
Panel(
'Avatar',
Img(src="{}{}".format(settings.MEDIA_URL, object.avatar)),
collapse=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 add_exp_key(self, key, value, ex):
"Expired in seconds"
return self.c.set(key, value, ex) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unpack(iterable, count, fill=None):
""" The iter data unpack function. Example 1: In[1]: source = 'abc' In[2]: a, b = safe_unpack(source, 2) In[3]: print(a, ... |
iterable = list(enumerate(iterable))
cnt = count if count <= len(iterable) else len(iterable)
results = [iterable[i][1] for i in range(cnt)]
# results[len(results):len(results)] = [fill for i in range(count-cnt)]
results = merge(results, [fill for i in range(count-cnt)])
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 transpose_list(list_of_dicts):
"""Transpose a list of dicts to a dict of lists :param list_of_dicts: to transpose, as in the output from a parse call :return... |
res = {}
for d in list_of_dicts:
for k, v in d.items():
if k in res:
res[k].append(v)
else:
res[k] = [v]
return 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 noisy_wrap(__func: Callable) -> Callable: """Decorator to enable DebugPrint for a given function. Args: __func: Function to wrap Returns: Wrapped function """ |
# pylint: disable=missing-docstring
def wrapper(*args, **kwargs):
DebugPrint.enable()
try:
__func(*args, **kwargs)
finally:
DebugPrint.disable()
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 on_enter(__msg: Optional[Union[Callable, str]] = None) -> Callable: """Decorator to display a message when entering a function. Args: __msg: Message to displa... |
# pylint: disable=missing-docstring
def decorator(__func):
@wraps(__func)
def wrapper(*args, **kwargs):
if __msg:
print(__msg)
else:
print('Entering {!r}({!r})'.format(__func.__name__, __func))
return __func(*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 write(self, __text: str) -> None: """Write text to the debug stream. Args: __text: Text to write """ |
if __text == os.linesep:
self.handle.write(__text)
else:
frame = inspect.currentframe()
if frame is None:
filename = 'unknown'
lineno = 0
else:
outer = frame.f_back
filename = outer.f_code.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 enable() -> None: """Patch ``sys.stdout`` to use ``DebugPrint``.""" |
if not isinstance(sys.stdout, DebugPrint):
sys.stdout = DebugPrint(sys.stdout) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def starting(self):
""" Prints a startup message to stdout. """ |
ident = self.ident()
print('{} starting & consuming "{}".'.format(ident, self.to_consume))
if self.max_tasks:
print('{} will die after {} tasks.'.format(ident, self.max_tasks))
else:
print('{} will never die.'.format(ident)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def interrupt(self):
""" Prints an interrupt message to stdout. """ |
ident = self.ident()
print('{} for "{}" saw interrupt. Finishing in-progress task.'.format(
ident,
self.to_consume
)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stopping(self):
""" Prints a shutdown message to stdout. """ |
ident = self.ident()
print('{} for "{}" shutting down. Consumed {} tasks.'.format(
ident,
self.to_consume,
self.tasks_complete
)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run_forever(self):
""" Causes the worker to run either forever or until the ``Worker.max_tasks`` are reached. """ |
self.starting()
self.keep_running = True
def handle(signum, frame):
self.interrupt()
self.keep_running = False
signal.signal(signal.SIGINT, handle)
while self.keep_running:
if self.max_tasks and self.tasks_complete >= self.max_tasks:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def chdir(path):
"""Change the working directory to `path` for the duration of this context manager. :param str path: The path to change to """ |
cur_cwd = os.getcwd()
os.chdir(path)
try:
yield
finally:
os.chdir(cur_cwd) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def temp_file():
"""Create a temporary file for the duration of this context manager, deleting it afterwards. Yields: str - path to the file """ |
fd, path = tempfile.mkstemp()
os.close(fd)
try:
yield path
finally:
os.remove(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 skip_pickle_inject(app, what, name, obj, skip, options):
"""skip global wrapper._raw_slave names used only for pickle support""" |
if name.endswith('._raw_slave'):
return True
return 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 wraplet_signature(app, what, name, obj, options, signature, return_annotation):
"""have wrapplets use the signature of the slave""" |
try:
wrapped = obj._raw_slave
except AttributeError:
return None
else:
slave_argspec = autodoc.getargspec(wrapped)
slave_signature = autodoc.formatargspec(obj, *slave_argspec)
return (slave_signature, return_annotation) |
<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_users(path=settings.LOGIN_FILE):
""" Read passwd file and return dict with users and all their settings. Args: path (str, default settings.LOGIN_FILE):
... |
if not os.path.exists(path):
return {}
data = ""
with open(path) as f:
data = f.read().splitlines()
users = {}
cnt = 1
for line in data:
line = line.split(":")
assert len(line) == 7, "Bad number of fields in '%s', at line %d!" % (
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 set_permissions(filename, uid=None, gid=None, mode=0775):
""" Set pemissions for given `filename`. Args: filename (str):
name of the file/directory uid (int... |
if uid is None:
uid = get_ftp_uid()
if gid is None:
gid = -1
os.chown(filename, uid, gid)
os.chmod(filename, mode) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _decode_config(conf_str):
""" Decode string to configuration dict. Only values defined in settings._ALLOWED_MERGES can be redefined. """ |
conf_str = conf_str.strip()
# convert "tttff" -> [True, True, True, False, False]
conf = map(
lambda x: True if x.upper() == "T" else False,
list(conf_str)
)
return dict(zip(settings._ALLOWED_MERGES, conf)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _encode_config(conf_dict):
"""Encode `conf_dict` to string.""" |
out = []
# get variables in order defined in settings._ALLOWED_MERGES
for var in settings._ALLOWED_MERGES:
out.append(conf_dict[var])
# convert bools to chars
out = map(
lambda x: "t" if x else "f",
out
)
return "".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 read_user_config(username, path=settings.LOGIN_FILE):
""" Read user's configuration from otherwise unused field ``full_name`` in passwd file. Configuration i... |
return _decode_config(load_users(path=path)[username]["full_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 save_user_config(username, conf_dict, path=settings.LOGIN_FILE):
""" Save user's configuration to otherwise unused field ``full_name`` in passwd file. """ |
users = load_users(path=path)
users[username]["full_name"] = _encode_config(conf_dict)
save_users(users, path=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 create_ecdsap256_key_pair():
""" Create a new ECDSAP256 key pair. :returns: a tuple of the public and private keys """ |
pub = ECDSAP256PublicKey()
priv = ECDSAP256PrivateKey()
rc = _lib.xtt_crypto_create_ecdsap256_key_pair(pub.native, priv.native)
if rc == RC.SUCCESS:
return (pub, priv)
else:
raise error_from_code(rc) |
<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_option_default(option):
""" Given an optparse.Option, returns a two-tuple of the option's variable name and default value. """ |
return (
option.dest,
None if option.default is optparse.NO_DEFAULT else option.default,
) |
<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_command_class_from_apps(name, apps, exclude_packages=None, exclude_command_class=None):
""" Searches through the given apps to find the named command cla... |
if exclude_packages is None:
exclude_packages = []
for app in reversed(
[app for app in apps if not issubpackage(app, exclude_packages)]):
try:
command_class = import_module(
"{app:s}.management.commands.{name:s}".format(
app=app, name=nam... |
<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_command_class(name, exclude_packages=None, exclude_command_class=None):
""" Searches "django.core" and the apps in settings.INSTALLED_APPS to find the na... |
from django.conf import settings
return get_command_class_from_apps(
name,
settings.INSTALLED_APPS \
if "django.core" in settings.INSTALLED_APPS \
else ("django.core",) + tuple(settings.INSTALLED_APPS),
exclude_packages=exclude_packages,
exclude_command_... |
<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_program(name):
""" Uses the shell program "which" to determine whether the named program is available on the shell PATH. """ |
with open(os.devnull, "w") as null:
try:
subprocess.check_call(("which", name), stdout=null, stderr=null)
except subprocess.CalledProcessError as e:
return False
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 get_option_lists(self):
""" A hook to override the option lists used to generate option names and defaults. """ |
return [self.get_option_list()] + \
[option_list
for name, description, option_list
in self.get_option_groups()] |
<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_options(self):
""" A hook to override the flattened list of all options used to generate option names and defaults. """ |
return reduce(
list.__add__,
[list(option_list) for option_list in self.get_option_lists()],
[]) |
<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_parser(self, prog_name, subcommand):
""" Customize the parser to include option groups. """ |
parser = optparse.OptionParser(
prog=prog_name,
usage=self.usage(subcommand),
version=self.get_version(),
option_list=self.get_option_list())
for name, description, option_list in self.get_option_groups():
group = optparse.OptionGroup(parser, ... |
<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_command(self, name):
""" Checks whether the given Django management command exists, excluding this command from the search. """ |
if not check_command(
name,
exclude_packages=self.get_exclude_packages(),
exclude_command_class=self.__class__):
raise management.CommandError(
"The management command \"{name:s}\" is not available. "
"Please ensure that you've ad... |
<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_program(self, name):
""" Checks whether a program is available on the shell PATH. """ |
if not check_program(name):
raise management.CommandError(
"The program \"{name:s}\" is not available in the shell. "
"Please ensure that \"{name:s}\" is installed and reachable "
"through your PATH environment variable.".format(
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 call_command(self, name, *arguments, **options):
""" Finds the given Django management command and default options, excluding this command, and calls it with... |
command, defaults = get_command_and_defaults(
name,
exclude_packages=self.get_exclude_packages(),
exclude_command_class=self.__class__)
if command is None:
raise management.CommandError(
"Unknown command: {name:s}".format(
... |
<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_program(self, name, *arguments):
""" Calls the shell program on the PATH with the given arguments. """ |
verbosity = self.options.get("verbosity", 1)
with self.devnull as null:
try:
subprocess.check_call((name,) + tuple(arguments),
stdout=null if verbosity == 0 else self.stdout,
stderr=null if verbosity == 0 else self.stderr)
... |
<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_score(self):
"""Update the relevance score for this thread. The score is calculated with the following variables: * vote_weight: 100 - (minus) 1 for e... |
if not self.subject_token:
return
vote_score = 0
replies_score = 0
for msg in self.message_set.all():
# Calculate replies_score
replies_score += self._get_score(300, msg.received_time)
# Calculate vote_score
for vote in msg.... |
<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(self):
"""Shortcut to get thread url""" |
return reverse('archives:thread_view',
args=[self.mailinglist.name,
self.thread.subject_token]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def print_config():
# pragma: no cover """Print config entry function.""" |
description = """\
Print the deployment settings for a Pyramid application. Example:
'psettings deployment.ini'
"""
parser = argparse.ArgumentParser(
description=textwrap.dedent(description)
)
parser.add_argument(
'config_uri', type=str, help='an integer for the acc... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def printer(data, depth=0):
""" Prepare data for printing. :param data: a data value that will be processed by method :param int depth: recurrency indicator, to ... |
indent = _INDENT * depth
config_string = '' if not depth else ':\n'
if isinstance(data, dict):
for key, val in data.items():
line = '{0}{1}'.format(indent, key)
values = printer(val, depth + 1)
if not values.count('\n'):
values = ': {0}'.format(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 slice_config(config, key):
""" Slice config for printing as defined in key. :param ConfigManager config: configuration dictionary :param str key: dotted key,... |
if key:
keys = key.split('.')
for k in keys:
config = config[k]
return config |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def split_size(size):
'''Split the file size into several chunks.'''
rem = size % CHUNK_SIZE
if rem == 0:
cnt = size // CHUNK_SIZE
else:
cnt = size // CHUNK_SIZE + 1
chunks = []
for i in range(cnt):
pos = i * CHUNK_SIZE
if i == cnt - 1:
disp = size - ... |
<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_fd(inf, outf):
'''Reverse the content of inf, write to outf.
Both inf and outf are file objects.
inf must be seekable.
'''
inf.seek(0, 2)
size = inf.tell()
if not size:
return
chunks = split_size(size)
for chunk in reversed(chunks):
inf.seek(chunk[0], 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 reverse_file(infile, outfile):
'''Reverse the content of infile, write to outfile.
Both infile and outfile are filenames or filepaths.
'''
with open(infile, 'rb') as inf:
with open(outfile, 'wb') as outf:
reverse_fd(inf, outf) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def print(self, *objects, **kwargs):
"""Micmic print interface""" |
file = kwargs.get("file")
if file is not None and file is not sys.stdout:
PRINT(*objects, **kwargs)
else:
sep = STR(kwargs.get("sep", " "))
end = STR(kwargs.get("end", "\n"))
text = sep.join(STR(o) for o in objects)
self.imp_print(text, end)
for callback in self.listeners:
callback(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 imp_print(self, text, end):
"""Directly send utf8 bytes to stdout""" |
sys.stdout.write((text + end).encode("utf-8")) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def restore(cdiff, a):
"""Restores the full text of either the edited text using the compressed diff. Args: cdiff (dict):
compressed diff returned by :func:`~ac... |
left = a.splitlines(1) if isinstance(a, string_types) else a
lrest = []
iline = 0
for i, line in enumerate(left):
if iline not in cdiff:
lrest.append(" " + line)
iline += 1
else:
cs = [l[0] for l in cdiff[iline]]
add = cs.count('+') ... |
<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, color=True):
""" Craft the URL for a placekitten image. By default they are in color. To retrieve a grayscale image, set the color kwa... |
d = dict(width=width, height=height)
return URL % 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 instance():
"""Returns a global `IOLoop` instance. Most applications have a single, global `IOLoop` running on the main thread. Use this method to get this i... |
if not hasattr(IOLoop, "_instance"):
with IOLoop._instance_lock:
if not hasattr(IOLoop, "_instance"):
# New instance after double check
IOLoop._instance = IOLoop()
return IOLoop._instance |
<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_paste(self, content):
"""Create a raw paste of the given content. Returns a URL to the paste, or raises a ``pasteraw.Error`` if something tragic happe... |
r = requests.post(
self.endpoint + '/pastes',
data={'content': content},
allow_redirects=False)
if r.status_code == 302:
return r.headers['Location']
if r.status_code == 413:
raise MaxLengthExceeded('%d bytes' % len(content))
... |
<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_keys(inp, p=False):
"""Takes a comma-separated string of key ids or fingerprints and returns a list of key ids""" |
_keys = []
ssh_keys = DO.get_ssh_keys()
for k in inp.split(","):
done = False
if k.isdigit():
for _ in [s for s in ssh_keys if s["id"] == int(k)]:
done = True
_keys.append(_["fingerprint"])
else:
for _ in [s for s in ssh_keys 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 cd(cd_path, create=False):
"""cd to target dir when running in this block :param cd_path: dir to cd into :param create: create new dir if destination not the... |
oricwd = os.getcwd()
if create:
mkdir(cd_path)
try:
os.chdir(cd_path)
yield
finally:
os.chdir(oricwd) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cd_to(path, mkdir=False):
"""make a generator like cd, but use it for function Usage:: / """ |
def cd_to_decorator(func):
@functools.wraps(func)
def _cd_and_exec(*args, **kwargs):
with cd(path, mkdir):
return func(*args, **kwargs)
return _cd_and_exec
return cd_to_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 require_python(minimum):
"""Require at least a minimum Python version. The version number is expressed in terms of `sys.hexversion`. E.g. to require a minimu... |
if sys.hexversion < minimum:
hversion = hex(minimum)[2:]
if len(hversion) % 2 != 0:
hversion = '0' + hversion
split = list(hversion)
parts = []
while split:
parts.append(int(''.join((split.pop(0), split.pop(0))), 16))
major, minor, micro, rele... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def long_description(*filenames):
"""Provide a long description.""" |
res = ['']
for filename in filenames:
with open(filename) as fp:
for line in fp:
res.append(' ' + line)
res.append('')
res.append('\n')
return EMPTYSTRING.join(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 description(filename):
"""Provide a short description.""" |
# This ends up in the Summary header for PKG-INFO and it should be a
# one-liner. It will get rendered on the package page just below the
# package version header but above the long_description, which ironically
# gets stuff into the Description header. It should not include reST, so
# pick out t... |
<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 fetch_house(self, house_id):
"""Lookup details for a given house id""" |
url = "https://production.plum.technology/v2/getHouse"
data = {"hid": house_id}
return await self.__post(url, data) |
<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 fetch_room(self, room_id):
"""Lookup details for a given room id""" |
url = "https://production.plum.technology/v2/getRoom"
data = {"rid": room_id}
return await self.__post(url, data) |
<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 fetch_logical_load(self, llid):
"""Lookup details for a given logical load""" |
url = "https://production.plum.technology/v2/getLogicalLoad"
data = {"llid": llid}
return await self.__post(url, data) |
<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 fetch_lightpad(self, lpid):
"""Lookup details for a given lightpad""" |
url = "https://production.plum.technology/v2/getLightpad"
data = {"lpid": lpid}
return await self.__post(url, 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 to_bytes(s, encoding="utf-8"):
""" Converts the string to a bytes type, if not already. :s: the string to convert to bytes :returns: `str` on Python2 and `by... |
if isinstance(s, six.binary_type):
return s
else:
return six.text_type(s).encode(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 to_text(s, encoding="utf-8"):
""" Converts the bytes to a text type, if not already. :s: the bytes to convert to text :returns: `unicode` on Python2 and `str... |
if isinstance(s, six.text_type):
return s
else:
return six.binary_type(s).decode(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 _check_len(a, b):
""" Raises an exception if the two values do not have the same length. This is useful for validating preconditions. :a: the first value :b:... |
if len(a) != len(b):
msg = "Length must be {}. Got {}".format(len(a), len(b))
raise ValueError(msg) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def similarity1DdiffShapedArrays(arr1, arr2, normalize=False):
""" compare two strictly monotonous increasing 1d arrays of same or different size return a simila... |
# assign longer and shorter here, because jit cannot do it
if len(arr1) < len(arr2):
arr1, arr2 = arr2, arr1
if not len(arr2):
out = sum(arr1)
else:
out = _calc(arr1, arr2)
if normalize:
if not len(arr2):
mn = arr1[0]
mx = arr1[-1]
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 get_instance( model, method="file", img_dir=None, data_dir=None, bucket=None ):
"""Return an instance of ConsumeStore.""" |
global _instances
if not isinstance(model, ConsumeModel):
raise TypeError(
"get_instance() expects a parker.ConsumeModel derivative."
)
if method == "file":
my_store = store.get_filestore_instance(
img_dir=img_dir,
data_dir=data_dir
)
... |
<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_media(self):
"""Store any media within model.media_list.""" |
chunk_path = fileops.get_chunk_path_from_string(
self.model.unique_field
)
for i, mediafile in enumerate(self.model.media_list):
filename = os.path.join(
self._get_prefix(),
chunk_path,
"%s_%d" % (self.model.unique_field, ... |
<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_data(self):
"""Store data as a JSON dump.""" |
filename = os.path.join(
self._get_prefix(),
self.model.site
)
self.store.store_json(
filename,
self.model.get_dict()
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def findloop(m):
"""Determines if the specified member of `_ast` contains any for or while loops in its body definition. """ |
from _ast import For, While, FunctionDef, ClassDef, ListComp
from _ast import DictComp
if isinstance(m, (FunctionDef, ClassDef)):
return False
elif isinstance(m, (For, While, ListComp, DictComp)):
return True
elif hasattr(m, "value"):
return findloop(m.value)
elif ha... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def record_markdown(text, cellid):
"""Records the specified markdown text to the acorn database. Args: text (str):
the *raw* markdown text entered into the cell... |
from acorn.logging.database import record
from time import time
ekey = "nb-{}".format(cellid)
global _cellid_map
if cellid not in _cellid_map:
from acorn.logging.database import active_db
from difflib import SequenceMatcher
from acorn.logging.diff import cascade
... |
<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_ipython_extension(ip):
"""Loads the interacting decorator that ships with `acorn` into the ipython interactive shell. Args: ip (IPython.core.interactive... |
decor = InteractiveDecorator(ip)
ip.events.register('post_run_cell', decor.post_run_cell)
#Unfortunately, the built-in "pre-execute" and "pre-run" methods are
#triggered *before* the input from the cell has been stored to
#history. Thus, we don't have access to the actual code that is about to be
... |
<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_decoratables(self, atype):
"""Returns a list of the objects that need to be decorated in the current user namespace based on their type. Args: atype (st... |
result = []
defmsg = "Skipping {}; not decoratable or already decorated."
for varname in self.shell.run_line_magic("who_ls", atype):
varobj = self.shell.user_ns.get(varname, None)
decorate = False
if varobj is None: # Nothing useful can be done.
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _logdef(self, n, o, otype):
"""Logs the definition of the object that was just auto-decorated inside the `ipython` notebook. """ |
import re
try:
#The latest input cell will be the one that this got executed
#from. TODO: actually, if acorn got imported after the fact, then
#the import would have caused all the undecorated functions to be
#decorated as soon as acorn imported. I suppos... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _decorate(self, atype, n, o):
"""Decorates the specified object for automatic logging with acorn. Args: atype (str):
one of the types specified in :attr:`at... |
typemap = {"function": "functions",
"classobj": "classes",
"staticmethod": "methods",
"type": "classes"}
from acorn.logging.decoration import decorate_obj
try:
otype = typemap[atype]
decorate_obj(self.shell.user_ns... |
<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_run_cell(self):
"""Runs after the user-entered code in a cell has been executed. It detects any new, decoratable objects that haven't been decorated yet... |
#We just want to detect any new, decoratable objects that haven't been
#decorated yet.
decorlist = {k: [] for k in self.atypes}
for atype in self.atypes:
for n, o in self._get_decoratables(atype):
self._decorate(atype, n, o)
#Next, check whether we h... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _var_changes(self):
"""Determines the list of variables whose values have changed since the last cell execution. """ |
result = []
variables = self.shell.run_line_magic("who_ls", "")
if variables is None:
return result
import inspect
for varname in variables:
varobj = self.shell.user_ns.get(varname, None)
if varobj is None:
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 pre_run_cell(self, cellno, code):
"""Executes before the user-entered code in `ipython` is run. This intercepts loops and other problematic code that would p... |
#First, we look for loops and list/dict comprehensions in the code. Find
#the id of the latest cell that was executed.
self.cellid = cellno
#If there is a loop somewhere in the code, it could generate millions of
#database entries and make the notebook unusable.
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def inverseHistogram(hist, bin_range):
"""sample data from given histogram and min, max values within range Returns: np.array: data that would create the same hi... |
data = hist.astype(float) / np.min(hist[np.nonzero(hist)])
new_data = np.empty(shape=np.sum(data, dtype=int))
i = 0
xvals = np.linspace(bin_range[0], bin_range[1], len(data))
for d, x in zip(data, xvals):
new_data[i:i + d] = x
i += int(d)
return new_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 watermark_image(image, wtrmrk_path, corner=2):
'''Adds a watermark image to an instance of a PIL Image.
If the provided watermark image (wtrmrk_path) is
larger than the provided base image (image), then
the watermark image will be automatically resized to
roughly 1/8 the size of the base image... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def watermark_text(image, text, corner=2):
'''Adds a text watermark to an instance of a PIL Image.
The text will be sized so that the height of the text is
roughly 1/20th the height of the base image. The text will
be white with a thin black outline.
Args:
image: An instance of a PIL Imag... |
<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(msg, *args, **kwargs):
""" Print out a log message. """ |
if len(args) == 0 and len(kwargs) == 0:
print(msg)
else:
print(msg.format(*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 logv(msg, *args, **kwargs):
""" Print out a log message, only if verbose mode. """ |
if settings.VERBOSE:
log(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 _csv_to_nodes_dict(nodes_csv):
"""Convert CSV to a list of dicts formatted for os_cloud_config Given a CSV file in the format below, convert it into the stru... |
data = []
for row in csv.reader(nodes_csv):
node = {
"pm_user": row[2],
"pm_addr": row[1],
"pm_password": row[3],
"pm_type": row[0],
"mac": [
row[4]
]
}
data.append(node)
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 assign(A, attr, B, lock=False):
'''Assigns B to A.attr, yields, and then assigns A.attr back to its
original value.
'''
class NoAttr(object): pass
context = threading.Lock if lock else null_context
with context():
if not hasattr(A, attr):
tmp = NoAttr
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 delete(*args):
'''For using then deleting objects.'''
from syn.base_utils import this_module
mod = this_module(npop=3)
yield
for arg in args:
name = arg
if not isinstance(name, STR):
name = arg.__name__
delattr(mod, 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 serialize_job(job):
"""Return a dictionary representing the job.""" |
d = dict(
id=job.get_id(),
uri=url_for('jobs.get_job', job_id=job.get_id(), _external=True),
status=job.get_status(),
result=job.result
)
return d |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.