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 now(utc=False):
"""Returns the current time. :param utc: If ``True``, returns a timezone-aware ``datetime`` object in UTC. When ``False`` (the default), retu... |
if utc:
return datetime.datetime.utcnow().replace(tzinfo=dateutil.tz.tzutc())
else:
return 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 merge_envs(*args):
"""Union of one or more dictionaries. In case of duplicate keys, the values in the right-most arguments will squash (overwrite) the value ... |
env = {}
for arg in args:
if not arg:
continue
env.update(arg)
return env |
<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_once(name, cmd, env, shutdown, loop=None, utc=False):
"""Starts a child process and waits for its completion. .. note:: This function is a coroutine. Sta... |
# Get the default event loop if necessary.
loop = loop or asyncio.get_event_loop()
# Launch the command into a child process.
if isinstance(cmd, str):
cmd = shlex.split(cmd)
process = yield from asyncio.create_subprocess_exec(
*cmd,
env=env,
stdin=asyncio.subproces... |
<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_and_respawn(shutdown, loop=None, **kwds):
"""Starts a child process and re-spawns it every time it completes. .. note:: This function is a coroutine. :pa... |
# Get the default event loop if necessary.
loop = loop or asyncio.get_event_loop()
while not shutdown.done():
t = loop.create_task(run_once(shutdown=shutdown, loop=loop, **kwds))
yield from 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 add_date(log):
'''Userful for randomizing the name of a log'''
return '{base} - {time}.log'.format(
base=os.path.splitext(log)[0],
time=strftime("%a, %d %b %Y %H-%M-%S", gmtime())) |
<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_log(self, log):
'''check we don't delte anythin unintended'''
if os.path.splitext(log)[-1] != '.log':
raise Exception('File without .log was passed in for deletoin')
with suppress(Exception):
os.remove(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 get_logs(self):
'''returns logs from disk, requires .log extenstion'''
folder = os.path.dirname(self.pcfg['log_file'])
for path, dir, files in os.walk(folder):
for file in files:
if os.path.splitext(file)[-1] == '.log':
yield os.path.join(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 _uniquename(self, log):
'''
renames the log to ensure we get no clashes on the server
subclass this to change the path etc'''
return '{hostname} - {time}.log'.format(
hostname=os.getenv('USERNAME'),
time=strftime("%a, %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 arg_strings(parsed_args, name=None):
"""A list of all strings for the named arg""" |
name = name or 'arg_strings'
value = getattr(parsed_args, name, [])
if isinstance(value, str):
return [value]
try:
return [v for v in value if isinstance(v, str)]
except TypeError:
return [] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_module_file(txt, directory):
"""Create a file in the given directory with a valid module name populated with the given txt. Returns: A path to the fil... |
name = nonpresent_module_filename()
path = os.path.join(directory, name)
with open(path, 'w') as fh:
fh.write(txt)
return path |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def nonpresent_module_filename():
"""Return module name that doesn't already exist""" |
while True:
module_name = get_random_name()
loader = pkgutil.find_loader(module_name)
if loader is not None:
continue
importlib.invalidate_caches()
return "{}.py".format(module_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 get_random_name():
"""Return random lowercase name""" |
char_seq = []
name_source = random.randint(1, 2**8-1)
current_value = name_source
while current_value > 0:
char_offset = current_value % 26
current_value = current_value - random.randint(1, 26)
char_seq.append(chr(char_offset + ord('a')))
name = ''.join(char_seq)
assert ... |
<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_header_dict(response, header):
""" returns a dictionary of the cache control headers the same as is used by django.utils.cache.patch_cache_control if the... |
def dictitem(s):
t = s.split('=', 1)
if len(t) > 1:
return (t[0].lower(), t[1])
else:
return (t[0].lower(), True)
if response.has_header(header):
hd = dict([dictitem(el) for el in cc_delim_re.split(response[header])])
else:
hd= {}
return ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_header_dict(response, header, header_dict):
"""Formats and sets a header dict in a response, inververs of get_header_dict.""" |
def dictvalue(t):
if t[1] is True:
return t[0]
return t[0] + '=' + smart_str(t[1])
response[header] = ', '.join([dictvalue(el) for el in header_dict.items()]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def smart_import(mpath):
"""Given a path smart_import will import the module and return the attr reffered to.""" |
try:
rest = __import__(mpath)
except ImportError:
split = mpath.split('.')
rest = smart_import('.'.join(split[:-1]))
rest = getattr(rest, split[-1])
return rest |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def strip_wsgi(request):
"""Strip WSGI data out of the request META data.""" |
meta = copy(request.META)
for key in meta:
if key[:4] == 'wsgi':
meta[key] = None
return meta |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def patch_headers(self, response):
"""Set the headers we want for caching.""" |
# Remove Vary:Cookie if we want to cache non-anonymous
if not getattr(settings, 'BETTERCACHE_ANONYMOUS_ONLY', False):
vdict = get_header_dict(response, 'Vary')
try:
vdict.pop('cookie')
except KeyError:
pass
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 should_cache(self, request, response):
""" Given the request and response should it be cached """ |
if not getattr(request, '_cache_update_cache', False):
return False
if not response.status_code in getattr(settings, 'BETTERCACHE_CACHEABLE_STATUS', CACHEABLE_STATUS):
return False
if getattr(settings, 'BETTERCACHE_ANONYMOUS_ONLY', False) and self.session_accessed and r... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def should_regenerate(self, response):
""" Check if this page was originally generated less than LOCAL_POSTCHECK seconds ago """ |
if response.has_header('Last-Modified'):
last_modified = parse_http_date(response['Last-Modified'])
next_regen = last_modified + settings.BETTERCACHE_LOCAL_POSTCHECK
return time.time() > next_regen |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def has_uncacheable_headers(self, response):
""" Should this response be cached based on it's headers broken out from should_cache for flexibility """ |
cc_dict = get_header_dict(response, 'Cache-Control')
if cc_dict:
if 'max-age' in cc_dict and cc_dict['max-age'] == '0':
return True
if 'no-cache' in cc_dict:
return True
if 'private' in cc_dict:
return True
if ... |
<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_cache(self, request, response):
""" caches the response supresses and logs exceptions""" |
try:
cache_key = self.cache_key(request)
#presumably this is to deal with requests with attr functions that won't pickle
if hasattr(response, 'render') and callable(response.render):
response.add_post_render_callback(lambda r: cache.set(cache_key, (r, time.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 cache_key(self, request, method=None):
""" the cache key is the absolute uri and the request method """ |
if method is None:
method = request.method
return "bettercache_page:%s:%s" %(request.build_absolute_uri(), method) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send_task(self, request, response):
"""send off a celery task for the current page and recache""" |
# TODO is this too messy?
from bettercache.tasks import GeneratePage
try:
GeneratePage.apply_async((strip_wsgi(request),))
except:
logger.error("failed to send celery task")
self.set_cache(request, response) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def entity_to_unicode(string):
""" Quick convert unicode HTML entities to unicode characters using a regular expression replacement """ |
# Selected character replacements that have been seen
replacements = []
replacements.append((r"α", u"\u03b1"))
replacements.append((r"β", u"\u03b2"))
replacements.append((r"γ", u"\u03b3"))
replacements.append((r"δ", u"\u03b4"))
replacements.append((r"ε", u"\u0... |
<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_tag(tag_name, string):
""" Remove open and close tags - the tags themselves only - using a non-greedy angle bracket pattern match """ |
if not string:
return string
pattern = re.compile('</?' + tag_name + '.*?>')
string = pattern.sub('', string)
return string |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def version_from_xml_filename(filename):
"extract the numeric version from the xml filename"
try:
filename_parts = filename.split(os.sep)[-1].split('-')
except AttributeError:
return None
if len(filename_parts) == 3:
try:
return int(filename_parts[-1].lstrip('v').rstr... |
<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_last_commit_to_master(repo_path="."):
""" returns the last commit on the master branch. It would be more ideal to get the commit from the branch we are c... |
last_commit = None
repo = None
try:
repo = Repo(repo_path)
except (InvalidGitRepositoryError, NoSuchPathError):
repo = None
if repo:
try:
last_commit = repo.commits()[0]
except AttributeError:
# Optimised for version 0.3.2.RC1
last... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calculate_journal_volume(pub_date, year):
""" volume value is based on the pub date year pub_date is a python time object """ |
try:
volume = str(pub_date.tm_year - year + 1)
except TypeError:
volume = None
except AttributeError:
volume = None
return volume |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def author_name_from_json(author_json):
"concatenate an author name from json data"
author_name = None
if author_json.get('type'):
if author_json.get('type') == 'group' and author_json.get('name'):
author_name = author_json.get('name')
elif author_json.get('type') == 'person' and... |
<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_from_affiliation_elements(department, institution, city, country):
"format an author affiliation from details"
return ', '.join(element for element in [department, institution, city, country] if element) |
<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_variants(fns, remove=['DBSNP'], keep_only=True, min_tumor_f=0.1, min_tumor_cov=14, min_normal_cov=8):
"""Read muTect results from the list of files fns ... |
variants = []
for i, f in enumerate(fns):
# If keep_only, use awk to only grab those lines for big speedup.
if keep_only:
from numpy import dtype
import subprocess
res = subprocess.check_output(
'awk \'$35 == "KEEP"\' {}'.format(f), shell=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 traverse(self, traverser, **kwargs):
""" Implementation of mandatory interface for traversing the whole rule tree. This method will call the ``traverse`` met... |
result = self.rule.traverse(traverser, **kwargs)
return self.conversion(result) |
<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_variable_compilation(self, path, compilation_cbk, listclass):
""" Register given compilation method for variable on given path. :param str path: JPa... |
self.compilations_variable[path] = {
'callback': compilation_cbk,
'listclass': listclass
} |
<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_function_compilation(self, func, compilation_cbk, listclass):
""" Register given compilation method for given function. :param str path: Function na... |
self.compilations_function[func] = {
'callback': compilation_cbk,
'listclass': listclass
} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _cor_compile(rule, var, val, result_class, key, compilation_list):
""" Actual compilation worker method. """ |
compilation = compilation_list.get(key, None)
if compilation:
if isinstance(val, ListRule):
result = []
for itemv in val.value:
result.append(compilation['callback'](itemv))
val = compilation['listclass'](result)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _compile_operation_rule(self, rule, left, right, result_class):
""" Compile given operation rule, when possible for given compination of operation operands. ... |
# Make sure variables always have constant with correct datatype on the
# opposite side of operation.
if isinstance(left, VariableRule) and isinstance(right, (ConstantRule, ListRule)):
return self._cor_compile(
rule,
left,
right,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _calculate_operation_math(self, rule, left, right):
""" Perform compilation of given math operation by actually calculating given math expression. """ |
# Attempt to keep integer data type for the result, when possible.
if isinstance(left, IntegerRule) and isinstance(right, IntegerRule):
result = self.evaluate_binop_math(rule.operation, left.value, right.value)
if isinstance(result, list):
return ListRule([Integ... |
<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_db(directory, engine=None):
"""Get a database :param directory: The root data directory :param engine: a pre-created SQLAlchemy engine (default: in-memor... |
if engine is None:
engine = create_engine('sqlite://')
tables.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
db = Session()
if directory is not None:
load_from_directory(db, directory)
return db |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bind_unix_socket(file_, mode=0o600, backlog=_DEFAULT_BACKLOG):
"""Creates a listening unix socket. If a socket with the given name already exists, it will be... |
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.setblocking(0)
try:
st = os.stat(file_)
except OSError as err:
if err.errno != errno.ENOENT:
raise
else:
if stat.S_ISSOCK(st.st_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 firsthash(frame, removedupes=False):
'''
Hashes the first time step. Only will work as long as
the hash can fit in a uint64.
Parameters:
-----------
frame : first frame.
Keywords:
---------
removedups: specify duplicates for the given frame.
Returns a dictionary of... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def genhash(frame,**kw):
'''
Generate the hashes for the given frame for a specification
given in the dictionary d returned from firsthash.
Parameters:
-----------
frame : frame to hash.
Keywords:
---------
d : hash specification generated from firsthash.
new ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def addhash(frame,**kw):
'''
helper function to add hashes to the given frame
given in the dictionary d returned from firsthash.
Parameters:
-----------
frame : frame to hash.
Keywords:
---------
same as genhash
Returns frame with added hashes, although it will be add... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def sortframe(frame):
'''
sorts particles for a frame
'''
d = frame['data'];
sortedargs = np.lexsort([d['xi'],d['yi'],d['zi']])
d = d[sortedargs];
frame['data']=d;
return frame; |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def read_and_hash(fname, **kw):
'''
Read and and addhash each frame.
'''
return [addhash(frame, **kw) for frame in read(fname, **kw)]; |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def filter_hashes_from_file(fname, f, **kw):
'''
Obtain good hashes from a .p4 file with the dict hashd and a
function that returns good hashes. Any keywords will be
sent to read_and_hash.
Parameters:
-----------
fname -- filename of file.
f -- function that returns a list of good ... |
<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_match(self, step) -> list: """Like matchers.CFParseMatcher.check_match but also add the implicit parameters from the context """ |
args = []
match = super().check_match(step)
if match is None:
return None
for arg in match:
args.append(model.Argument.from_argument(arg))
for arg in self.context_params:
args.append(model.Argument(0, 0, "", None, name=arg, implicit=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 convert(self, pattern: str) -> str: """Convert the goat step string to CFParse String""" |
parameters = OrderedDict()
for parameter in self.signature.parameters.values():
annotation = self.convert_type_to_parse_type(parameter)
parameters[parameter.name] = "{%s:%s}" % (parameter.name, annotation)
formatter = GoatFormatter()
# We have to use vformat he... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def xml_to_json(root, tag_prefix=None, on_tag={}):
'''
Parses a XML element to JSON format.
This is a relatively generic function parsing a XML element
to JSON format. It does not guarantee any specific formal
behaviour but is empirically known to "work well" with respect
to the author's needs.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _textwrap_slices(text, width, strip_leading_indent=False):
""" Nearly identical to textwrap.wrap except this routine is a tad bit safer in its algo that text... |
if not isinstance(text, str):
raise TypeError("Expected `str` type")
chunks = (x for x in _textwrap_word_break.split(text) if x)
remaining = width
buf = []
lines = [buf]
whitespace = []
whitespace_len = 0
pos = 0
try:
chunk = next(chunks)
except StopIteration:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def vtmlrender(vtmarkup, plain=None, strict=False, vtmlparser=VTMLParser()):
""" Look for vt100 markup and render vt opcodes into a VTMLBuffer. """ |
if isinstance(vtmarkup, VTMLBuffer):
return vtmarkup.plain() if plain else vtmarkup
try:
vtmlparser.feed(vtmarkup)
vtmlparser.close()
except:
if strict:
raise
buf = VTMLBuffer()
buf.append_str(str(vtmarkup))
return buf
else:
bu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clean_text(value, topic=False):
""" Replaces "profane" words with more suitable ones. Uses bleach to strip all but whitelisted html. Converts bbcode to Markd... |
for x in PROFANITY_REPLACEMENTS:
value = value.replace(x[0], x[1])
for bbset in BBCODE_REPLACEMENTS:
p = re.compile(bbset[0], re.DOTALL)
value = p.sub(bbset[1], value)
bleached = bleach.clean(value, tags=ALLOWED_TAGS, attributes=ALLOWED_ATTRIBUTES, strip=True)
# We want to re... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_email_simple(value):
"""Return True if value looks like an email address.""" |
# An @ must be in the middle of the value.
if '@' not in value or value.startswith('@') or value.endswith('@'):
return False
try:
p1, p2 = value.split('@')
except ValueError:
# value contains more than one @.
return False
# Dot mus... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convert_links(text, trim_url_limit=None, nofollow=False, autoescape=False):
""" Finds URLs in text and attempts to handle correctly. Heavily based on django.... |
safe_input = isinstance(text, SafeData)
words = word_split_re.split(force_text(text))
for i, word in enumerate(words):
if '.' in word or ':' in word:
# Deal with punctuation.
lead, middle, trail = '', word, ''
stripped = middle.rstrip(TRAILING_PUNCTUATION_CHARS)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pool_process(func, iterable, cpus=cpu_count(), return_vals=False, cpu_reduction=0, progress_bar=False):
""" Multiprocessing helper function for performing lo... |
with Pool(cpus - abs(cpu_reduction)) as pool:
# Return values returned by 'func'
if return_vals:
# Show progress bar
if progress_bar:
vals = [v for v in tqdm(pool.imap_unordered(func, iterable), total=len(iterable))]
# No progress bar
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def map(self):
"""Perform a function on every item in an iterable.""" |
with Pool(self.cpu_count) as pool:
pool.map(self._func, self._iterable)
pool.close()
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 map_return(self):
"""Perform a function on every item and return a list of yield values.""" |
with Pool(self.cpu_count) as pool:
vals = pool.map(self._func, self._iterable)
pool.close()
return vals |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def map_tqdm(self):
""" Perform a function on every item while displaying a progress bar. :return: A list of yielded values """ |
with Pool(self.cpu_count) as pool:
vals = [v for v in tqdm(pool.imap_unordered(self._func, self._iterable), total=len(self._iterable))]
pool.close()
return vals |
<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_by_line(content):
"""Split the given content into a list of items by newline. Both \r\n and \n are supported. This is done since it seems that TTY devi... |
# Make sure we don't end up splitting a string with
# just a single trailing \n or \r\n into multiple parts.
stripped = content.strip()
if not stripped:
return []
if '\r\n' in stripped:
return _strip_all(stripped.split('\r\n'))
if '\n' in stripped:
return _strip_all(str... |
<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_release_id(version=None):
"""Get a unique, time-based identifier for a deployment that optionally, also includes some sort of version number or release. ... |
# pylint: disable=invalid-name
ts = datetime.utcnow().strftime(RELEASE_DATE_FMT)
if version is None:
return ts
return '{0}-{1}'.format(ts, version) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def try_repeatedly(method, max_retries=None, delay=None):
"""Execute the given Fabric call, retrying up to a certain number of times. The method is expected to b... |
max_retries = max_retries if max_retries is not None else 1
delay = delay if delay is not None else 0
tries = 0
with warn_only():
while tries < max_retries:
res = method()
if not res.failed:
return res
tries += 1
time.sleep(delay... |
<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_current_release(self):
"""Get the release ID of the "current" deployment, None if there is no current deployment. This method performs one network operat... |
current = self._runner.run("readlink '{0}'".format(self._current))
if current.failed:
return None
return os.path.basename(current.strip()) |
<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_previous_release(self):
"""Get the release ID of the deployment immediately before the "current" deployment, ``None`` if no previous release could be det... |
releases = self.get_releases()
if not releases:
return None
current = self.get_current_release()
if not current:
return None
try:
current_idx = releases.index(current)
except ValueError:
return None
try:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cleanup(self, keep=5):
"""Remove all but the ``keep`` most recent releases. If any of the candidates for deletion are pointed to by the 'current' symlink, th... |
releases = self.get_releases()
current_version = self.get_current_release()
to_delete = [version for version in releases[keep:] if version != current_version]
for release in to_delete:
self._runner.run("rm -rf '{0}'".format(os.path.join(self._releases, release))) |
<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_directories(self, use_sudo=True):
"""Create the minimal required directories for deploying multiple releases of a project. By default, creation of dire... |
runner = self._runner.sudo if use_sudo else self._runner.run
runner("mkdir -p '{0}'".format(self._releases)) |
<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( self, owner, file_perms=PERMS_FILE_DEFAULT, dir_perms=PERMS_DIR_DEFAULT, use_sudo=True):
"""Set the owner and permissions of the code deploy... |
runner = self._runner.sudo if use_sudo else self._runner.run
if use_sudo:
runner("chown -R '{0}' '{1}'".format(owner, self._base))
for path in (self._base, self._releases):
runner("chmod '{0}' '{1}'".format(dir_perms, path))
runner("chmod -R '{0}' '{1}'".forma... |
<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_pending_after_task(self):
""" Creates pending task results in a dict on self.after_result with task string as key. It will also create a list on self.... |
for task in self.settings.tasks[self.after_tasks_key]:
self.after_tasks.append(task)
self.after_results[task] = Result(task) |
<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_config():
'''try loading config file from a default directory'''
cfg_path = '/usr/local/etc/freelan'
cfg_file = 'freelan.cfg'
if not os.path.isdir(cfg_path):
print("Can not find default freelan config directory.")
return
cfg_file_path = os.path.join(cfg_path,cfg_file)
... |
<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_config(cfg):
'''try writing config file to a default directory'''
cfg_path = '/usr/local/etc/freelan'
cfg_file = 'freelan_TEST.cfg'
cfg_lines = []
if not isinstance(cfg, FreelanCFG):
if not isinstance(cfg, (list, tuple)):
print("Freelan write input can not be processe... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cfgdump(path, config):
"""Create output directory path and output there the config.yaml file.""" |
dump = yaml_dump(config)
if not os.path.exists(path):
os.makedirs(path)
with open(os.path.join(path, 'config.yaml'), 'w') as outf:
outf.write(dump)
print(dump) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def videometadata(ctx, city, date, outpath):
"""Generate metadata for video records. city: The meetup series. \b date: The date. May be: - YYYY-MM-DD or YY-MM-DD... |
db = ctx.obj['db']
today = ctx.obj['now'].date()
event = cliutil.get_event(db, city, date, today)
data = event.as_dict()
cliutil.handle_raw_output(ctx, data)
evdir = "{}-{}".format(event.city.name, event.slug)
config = OrderedDict()
config['speaker'] = ''
config['title'] = ''
... |
<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_data(data, subset, splits):
'''Returns the data for a given protocol
'''
return dict([(k, data[k][splits[subset]]) for k in 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 get(protocol, subset, classes=CLASSES, variables=VARIABLES):
'''Returns the data subset given a particular protocol
Parameters
protocol (string): one of the valid protocols supported by this interface
subset (string): one of 'train' or 'test'
classes (list of string): a list of strings containi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def silent_parse_args(self, command, args):
""" Silently attempt to parse args. If there is a failure then we ignore the effects. Using an in-place namespace obj... |
args_ns = argparse.Namespace()
stderr_save = argparse._sys.stderr
stdout_save = argparse._sys.stdout
argparse._sys.stderr = os.devnull
argparse._sys.stdout = os.devnull
try:
command.argparser.parse_known_args(args, args_ns)
except BaseException:
... |
<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_nargs(self, nargs):
""" Nargs is essentially a multi-type encoding. We have to parse it to understand how many values this action may consume. """ |
self.max_args = self.min_args = 0
if nargs is None:
self.max_args = self.min_args = 1
elif nargs == argparse.OPTIONAL:
self.max_args = 1
elif nargs == argparse.ZERO_OR_MORE:
self.max_args = None
elif nargs in (argparse.ONE_OR_MORE, argparse.RE... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def consume(self, args):
""" Consume the arguments we support. The args are modified inline. The return value is the number of args eaten. """ |
consumable = args[:self.max_args]
self.consumed = len(consumable)
del args[:self.consumed]
return self.consumed |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def about_action(self):
""" Simple string describing the action. """ |
name = self.action.metavar or self.action.dest
type_name = self.action.type.__name__ if self.action.type else ''
if self.action.help or type_name:
extra = ' (%s)' % (self.action.help or 'type: %s' % type_name)
else:
extra = ''
return name + extra |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def file_complete(self, prefix, args):
""" Look in the local filesystem for valid file choices. """ |
path = os.path.expanduser(prefix)
dirname, name = os.path.split(path)
if not dirname:
dirname = '.'
try:
dirs = os.listdir(dirname)
except FileNotFoundError:
return frozenset()
choices = []
session = self.calling_command.sessio... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def exec_command(command, **kwargs):
""" Executes the given command and send the output to the console :param str|list command: :kwargs: * `shell` (``bool`` = Fa... |
shell = kwargs.get('shell', False)
stdin = kwargs.get('stdin', None)
stdout = kwargs.get('stdout', None)
stderr = kwargs.get('stderr', None)
kwargs.update(shell=shell)
kwargs.update(stdin=stdin)
kwargs.update(stdout=stdout)
kwargs.update(stderr=stderr)
if not isinstance(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 observe_command(command, **kwargs):
""" Executes the given command and captures the output without any output to the console :param str|list command: :kwargs... |
shell = kwargs.get('shell', False)
timeout = kwargs.get('timeout', 15)
stdin = kwargs.get('stdin', subprocess.PIPE)
stdout = kwargs.get('stdout', subprocess.PIPE)
stderr = kwargs.get('stderr', subprocess.PIPE)
cwd = kwargs.get('cwd', None)
kwargs.update(shell=shell)
kwargs.update(stdi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calculate_hash(obj):
""" Computes fingerprint for an object, this code is duplicated from representatives.models.HashableModel because we don't have access t... |
hashable_fields = {
'Chamber': ['name', 'country', 'abbreviation'],
'Constituency': ['name'],
'Group': ['name', 'abbreviation', 'kind', 'chamber'],
'Mandate': ['group', 'constituency', 'role', 'begin_date', 'end_date',
'representative']
}
fingerprint = hashlib.... |
<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_or_create(cls, **kwargs):
""" Implements get_or_create logic for models that inherit from representatives.models.HashableModel because we don't have acce... |
try:
obj = cls.objects.get(**kwargs)
created = False
except cls.DoesNotExist:
obj = cls(**kwargs)
created = True
calculate_hash(obj)
obj.save()
return (obj, created) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decorator_with_args(func, return_original=False, target_pos=0):
"""Enable a function to work with a decorator with arguments Args: func (callable):
The inpu... |
if sys.version_info[0] >= 3:
target_name = inspect.getfullargspec(func).args[target_pos]
else:
target_name = inspect.getargspec(func).args[target_pos]
@functools.wraps(func)
def wrapper(*args, **kwargs):
if len(args) > target_pos:
res = 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 elements_equal(first, *others):
""" Check elements for equality """ |
f = first
lf = list(f)
for e in others:
le = list(e)
if (len(lf) != len(le)
or f.tag != e.tag
or f.text != e.text
or f.tail != e.tail
or f.attrib != e.attrib
or (not all(map(elements_equal, lf, le)))
... |
<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_element(text_or_tree_or_element):
""" Get back an ET.Element for several possible input formats """ |
if isinstance(text_or_tree_or_element, ET.Element):
return text_or_tree_or_element
elif isinstance(text_or_tree_or_element, ET.ElementTree):
return text_or_tree_or_element.getroot()
elif isinstance(text_or_tree_or_element, (unicode, bytes)):
return ET.fromstring(text_or_tree_or_elem... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def task_failure_handler(task_id=None, exception=None, traceback=None, args=None, **kwargs):
"""Task failure handler""" |
# TODO: find a better way to acces workdir/archive/image
task_report = {'task_id': task_id,
'exception': exception,
'traceback': traceback,
'archive': args[1]['archive_path'],
'image': args[1]['image']}
notifier.send_task_failure_r... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _update_config(self,directory,filename):
"""Manages FLICKR config files""" |
basefilename=os.path.splitext(filename)[0]
ext=os.path.splitext(filename)[1].lower()
if filename==LOCATION_FILE:
print("%s - Updating geotag information"%(LOCATION_FILE))
return self._update_config_location(directory)
elif filename==TAG_FILE:
print("%... |
<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_meta(self,directory,filename):
"""Opens up filename.title and filename.description, updates on flickr""" |
if not self._connectToFlickr():
print("%s - Couldn't connect to flickr"%(directory))
return False
db = self._loadDB(directory)
# Look up photo id for this photo
pid=db[filename]['photoid']
# =========== LOAD TITLE ========
fullfile=os.path.joi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _createphotoset(self,myset,primary_photoid):
"""Creates a photo set on Flickr""" |
if not self._connectToFlickr():
print("%s - Couldn't connect to flickr"%(directory))
return False
logger.debug('Creating photo set %s with prim photo %s'\
%(myset,primary_photoid))
resp=self.flickr.photosets_create(title=myset,\
p... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _update_config_sets(self,directory,files=None):
""" Loads set information from file and updates on flickr, only reads first line. Format is comma separated e... |
if not self._connectToFlickr():
print("%s - Couldn't connect to flickr"%(directory))
return False
# Load sets from SET_FILE
_sets=self._load_sets(directory)
# Connect to flickr and get dicionary of photosets
psets=self._getphotosets()
db = self... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _getphotosets_forphoto(self,pid):
"""Asks flickr which photosets photo with given pid belongs to, returns list of photoset names""" |
resp=self.flickr.photos_getAllContexts(photo_id=pid)
if resp.attrib['stat']!='ok':
logger.error("%s - flickr: photos_getAllContext failed with status: %s",\
resp.attrib['stat']);
return None
lphotosets=[]
for element in resp.findall('set'):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _getphoto_originalsize(self,pid):
"""Asks flickr for photo original size returns tuple with width,height """ |
logger.debug('%s - Getting original size from flickr'%(pid))
width=None
height=None
resp=self.flickr.photos_getSizes(photo_id=pid)
if resp.attrib['stat']!='ok':
logger.error("%s - flickr: photos_getSizes failed with status: %s",\
resp.attrib['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 _getphoto_information(self,pid):
"""Asks flickr for photo information returns dictionary with attributes {'dateuploaded': '1383410793', 'farm': '3', 'id': '1... |
if not self._connectToFlickr():
print("%s - Couldn't connect to flickr"%(directory))
return False
d={}
logger.debug('%s - Getting photo information from flickr'%(pid))
resp=self.flickr.photos_getInfo(photo_id=pid)
if resp.attrib['stat']!='ok':
... |
<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_config_tags(self,directory,files=None):
""" Loads tags information from file and updates on flickr, only reads first line. Format is comma separated ... |
if not self._connectToFlickr():
print("%s - Couldn't connect to flickr"%(directory))
return False
logger.debug("Updating tags in %s"%(directory))
_tags=self._load_tags(directory)
# --- Load DB of photos, and update them all with new tags
db = self._loa... |
<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_media(self,directory,files=None):
"""Removes specified files from flickr""" |
# Connect if we aren't already
if not self._connectToFlickr():
logger.error("%s - Couldn't connect to flickr")
return False
db=self._loadDB(directory)
# If no files given, use files from DB in dir
if not files:
files=db.keys()
#If on... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _upload_media(self,directory,files=None,resize_request=None):
"""Uploads media file to FLICKR, returns True if uploaded successfully, Will replace if already... |
# Connect if we aren't already
if not self._connectToFlickr():
logger.error("%s - Couldn't connect to flickr")
return False
_tags=self._load_tags(directory)
_megapixels=self._load_megapixels(directory)
# If no files given, use files from DB in 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 create_project(self, project_path):
""" Create Trionyx project in given path :param str path: path to create project in. :raises FileExistsError: """ |
shutil.copytree(self.project_path, project_path)
self.update_file(project_path, 'requirements.txt', {
'trionyx_version': trionyx.__version__
})
self.update_file(project_path, 'config/local_settings.py', {
'secret_key': utils.random_string(32)
}) |
<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_app(self, apps_path, name):
""" Create Trionyx app in given path :param str path: path to create app in. :param str name: name of app :raises FileExis... |
app_path = os.path.join(apps_path, name.lower())
shutil.copytree(self.app_path, app_path)
self.update_file(app_path, '__init__.py', {
'name': name.lower()
})
self.update_file(app_path, 'apps.py', {
'name': name.lower(),
'verbose_name': 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 find_one(self, filter=None, fields=None, skip=0, sort=None):
""" Similar to find. This method will only retrieve one row. If no row matches, returns None """ |
result = self.find(filter=filter, fields=fields, skip=skip, limit=1, sort=sort)
if len(result) > 0:
return result[0]
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 get_existing_keys(self, events):
"""Returns the list of keys from the given event source that are already in the DB""" |
data = [e[self.key] for e in events]
ss = ','.join(['%s' for _ in data])
query = 'SELECT %s FROM %s WHERE %s IN (%s)' % (self.key, self.table, self.key, ss)
cursor = self.conn.conn.cursor()
cursor.execute(query, data)
LOG.info("%s (data: %s)", query, data)
existi... |
<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, events):
"""Constructs and executes a MySQL insert for the given events.""" |
if not len(events):
return
keys = sorted(events[0].keys())
ss = ','.join(['%s' for _ in keys])
query = 'INSERT INTO %s (%s) VALUES ' % (self.table, ','.join(keys))
data = []
for event in events:
query += '(%s),' % ss
data += [event[k] ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.