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 api_headers_tween_factory(handler, registry):
"""This tween provides necessary API headers """ |
def api_headers_tween(request):
response = handler(request)
set_version(request, response)
set_req_guid(request, response)
return response
return api_headers_tween |
<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_url(url):
""" Normalize the url and clean it 'http://www.assemblee-nationale.fr/dyn/15/dossiers/deuxieme_partie' 'https://www.conseil-constitutionnel.f... |
url = url.strip()
# fix urls like 'pjl09-518.htmlhttp://www.assemblee-nationale.fr/13/ta/ta051`8.asp'
if url.find('https://') > 0:
url = 'https://' + url.split('https://')[1]
if url.find('http://') > 0:
url = 'http://' + url.split('http://')[1]
scheme, netloc, path, params, query,... |
<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_national_assembly_url(url_an):
"""Returns the slug and the legislature of an AN url (14, 'devoir_vigilance_entreprises_donneuses_ordre') (15, 'retablis... |
legislature_match = re.search(r"\.fr/(dyn/)?(\d+)/", url_an)
if legislature_match:
legislature = int(legislature_match.group(2))
else:
legislature = None
slug = None
slug_match = re.search(r"/([\w_\-]*)(?:\.asp)?(?:#([\w_\-]*))?$", url_an)
if slug_match:
if legislature ... |
<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(self, given_file):
""" Read given_file to self.contents Will ignoring duplicate lines if self.unique is True Will sort self.contents after reading file ... |
if self.unique is not False and self.unique is not True:
raise AttributeError("Attribute 'unique' is not True or False.")
self.filename = str.strip(given_file)
self.log('Read-only opening {0}'.format(self.filename))
with open(self.filename, 'r') as handle:
for li... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check(self, line):
""" Find first occurrence of 'line' in file. This searches each line as a whole, if you want to see if a substring is in a line, use .grep... |
if not isinstance(line, str):
raise TypeError("Parameter 'line' not a 'string', is {0}".format(type(line)))
if line in self.contents:
return line
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add(self, line):
""" Append 'line' to contents where 'line' is an entire line or a list of lines. If self.unique is False it will add regardless of contents.... |
if self.unique is not False and self.unique is not True:
raise AttributeError("Attribute 'unique' is not True or False.")
self.log('add({0}); unique={1}'.format(line, self.unique))
if line is False:
return False
if isinstance(line, str):
line = line.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 rm(self, line):
""" Remove all occurrences of 'line' from contents where 'line' is an entire line or a list of lines. Return true if the file was changed by ... |
self.log('rm({0})'.format(line))
if line is False:
return False
if isinstance(line, str):
line = line.split('\n')
if not isinstance(line, list):
raise TypeError("Parameter 'line' not a 'string' or 'list', is {0}".format(type(line)))
local_chan... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def replace(self, old, new):
""" Replace all lines of file that match 'old' with 'new' Will replace duplicates if found. :param old: String, List of Strings, a m... |
self.log('replace({0}, {1})'.format(old, new))
if old is False:
return False
if isinstance(old, str):
old = old.split('\n')
if not isinstance(old, list):
raise TypeError("Parameter 'old' not a 'string' or 'list', is {0}".format(type(old)))
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 partition(pred, iterable):
""" split the results of an iterable based on a predicate """ |
trues = []
falses = []
for item in iterable:
if pred(item):
trues.append(item)
else:
falses.append(item)
return trues, falses |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def zip_with_output(skip_args=[]):
"""decorater that zips the input of a function with its output only zips positional arguments. skip_args : list a list of inde... |
def decorator(fn):
def wrapped(*args, **vargs):
g = [arg for i, arg in enumerate(args) if i not in skip_args]
if len(g) == 1:
return(g[0], fn(*args, **vargs))
else:
return (g, fn(*args, **vargs))
return wrapped
return decorator |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def capture_exception(fn):
"""decorator that catches and returns an exception from wrapped function""" |
def wrapped(*args):
try:
return fn(*args)
except Exception as e:
return e
return wrapped |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compose(*funcs):
"""compose a list of functions""" |
return lambda x: reduce(lambda v, f: f(v), reversed(funcs), x) |
<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_over_glob(fn, path, pattern):
"""map a function over a glob pattern, relative to a directory""" |
return [fn(x) for x in glob.glob(os.path.join(path, pattern))] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mkdir_recursive(dirname):
"""makes all the directories along a given path, if they do not exist""" |
parent = os.path.dirname(dirname)
if parent != "":
if not os.path.exists(parent):
mkdir_recursive(parent)
if not os.path.exists(dirname):
os.mkdir(dirname)
elif not os.path.exists(dirname):
os.mkdir(dirname) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def indent_text(*strs, **kwargs):
""" indents text according to an operater string and a global indentation level. returns a tuple of all passed args, indented a... |
# python 2.7 workaround
indent = kwargs["indent"] if "indent" in kwargs else"+0"
autobreak = kwargs.get("autobreak", False)
char_limit = kwargs.get("char_limit", 80)
split_char = kwargs.get("split_char", " ")
strs = list(strs)
if autobreak:
for index, s in enumerate(strs):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pdebug(*args, **kwargs):
"""print formatted output to stdout with indentation control""" |
if should_msg(kwargs.get("groups", ["debug"])):
# initialize colorama only if uninitialized
global colorama_init
if not colorama_init:
colorama_init = True
colorama.init()
args = indent_text(*args, **kwargs)
# write to stdout
sys.stderr.writ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pout(*args, **kwargs):
"""print to stdout, maintaining indent level""" |
if should_msg(kwargs.get("groups", ["normal"])):
args = indent_text(*args, **kwargs)
# write to stdout
sys.stderr.write("".join(args))
sys.stderr.write("\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 urlretrieve(url, dest, write_mode="w"):
"""save a file to disk from a given url""" |
response = urllib2.urlopen(url)
mkdir_recursive(os.path.dirname(dest))
with open(dest, write_mode) as f:
f.write(response.read())
f.close() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_dups(seq):
"""remove duplicates from a sequence, preserving order""" |
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def json_requested():
"""Check if json is the preferred output format for the request.""" |
best = request.accept_mimetypes.best_match(
['application/json', 'text/html'])
return (best == 'application/json' and
request.accept_mimetypes[best] >
request.accept_mimetypes['text/html']) |
<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_readme():
'Get the long description from the README file'
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.rst'), encoding='utf-8') as my_fd:
result = my_fd.read()
return 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 get_nc_attrs(nc):
"""Gets netCDF file metadata attributes. Arguments: nc (netCDF4.Dataset):
an open NetCDF4 Dataset to pull attributes from. Returns: dict: ... |
meta = {
'experiment': nc.experiment_id,
'frequency': nc.frequency,
'institute': nc.institute_id,
'model': nc.model_id,
'modeling_realm': nc.modeling_realm,
'ensemble_member': 'r{}i{}p{}'.format(nc.realization, nc.initialization_method, nc.physics_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 get_var_name(nc):
"""Guesses the variable_name of an open NetCDF file """ |
non_variable_names = [
'lat',
'lat_bnds',
'lon',
'lon_bnds',
'time',
'latitude',
'longitude',
'bnds'
]
_vars = set(nc.variables.keys())
_vars.difference_update(set(non_variable_names))
if len(_vars) == 1:
return _vars.pop()
... |
<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_known_atts(self, **kwargs):
"""Updates instance attributes with supplied keyword arguments. """ |
for k, v in kwargs.items():
if k not in ATTR_KEYS:
# Warn if passed in unknown kwargs
raise SyntaxWarning('Unknown argument: {}'.format(k))
elif not v: # Delete attributes with falsey values
delattr(self, k)
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 savecache(apicache, json_file):
""" Saves apicache dictionary as json_file, returns dictionary as indented str """ |
if apicache is None or apicache is {}:
return ""
apicachestr = json.dumps(apicache, indent=2)
with open(json_file, 'w') as cache_file:
cache_file.write(apicachestr)
return apicachestr |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def loadcache(json_file):
""" Loads json file as dictionary, feeds it to monkeycache and spits result """ |
f = open(json_file, 'r')
data = f.read()
f.close()
try:
apicache = json.loads(data)
except ValueError as e:
print("Error processing json:", json_file, e)
return {}
return apicache |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def monkeycache(apis):
""" Feed this a dictionary of api bananas, it spits out processed cache """ |
if isinstance(type(apis), type(None)) or apis is None:
return {}
verbs = set()
cache = {}
cache['count'] = apis['count']
cache['asyncapis'] = []
apilist = apis['api']
if apilist is None:
print("[monkeycache] Server response issue, no apis found")
for api in apilist:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def execute(self, sql, param=(), times=1):
"""This function is the most use one, with the paramter times it will try x times to execute the sql, default is 1. ""... |
self.log and self.log.debug('%s %s' % ('SQL:', sql))
if param is not ():
self.log and self.log.debug('%s %s' % ('PARAMs:', param))
for i in xrange(times):
try:
ret, res = self._execute(sql, param)
return ret, res
except Excepti... |
<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_metadata(source):
""" Extract the metadata from the module or dict argument. It returns a `metadata` dictionary that provides keywords arguments for the ... |
if isinstance(source, types.ModuleType):
metadata = source.__dict__
else:
metadata = source
setuptools_kwargs = {}
for key in "name version url license".split():
val = metadata.get("__" + key + "__")
if val is not None:
setuptools_kwargs[key] = val
ver... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def profile(length=25):
""" Start the application under the code profiler """ |
from werkzeug.contrib.profiler import ProfilerMiddleware
app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[length])
app.run() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _help():
""" Display both SQLAlchemy and Python help statements """ |
statement = '%s%s' % (shelp, phelp % ', '.join(cntx_.keys()))
print statement.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 run(self):
""" Sets up live server, and then loops over handling http requests. """ |
try:
# Go through the list of possible ports, hoping we can find
# one that is free to use for the WSGI server.
for index, port in enumerate(self.possible_ports):
try:
self.httpd = self._create_server(port)
except socket.er... |
<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_column(table, remove_index):
'''
Removes the specified column from the table.
'''
for row_index in range(len(table)):
old_row = table[row_index]
new_row = []
for column_index in range(len(old_row)):
if column_index !=... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def row_content_length(row):
'''
Returns the length of non-empty content in a given row.
'''
if not row:
return 0
try:
return (index + 1 for index, cell in reversed(list(enumerate(row))) if not is_empty_cell(cell)).next()
except StopIteration:
return len(row) |
<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_block_by_row_length(block, split_row_length):
'''
Splits the block by finding all rows with less consequetive, non-empty rows than the
min_row_length input.
'''
split_blocks = []
current_block = []
for row in block:
if row_content_length(row) <= split_row_length:
... |
<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_need_install():
"""Check if installed package are exactly the same to this one. """ |
md5_root, md5_dst = list(), list()
need_install_flag = False
for root, _, basename_list in os.walk(_ROOT):
if os.path.basename(root) != "__pycache__":
for basename in basename_list:
src = os.path.join(root, basename)
dst = os.path.join(root.replace(_ROOT,... |
<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_permission_to_view(page, user):
""" Check whether the user has permission to view the page. If the user has any of the page's permissions, they have perm... |
if page.permissions.count() == 0:
return True
for perm in page.permissions.all():
perm_label = '%s.%s' % (perm.content_type.app_label, perm.codename)
if user.has_perm(perm_label):
return True
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_directives(self, line):
"""List all directives supported by the bot""" |
for name, cmd in self.adapter.directives.items():
with colorize('blue'):
print('bot %s:' % name)
if cmd.__doc__:
for line in cmd.__doc__.split('\n'):
print(' %s' % line)
else:
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 do_bot(self, line):
"""Call the bot""" |
with colorize('blue'):
if not line:
self.say('what?')
try:
res = self.adapter.receive(message=line)
except UnknownCommand:
self.say("I do not known what the '%s' directive is" % line)
else:
self.say... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def timeout(seconds, error_message=None):
"""Timeout checking just for Linux-like platform, not working in Windows platform.""" |
def decorated(func):
result = ""
def _handle_timeout(signum, frame):
errmsg = error_message or 'Timeout: The action <%s> is timeout!' % func.__name__
global result
result = None
import inspect
stack_frame = inspect.stack()[4]
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def broadcast(self, command, *args, **kwargs):
""" Notifies each user with a specified command. """ |
criterion = kwargs.pop('criterion', self.BROADCAST_FILTER_ALL)
for index, user in items(self.users()):
if criterion(user, command, *args, **kwargs):
self.notify(user, command, *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 get_config(basedir, files):
""" Returns the config object for the selected docker-compose.yml This is an instance of `compose.config.config.Config`. """ |
config_details = config.find(
basedir, files,
environment.Environment.from_env_file(basedir))
return config.load(config_details) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build(config, services):
""" Builds images and tags them appropriately. Where "appropriately" means with the output of: git describe --tags HEAD and 'latest'... |
filtered_services = {name: service for name, service in services.iteritems() if 'build' in service}
_call_output('docker-compose build {}'.format(' '.join(filtered_services.iterkeys())))
version = _get_version()
for service_name, service_dict in filtered_services.iteritems():
# Tag with prop... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def push(config, services):
""" Upload the defined services to their respective repositories. So's we can then tell the remote docker host to then pull and run t... |
version = _get_version()
for service_name, service_dict in services.iteritems():
image = service_dict['image']
things = {'image': image, 'version': version}
_call_output('docker push {image}:latest'.format(**things))
_call_output('docker push {image}:{version}'.format(**things)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_bins(bins, values=None):
"""Compute bin edges for numpy.histogram based on values and a requested bin parameters Unlike `range`, the largest value i... |
if isinstance(bins, int):
bins = (bins,)
if isinstance(bins, float):
bins = (0, bins)
if not len(bins) in (1, 2):
return bins
if values is None or not hasattr(values, '__iter__') or not any(values) or not hasattr(values, '__len__') or len(values) < 1:
values = [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 select(target, path, default=None, slient=True):
"""Select item with path from target. If not find item and slient marked as True, return default value. If n... |
def _(value, slient):
if slient:
return value
else:
raise KeyError("")
default = partial(_, default, slient)
names = path.split(".")
node = target
for name in names:
if isinstance(node, dict):
try:
node = node[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 update(target, path, value):
"""Update item in path of target with given value. """ |
names = path.split(".")
names_length = len(names)
node = target
for index in range(names_length):
name = names[index]
if index == names_length - 1:
last = True
else:
last = False
if isinstance(node, dict):
if last:
node... |
<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_bam_index_stats(fn):
""" Parse the output from Picard's BamIndexStast and return as pandas Dataframe. Parameters filename : str of filename or file han... |
with open(fn) as f:
lines = [x.strip().split() for x in f.readlines()]
no_counts = int(lines[-1][-1])
lines = lines[:-1]
chrom = [x[0] for x in lines]
length = [int(x[2]) for x in lines]
aligned = [int(x[4]) for x in lines]
unaligned = [int(x[6]) for x in lines]
df = pd.DataFram... |
<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_alignment_summary_metrics(fn):
""" Parse the output from Picard's CollectAlignmentSummaryMetrics and return as pandas Dataframe. Parameters filename : ... |
df = pd.read_table(fn, index_col=0, skiprows=range(6) + [10, 11]).T
return df |
<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_mark_duplicate_metrics(fn):
""" Parse the output from Picard's MarkDuplicates and return as pandas Series. Parameters filename : str of filename or fil... |
with open(fn) as f:
lines = [x.strip().split('\t') for x in f.readlines()]
metrics = pd.Series(lines[7], lines[6])
m = pd.to_numeric(metrics[metrics.index[1:]])
metrics[m.index] = m.values
vals = np.array(lines[11:-1])
hist = pd.Series(vals[:, 1], index=[int(float(x)) for x in 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 parse_insert_metrics(fn):
""" Parse the output from Picard's CollectInsertSizeMetrics and return as pandas Series. Parameters filename : str of filename or f... |
with open(fn) as f:
lines = [x.strip().split('\t') for x in f.readlines()]
index = lines[6]
vals = lines[7]
for i in range(len(index) - len(vals)):
vals.append(np.nan)
for i, v in enumerate(vals):
if type(v) == str:
try:
vals[i] = int(v)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def shell_sqlalchemy(session: SqlalchemySession, backend: ShellBackend):
""" This command includes SQLAlchemy DB Session """ |
namespace = {
'session': session
}
namespace.update(backend.get_namespace())
embed(user_ns=namespace, header=backend.header) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def shell_django(session: DjangoSession, backend: ShellBackend):
""" This command includes Django DB Session """ |
namespace = {
'session': session
}
namespace.update(backend.get_namespace())
embed(user_ns=namespace, header=backend.header) |
<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_query(func):
""" Ensure any SQLExpression instances are serialized""" |
@functools.wraps(func)
def wrapper(self, query, *args, **kwargs):
if hasattr(query, 'serialize'):
query = query.serialize()
assert isinstance(query, basestring), 'Expected query to be string'
if self.debug:
print('SQL:', query)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def autocomplete_view(self, request):
""" Searches in the fields of the given related model and returns the result as a simple string to be used by the jQuery Au... |
query = request.GET.get('q', None)
app_label = request.GET.get('app_label', None)
model_name = request.GET.get('model_name', None)
search_fields = request.GET.get('search_fields', None)
object_pk = request.GET.get('object_pk', None)
try:
to_string_function =... |
<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(self, context):
"""We have to overwrite this method because we don't want an implicit context """ |
args = []
kwargs = {}
for arg in self.explicit_arguments:
if arg.name is not None:
kwargs[arg.name] = arg.value
else:
args.append(arg.value)
for arg in self.implicit_arguments:
if arg.name is not 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 liftover_bed( bed, chain, mapped=None, unmapped=None, liftOver_path='liftOver', ):
""" Lift over a bed file using a given chain file. Parameters bed : str or... |
import subprocess
import pybedtools as pbt
if mapped == None:
import tempfile
mapped = tempfile.NamedTemporaryFile()
mname = mapped.name
else:
mname = mapped
if unmapped == None:
import tempfile
unmapped = tempfile.NamedTemporaryFile()
uname =... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deseq2_size_factors(counts, meta, design):
""" Get size factors for counts using DESeq2. Parameters counts : pandas.DataFrame Counts to pass to DESeq2. meta ... |
import rpy2.robjects as r
from rpy2.robjects import pandas2ri
pandas2ri.activate()
r.r('suppressMessages(library(DESeq2))')
r.globalenv['counts'] = counts
r.globalenv['meta'] = meta
r.r('dds = DESeqDataSetFromMatrix(countData=counts, colData=meta, '
'design={})'.format(design))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def goseq_gene_enrichment(genes, sig, plot_fn=None, length_correct=True):
""" Perform goseq enrichment for an Ensembl gene set. Parameters genes : list List of a... |
import os
import readline
import statsmodels.stats.multitest as smm
import rpy2.robjects as r
genes = list(genes)
sig = [bool(x) for x in sig]
r.r('suppressMessages(library(goseq))')
r.globalenv['genes'] = list(genes)
r.globalenv['group'] = list(sig)
r.r('group = as.logical(grou... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def categories_to_colors(cats, colormap=None):
""" Map categorical data to colors. Parameters cats : pandas.Series or list Categorical data as a list or in a Ser... |
if colormap is None:
colormap = tableau20
if type(cats) != pd.Series:
cats = pd.Series(cats)
legend = pd.Series(dict(zip(set(cats), colormap)))
# colors = pd.Series([legend[x] for x in cats.values], index=cats.index)
# I've removed this output:
# colors : pd.Series
# Ser... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def plot_color_legend(legend, horizontal=False, ax=None):
""" Plot a pandas Series with labels and colors. Parameters legend : pandas.Series Pandas Series whose ... |
import matplotlib.pyplot as plt
import numpy as np
t = np.array([np.array([x for x in legend])])
if ax is None:
fig, ax = plt.subplots(1, 1)
if horizontal:
ax.imshow(t, interpolation='none')
ax.set_yticks([])
ax.set_xticks(np.arange(0, legend.shape[0]))
t = a... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_color_legend_rects(colors, labels=None):
""" Make list of rectangles and labels for making legends. Parameters colors : pandas.Series or list Pandas ser... |
from matplotlib.pyplot import Rectangle
if labels:
d = dict(zip(labels, colors))
se = pd.Series(d)
else:
se = colors
rects = []
for i in se.index:
r = Rectangle((0, 0), 0, 0, fc=se[i])
rects.append(r)
out = pd.Series(rects, index=se.index)
return out |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pc_correlation(self, covariates, num_pc=5):
""" Calculate the correlation between the first num_pc prinicipal components and known covariates. The size and i... |
from scipy.stats import spearmanr
if (covariates.shape[0] == self.u.shape[0] and
len(set(covariates.index) & set(self.u.index)) == self.u.shape[0]):
mat = self.u
elif (covariates.shape[0] == self.v.shape[0] and
len(set(covariates.index) & set(self.v.index))... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def can_handle(self, text: str) -> bool: """Check whether this parser can parse the text""" |
try:
changelogs = self.split_changelogs(text)
if not changelogs:
return False
for changelog in changelogs:
_header, _changes = self.split_changelog(changelog)
if not any((_header, _changes)):
return False
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remember(empowered, powerupClass, interface):
""" Adds a powerup to ``empowered`` that will instantiate ``powerupClass`` with the empowered's store when adap... |
className = fullyQualifiedName(powerupClass)
powerup = _StoredByName(store=empowered.store, className=className)
empowered.powerUp(powerup, interface) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def forget(empowered, powerupClass, interface):
""" Forgets powerups previously stored with ``remember``. :param empowered: The Empowered (Store or Item) to be p... |
className = fullyQualifiedName(powerupClass)
withThisName = _StoredByName.className == className
items = empowered.store.query(_StoredByName, withThisName)
if items.count() == 0:
template = "No named powerups for {} (interface: {})".format
raise ValueError(template(powerupClass, interf... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init_event_loop(self):
""" Every cell should have its own event loop for proper containment. The type of event loop is not so important however. """ |
self.loop = asyncio.new_event_loop()
self.loop.set_debug(self.debug)
if hasattr(self.loop, '_set_coroutine_wrapper'):
self.loop._set_coroutine_wrapper(self.debug)
elif self.debug:
warnings.warn("Cannot set debug on loop: %s" % self.loop)
self.loop_policy ... |
<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_event_loop(self):
""" Cleanup an event loop and close it down forever. """ |
for task in asyncio.Task.all_tasks(loop=self.loop):
if self.debug:
warnings.warn('Cancelling task: %s' % task)
task._log_destroy_pending = False
task.cancel()
self.loop.close()
self.loop.set_exception_handler(self.loop_exception_handler_save)
... |
<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_tier(self, coro, **kwargs):
""" Add a coroutine to the cell as a task tier. The source can be a single value or a list of either `Tier` types or coroutin... |
self.assertNotFinalized()
assert asyncio.iscoroutinefunction(coro)
tier = self.Tier(self, coro, **kwargs)
self.tiers.append(tier)
self.tiers_coro_map[coro] = tier
return tier |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def append_tier(self, coro, **kwargs):
""" Implicitly source from the tail tier like a pipe. """ |
source = self.tiers[-1] if self.tiers else None
return self.add_tier(coro, source=source, **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 tier(self, *args, append=True, source=None, **kwargs):
""" Function decorator for a tier coroutine. If the function being decorated is not already a coroutin... |
if len(args) == 1 and not kwargs and callable(args[0]):
raise TypeError('Uncalled decorator syntax is invalid')
def decorator(coro):
if not asyncio.iscoroutinefunction(coro):
coro = asyncio.coroutine(coro)
if append and source is 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 cleaner(self, coro):
""" Function decorator for a cleanup coroutine. """ |
if not asyncio.iscoroutinefunction(coro):
coro = asyncio.coroutine(coro)
self.add_cleaner(coro)
return coro |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def finalize(self):
""" Look at our tiers and setup the final data flow. Once this is run a cell can not be modified again. """ |
self.assertNotFinalized()
starters = []
finishers = []
for x in self.tiers:
if not x.sources:
starters.append(x)
if not x.dests:
finishers.append(x)
self.add_tier(self.output_feed, source=finishers)
self.coord.setup... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def output(self):
""" Produce a classic generator for this cell's final results. """ |
starters = self.finalize()
try:
yield from self._output(starters)
finally:
self.close() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def event_loop(self):
""" Run the event loop once. """ |
if hasattr(self.loop, '._run_once'):
self.loop._thread_id = threading.get_ident()
try:
self.loop._run_once()
finally:
self.loop._thread_id = None
else:
self.loop.call_soon(self.loop.stop)
self.loop.run_forever() |
<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(self):
""" Run all of the cleaners added by the user. """ |
if self.cleaners:
yield from asyncio.wait([x() for x in self.cleaners],
loop=self.loop) |
<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_html_values(self, pydict, recovery_name=True):
"""Convert naive get response data to human readable field name format. using html data format. """ |
new_dict = {"id": pydict["id"]}
for field in self:
if field.key in pydict:
if recovery_name:
new_dict[field.name] = pydict[field.key]
else:
new_dict[field.key] = pydict[field.key]
return new_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 get_raw_values(self, pydict, recovery_name=True):
"""Convert naive get response data to human readable field name format. using raw data format. """ |
new_dict = {"id": pydict["id"]}
for field in self:
raw_key = "%s_raw" % field.key
if raw_key in pydict:
if recovery_name:
new_dict[field.name] = pydict[raw_key]
else:
new_dict[field.key] = pydict[raw_key]
... |
<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_values(self, pydict):
"""Convert knackhq data type instance to json friendly data. """ |
new_dict = dict()
for key, value in pydict.items():
try: # is it's BaseDataType Instance
new_dict[key] = value._data
except AttributeError:
new_dict[key] = value
return new_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 insert(self, data, using_name=True):
"""Insert one or many records. :param data: dict type data or list of dict :param using_name: if you are using field nam... |
if isinstance(data, list): # if iterable, insert one by one
for d in data:
self.insert_one(d, using_name=using_name)
else: # not iterable, execute insert_one
self.insert_one(data, using_name=using_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(self, url, params=dict()):
"""Http get method wrapper, to support search. """ |
try:
res = requests.get(url, headers=self.headers, params=params)
return json.loads(res.text)
except Exception as e:
print(e)
return "error" |
<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(self, url, data):
"""Http post method wrapper, to support insert. """ |
try:
res = requests.post(
url, headers=self.headers, data=json.dumps(data))
return json.loads(res.text)
except Exception as e:
print(e)
return "error" |
<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(self, url):
"""Http delete method wrapper, to support delete. """ |
try:
res = requests.delete(url, headers=self.headers)
return json.loads(res.text)
except Exception as e:
print(e)
return "error" |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def combine_express_output(fnL, column='eff_counts', names=None, tg=None, define_sample_name=None, debug=False):
""" Combine eXpress output files Parameters: fnL... |
if names is not None:
assert len(names) == len(fnL)
if define_sample_name is None:
define_sample_name = lambda x: x
transcriptL = []
for i,fn in enumerate(fnL):
if names is not None:
bn = names[i]
else:
bn = define_sample_name(fn)
tDF... |
<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(path, encoding="utf-8"):
"""Auto-decoding string reader. Usage:: or """ |
with open(path, "rb") as f:
content = f.read()
try:
text = content.decode(encoding)
except:
res = chardet.detect(content)
text = content.decode(res["encoding"])
return text |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write(text, path):
"""Writer text to file with utf-8 encoding. Usage:: or """ |
with open(path, "wb") as f:
f.write(text.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 _delay(self, ms):
"""Implement default delay mechanism. """ |
if ms:
self.Delay(ms)
else:
if self.default_delay:
self.Delay(self.default_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 AltTab(self, n=1, delay=0):
"""Press down Alt, then press n times Tab, then release Alt. """ |
self._delay(delay)
self.add(Command("KeyDown", 'KeyDown "%s", %s' % (BoardKey.Alt, 1)))
for i in range(n):
self.add(Command("KeyPress", 'KeyPress "%s", %s' % (BoardKey.Tab, 1)))
self.add(Command("KeyUp", 'KeyUp "%s", %s' % (BoardKey.Alt, 1))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def Ctrl_C(self, delay=0):
"""Ctrl + C shortcut. """ |
self._delay(delay)
self.add(Command("KeyDown", 'KeyDown "%s", %s' % (BoardKey.Ctrl, 1)))
self.add(Command("KeyPress", 'KeyPress "%s", %s' % (BoardKey.C, 1)))
self.add(Command("KeyUp", 'KeyUp "%s", %s' % (BoardKey.Ctrl, 1))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def Ctrl_V(self, delay=0):
"""Ctrl + V shortcut. """ |
self._delay(delay)
self.add(Command("KeyDown", 'KeyDown "%s", %s' % (BoardKey.Ctrl, 1)))
self.add(Command("KeyPress", 'KeyPress "%s", %s' % (BoardKey.V, 1)))
self.add(Command("KeyUp", 'KeyUp "%s", %s' % (BoardKey.Ctrl, 1))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def Ctrl_W(self, delay=0):
"""Ctrl + W shortcut. """ |
self._delay(delay)
self.add(Command("KeyDown", 'KeyDown "%s", %s' % (BoardKey.Ctrl, 1)))
self.add(Command("KeyPress", 'KeyPress "%s", %s' % (BoardKey.W, 1)))
self.add(Command("KeyUp", 'KeyUp "%s", %s' % (BoardKey.Ctrl, 1))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def randomize(length=6, choices=None):
"""Returns a random string of the given length.""" |
if type(choices) == str:
choices = list(choices)
choices = choices or ascii_lowercase
return "".join(choice(choices) for _ in range(length)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calc_scores_for_node(G, node, depth_limit=22, number_of_recommendations=None, impact_mode=10):
"""Calculate the score of multiple records.""" |
n, w, dep, _ = dfs_edges(G, node, depth_limit, "Record")
count_total_ways = len(n)
# print "Number of paths {}".format(len(n))
if impact_mode == 0:
impact_div = 12
elif impact_mode == 1:
impact_div = 1000
elif impact_mode == 2:
impact_div = 100
elif impact_mode == 10... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dfs_edges(G, start, depth_limit=1, get_only=True, get_path=False):
"""Deepest first search.""" |
depth_limit = depth_limit - 1
# creates unsigned int array (2 Byte)
output_nodes = array('L')
output_depth = array('I')
# creates float array (4 Byte)
output_weights = array('f')
apath = []
if G.node.get(start) is None:
# raise KeyError('Start node not found')
print('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 calc_weight_of_multiple_paths(path_scores, impact_div=12):
"""Caluculate the weight of multipe paths.""" |
number_of_paths = len(path_scores)
if number_of_paths > 1:
score_total = 0.0
highest_score = 0.0
for score in path_scores.Scores:
score_total += score
if highest_score < score:
highest_score = score
score_mean = score_total / number_of_pa... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def recommend_for_record(self, record_id, depth=4, num_reco=10):
"""Calculate recommendations for record.""" |
data = calc_scores_for_node(self._graph, record_id, depth, num_reco)
return data.Node.tolist(), data.Score.tolist() |
<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_profile(self, profile_name):
"""Load user profiles from file.""" |
data = self.storage.get_user_profiles(profile_name)
for x in data.get_user_views():
self._graph.add_edge(int(x[0]), int(x[1]), {'weight': float(x[2])})
self.all_records[int(x[1])] += 1
return self._graph |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def del_big_nodes(self, grater_than=215):
"""Delete big nodes with many connections from the graph.""" |
G = self._graph
it = G.nodes_iter()
node_paths = []
node_names = []
del_nodes = []
summe = 1
count = 1
for node in it:
l = len(G[node])
if l > grater_than:
del_nodes.append(node)
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 punify_filename(filename):
""" small hackisch workaround for unicode problems with the picflash api """ |
path, extension = splitext(filename)
return path.encode('punycode').decode('utf8') + extension |
<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(apikey, picture, resize=None, rotation='00', noexif=False, callback=None):
""" prepares post for regular upload :param str apikey: Apikey needed for A... |
if isinstance(picture, str):
with open(picture, 'rb') as file_obj:
picture_name = picture
data = file_obj.read()
elif isinstance(picture, (tuple, list)):
picture_name = picture[0]
data = picture[1]
else:
raise TypeError("The second argument must be s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.