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 process(specs): """ Executes the passed in list of specs """
pout, pin = chain_specs(specs) LOG.info("Processing") sw = StopWatch().start() r = pout.process(pin) if r: print(r) LOG.info("Finished in %s", sw.read())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def smartquotes(text): """ Runs text through pandoc for smartquote correction. """
command = shlex.split('pandoc --smart -t plain') com = Popen(command, shell=False, stdin=PIPE, stdout=PIPE, stderr=PIPE) out, err = com.communicate(text.encode('utf-8')) com_out = out.decode('utf-8') text = com_out.replace(u'\n', u' ').strip() return text
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shell(cmd, **kwargs): """Execute cmd, check exit code, return stdout"""
logger.debug("$ %s", cmd) return subprocess.check_output(cmd, shell=True, **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 main(argv=None): """ Script execution. The project repo will be cloned to a temporary directory, and the desired branch, tag, or commit will be checked out. Then, the application will be installed into a self-contained virtualenv environment. """
@contextmanager def tmpdir(): """ Create a self-deleting temporary directory. """ path = mkdtemp() try: yield path finally: rmtree(path) return def test(): """ Execute the test suite. """ install = "{:s} install -r requirements-test.txt" check_call(install.format(pip).split()) pytest = join(path, "bin", "py.test") test = "{:s} test/".format(pytest) check_call(test.split()) uninstall = "{:s} uninstall -y -r requirements-test.txt" check_call(uninstall.format(pip).split()) return args = _cmdline(argv) path = join(abspath(args.root), args.name) with tmpdir() as tmp: clone = "git clone {:s} {:s}".format(args.repo, tmp) check_call(clone.split()) chdir(tmp) checkout = "git checkout {:s}".format(args.checkout) check_call(checkout.split()) virtualenv = "virtualenv {:s}".format(path) check_call(virtualenv.split()) pip = join(path, "bin", "pip") install = "{:s} install -U -r requirements.txt .".format(pip) check_call(install.split()) if args.test: test() return 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 _create_user(self, email, password, is_superuser, **extra_fields): """Create new user"""
now = timezone.now() if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model( email=email, password=password, is_active=True, is_superuser=is_superuser, last_login=now, date_joined=now, **extra_fields) user.set_password(password) user.save(using=self._db) return user
<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_full_name(self): """Get full username if no name is set email is given"""
if self.first_name and self.last_name: return "{} {}".format(self.first_name, self.last_name) return self.email
<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_attribute(self, code, value): """Set attribute for user"""
attr, _ = self.get_or_create(code=code) attr.value = value attr.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 get_attribute(self, code, default=None): """Get attribute for user"""
try: return self.get(code=code).value except models.ObjectDoesNotExist: return default
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def next(self): """ fetch the chart identified by this chart's next_id attribute if the next_id is either null or not present for this chart return None returns the new chart instance on sucess"""
try: if self.next_id: return Chart(self.next_id) else: log.debug('attempted to get next chart, but none was found') return except AttributeError: #chart does not implement next pointer log.debug('attempted to get next chart from a chart without a next attribute') 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 previous(self): """ fetch the chart identified by this chart's previous_id attribute if the previous_id is either null or not present for this chart return None returns the new chart instance on sucess"""
try: if self.previous_id: return Chart(self.previous_id) else: log.debug('attempted to get previous chart, but none was found') return except AttributeError: #chart does not implement next pointer log.debug('attempted to get previous chart from a chart without a previous attribute') 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 now(self): """ fetch the chart identified by this chart's now_id attribute if the now_id is either null or not present for this chart return None returns the new chart instance on sucess"""
try: if self.now_id: return Chart(self.now_id) else: log.debug('attempted to get current chart, but none was found') return except AttributeError: #chart does not implement next pointer log.debug('attempted to get current ("now") chart from a chart without a now attribute') 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 initial(key, **kwarg): """Create an empty dicttree. The root node has a special attribute "_rootname". Because root node is the only dictionary doesn't have key. So we assign the key as a special attribute. Usage:: {'_meta': {'_rootname': 'US'}} """
d = dict() DictTree.setattr(d, _rootname = key, **kwarg) return 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 setattr(d, **kwarg): """Set an attribute. set attributes is actually add a special key, value pair in this dict under key = "_meta". Usage:: {'_meta': {'population': 27800000, '_rootname': 'US'}} """
if _meta not in d: d[_meta] = dict() for k, v in kwarg.items(): d[_meta][k] = 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 add_children(d, key, **kwarg): """Add a children with key and attributes. If children already EXISTS, OVERWRITE it. Usage:: {'_meta': {'population': 27800000, '_rootname': 'US'}, 'MD': {'_meta': {'name': 'maryland', 'population': 200000}}, 'VA': {'_meta': {'name': 'virginia', 'population': 100000}}} name="arlington county", population=5000) name="vienna county", population=5000) name="montgomery country", population=5800) name="fredrick country", population=1400) name="RiverHouse 1400", population=437) name="Crystal plaza South", population=681) name="loft hotel", population=216) {'MD': {'_meta': {'name': 'maryland', 'population': 200000}, 'bethesta': {'_meta': {'name': 'montgomery country', 'population': 5800}}, 'germentown': {'_meta': {'name': 'fredrick country', 'population': 1400}}}, 'VA': {'_meta': {'name': 'virginia', 'population': 100000}, 'arlington': {'_meta': {'name': 'arlington county', 'population': 5000}, 'crystal plaza': {'_meta': {'name': 'Crystal plaza South', 'population': 681}}, 'loft': {'_meta': {'name': 'loft hotel', 'population': 216}}, 'riverhouse': {'_meta': {'name': 'RiverHouse 1400', 'population': 437}}}, 'vienna': {'_meta': {'name': 'vienna county', 'population': 1500}}}, '_meta': {'_rootname': 'US', 'population': 27800000.0}} """
if kwarg: d[key] = {_meta: kwarg} else: d[key] = 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 del_depth(d, depth): """Delete all the nodes on specific depth in this dict """
for node in DictTree.v_depth(d, depth-1): for key in [key for key in DictTree.k(node)]: del node[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 prettyprint(d): """Print dicttree in Json-like format. keys are sorted """
print(json.dumps(d, sort_keys=True, indent=4, separators=("," , ": ")))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stats_on_depth(d, depth): """Display the node stats info on specific depth in this dict """
root_nodes, leaf_nodes = 0, 0 for _, node in DictTree.kv_depth(d, depth): if DictTree.length(node) == 0: leaf_nodes += 1 else: root_nodes += 1 total = root_nodes + leaf_nodes print("On depth %s, having %s root nodes, %s leaf nodes. " "%s nodes in total." % (depth, root_nodes, leaf_nodes, total))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def db_for_read(self, model, **hints): """ If the app has its own database, use it for reads """
if model._meta.app_label in self._apps: return getattr(model, '_db_alias', model._meta.app_label) 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 db_for_write(self, model, **hints): """ If the app has its own database, use it for writes """
if model._meta.app_label in self._apps: return getattr(model, '_db_alias', model._meta.app_label) 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 allow_migrate(self, db, model): """ Make sure self._apps go to their own db """
if model._meta.app_label in self._apps: return getattr(model, '_db_alias', model._meta.app_label) == db 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 check(path_dir, requirements_name='requirements.txt'): '''Look for unused packages listed on project requirements''' requirements = _load_requirements(requirements_name, path_dir) imported_modules = _iter_modules(path_dir) installed_packages = _list_installed_packages() imported_modules.update(_excluded_imports()) diff = {lib for lib in installed_packages if lib not in imported_modules} with_dependencies, _ = _list_dependencies(diff) unused_dependencies = sorted([d for d in diff if d in requirements]) for unused_dependency in unused_dependencies: if with_dependencies.get(unused_dependency): print(' - {}'.format(unused_dependency)) for dependency in with_dependencies.get(unused_dependency): print('\t - {}'.format(dependency)) else: print(' - {}'.format(unused_dependency))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pre(cond): """ Add a precondition check to the annotated method. The condition is passed the arguments from the annotated method. It does not need to accept all of the methods parameters. The condition is inspected to figure out which parameters to pass. """
cond_args, cond_varargs, cond_varkw, cond_defaults = inspect.getargspec(cond) source = inspect.getsource(cond).strip() def inner(f): if enabled: # deal with the real function, not a wrapper f = getattr(f, 'wrapped_fn', f) # need to check if 'self' is the first arg, # since @pre doesn't want the self param member_function = is_member_function(f) # need metadata for checking defaults method_args, method_defaults = inspect.getargspec(f)[0::3] def check_condition(args, kwargs): cond_kwargs = {} if method_defaults is not None and len(method_defaults) > 0 \ and len(method_args) - len(method_defaults) <= len(args) < len(method_args): args += method_defaults[len(args) - len(method_args):] # collection the args for name, value in zip(cond_args, args[member_function:]): cond_kwargs[name] = value # collect the remaining kwargs for name in cond_args: if name not in cond_kwargs: cond_kwargs[name] = kwargs.get(name) # test the precondition if not cond(**cond_kwargs): # otherwise raise the exception raise AssertionError('Precondition failure, %s' % source) # append to the rest of the preconditions attached to this method if not hasattr(f, 'preconditions'): f.preconditions = [] f.preconditions.append(check_condition) return check(f) else: return f return inner
<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(cond): """ Add a postcondition check to the annotated method. The condition is passed the return value of the annotated method. """
source = inspect.getsource(cond).strip() def inner(f): if enabled: # deal with the real function, not a wrapper f = getattr(f, 'wrapped_fn', f) def check_condition(result): if not cond(result): raise AssertionError('Postcondition failure, %s' % source) # append to the rest of the postconditions attached to this method if not hasattr(f, 'postconditions'): f.postconditions = [] f.postconditions.append(check_condition) return check(f) else: return f return inner
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def takes(*type_list): """ Decorates a function with type checks. Examples @takes(int): take an int as the first param @takes(int, str): take and int as first, string as 2nd @takes(int, (int, None)): take an int as first, and an int or None as second """
def inner(f): if enabled: # deal with the real function, not a wrapper f = getattr(f, 'wrapped_fn', f) # need to check if 'self' is the first arg, # since @pre doesn't want the self param member_function = is_member_function(f) # need metadata for defaults check method_args, method_defaults = inspect.getargspec(f)[0::3] if member_function: method_args = method_args[member_function:] def check_condition(args, kwargs): if method_defaults is not None and len(method_defaults) > 0 \ and len(method_args) - len(method_defaults) <= len(args) < len(method_args): args += method_defaults[len(args) - len(method_args):] for i, (arg, t) in enumerate(zip(args[member_function:], type_list)): method_arg = method_args[i] if method_arg not in kwargs and not check_type(t, arg): raise AssertionError('Precondition failure, wrong type for argument') for kwarg in kwargs: arg_position = method_args.index(kwarg) if arg_position < len(type_list): t = type_list[arg_position] if not check_type(t, kwargs.get(kwarg)): raise AssertionError('Precondition failure, wrong type for argument %s' % kwarg) # append to the rest of the postconditions attached to this method if not hasattr(f, 'preconditions'): f.preconditions = [] f.preconditions.append(check_condition) return check(f) else: return f return inner
<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_conditions(f, args, kwargs): """ This is what runs all of the conditions attached to a method, along with the conditions on the superclasses. """
member_function = is_member_function(f) # check the functions direct pre conditions check_preconditions(f, args, kwargs) # for member functions check the pre conditions up the chain base_classes = [] if member_function: base_classes = inspect.getmro(type(args[0]))[1:-1] for clz in base_classes: super_fn = getattr(clz, f.func_name, None) check_preconditions(super_fn, args, kwargs) # run the real function return_value = f(*args, **kwargs) # check the functions direct post conditions check_postconditions(f, return_value) # for member functions check the post conditions up the chain if member_function: for clz in base_classes: super_fn = getattr(clz, f.func_name, None) check_postconditions(super_fn, return_value) return return_value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_preconditions(f, args, kwargs): """ Runs all of the preconditions. """
f = getattr(f, 'wrapped_fn', f) if f and hasattr(f, 'preconditions'): for cond in f.preconditions: cond(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 check_postconditions(f, return_value): """ Runs all of the postconditions. """
f = getattr(f, 'wrapped_fn', f) if f and hasattr(f, 'postconditions'): for cond in f.postconditions: cond(return_value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_member_function(f): """ Checks if the first argument to the method is 'self'. """
f_args, f_varargs, f_varkw, f_defaults = inspect.getargspec(f) return 1 if 'self' in f_args else 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 list_of(cls): """ Returns a function that checks that each element in a list is of a specific type. """
return lambda l: isinstance(l, list) and all(isinstance(x, cls) for x in l)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_of(cls): """ Returns a function that checks that each element in a set is of a specific type. """
return lambda l: isinstance(l, set) and all(isinstance(x, cls) for x in l)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def swallow_stdout(stream=None): """Divert stdout into the given stream """
saved = sys.stdout if stream is None: stream = StringIO() sys.stdout = stream try: yield finally: sys.stdout = saved
<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_sj_out_tab(filename): """Read an SJ.out.tab file as produced by the RNA-STAR aligner into a pandas Dataframe. Parameters filename : str of filename or file handle Filename of the SJ.out.tab file you want to read in Returns ------- sj : pandas.DataFrame Dataframe of splice junctions """
def int_to_intron_motif(n): if n == 0: return 'non-canonical' if n == 1: return 'GT/AG' if n == 2: return 'CT/AC' if n == 3: return 'GC/AG' if n == 4: return 'CT/GC' if n == 5: return 'AT/AC' if n == 6: return 'GT/AT' sj = pd.read_table(filename, header=None, names=COLUMN_NAMES, low_memory=False) sj.intron_motif = sj.intron_motif.map(int_to_intron_motif) sj.annotated = sj.annotated.map(bool) sj.strand.astype('object') sj.strand = sj.strand.apply(lambda x: ['unk','+','-'][x]) # See https://groups.google.com/d/msg/rna-star/B0Y4oH8ZSOY/NO4OJbbUU4cJ for # definition of strand in SJout files. sj = sj.sort_values(by=['chrom', 'start', 'end']) return sj
<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_sj_out_dict(fns, jxns=None, define_sample_name=None): """Read multiple sj_outs, return dict with keys as sample names and values as sj_out dataframes. Parameters fns : list of strs of filenames or file handles List of filename of the SJ.out.tab files to read in jxns : set If provided, only keep junctions in this set. define_sample_name : function that takes string as input Function mapping filename to sample name. For instance, you may have the sample name in the path and use a regex to extract it. The sample names will be used as the column names. If this is not provided, the columns will be named as the input files. Returns ------- sj_outD : dict Dict whose keys are sample names and values are sj_out dataframes """
if define_sample_name == None: define_sample_name = lambda x: x else: assert len(set([define_sample_name(x) for x in fns])) == len(fns) sj_outD = dict() for fn in fns: sample = define_sample_name(fn) df = read_sj_out_tab(fn) # Remove any junctions that don't have any uniquely mapped junction # reads. Even if a junction passes the cutoff in other samples, we are # only concerned with unique counts. df = df[df.unique_junction_reads > 0] index = (df.chrom + ':' + df.start.astype(str) + '-' + df.end.astype(str)) assert len(index) == len(set(index)) df.index = index # If jxns is provided, only keep those. if jxns: df = df.ix[set(df.index) & jxns] sj_outD[sample] = df return sj_outD
<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_sj_out_panel(sj_outD, total_jxn_cov_cutoff=20): """Filter junctions from many sj_out files and make panel. Parameters sj_outD : dict Dict whose keys are sample names and values are sj_out dataframes total_jxn_cov_cutoff : int If the unique read coverage of a junction summed over all samples is not greater than or equal to this value, the junction will not be included in the final output. Returns ------- sj_outP : pandas.Panel Panel where each dataframe corresponds to an sj_out file filtered to remove low coverage junctions. Each dataframe has COUNT_COLS = ('unique_junction_reads', 'multimap_junction_reads', 'max_overhang') annotDF : pandas.DataFrame Dataframe with values ANNOTATION_COLS = ('chrom', 'start', 'end', 'intron_motif', 'annotated') that are otherwise duplicated in the panel. """
# num_jxns = dict() # # set of all junctions # jxnS = reduce(lambda x,y: set(x) | set(y), # [ sj_outD[k].index for k in sj_outD.keys() ]) # jxn_keepS = set() # jxn_setsD = dict() # for k in sj_outD.keys(): # jxn_setsD[k] = frozenset(sj_outD[k].index) # for j in jxnS: # if sum([ sj_outD[k].ix[j,'unique_junction_reads'] for k in sj_outD.keys() # if j in jxn_setsD[k] ]) >= total_jxn_cov_cutoff: # jxn_keepS.add(j) # for k in sj_outD.keys(): # sj_outD[k] = sj_outD[k].ix[jxn_keepS] sj_outP = pd.Panel(sj_outD) for col in ['unique_junction_reads', 'multimap_junction_reads', 'max_overhang']: sj_outP.ix[:,:,col] = sj_outP.ix[:,:,col].fillna(0) # Some dataframes will be missing information like intron_motif etc. for # junctions that were not observed in that sample. The info is somewhere in # the panel though so we can get it. annotDF = reduce(pd.DataFrame.combine_first, [ sj_outP.ix[item,:,ANNOTATION_COLS].dropna() for item in sj_outP.items ]) annotDF['start'] = annotDF['start'].astype(int) annotDF['end'] = annotDF['end'].astype(int) annotDF['annotated'] = annotDF['annotated'].astype(bool) # Sort annotation and panel annotDF = annotDF.sort_values(by=['chrom', 'start', 'end']) sj_outP = sj_outP.ix[:, annotDF.index, :] sj_outP = sj_outP.ix[:,:,COUNT_COLS].astype(int) return sj_outP, annotDF
<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_external_annotation(fn): """Read file with junctions from some database. This does not have to be the same splice junction database used with STAR. Parameters fn : filename str File with splice junctions from annotation. The file should have a header and contain the following columns: 'gene', 'chrom', 'start', 'end', 'strand', 'chrom:start', 'chrom:end', 'donor', 'acceptor', 'intron'. Returns ------- extDF : pandas.DataFrame DataFrame indexed by splice junction stats : list of strings Human readable statistics about the external database. """
assert os.path.exists(fn) extDF = pd.read_table(fn, index_col=0, header=0) total_num = extDF.shape[0] # In rare cases, a splice junction might be used by more than one gene. For # my purposes, these cases are confounding, so I will remove all such splice # junctions. intron_count = extDF.intron.value_counts() extDF['intron_count'] = extDF.intron.apply(lambda x: intron_count.ix[x]) extDF = extDF[extDF.intron_count == 1] extDF = extDF.drop('intron_count', axis=1) stats = [] stats.append('External database stats') stats.append('Read external annotation\t{}'.format(fn)) stats.append('Total number of junctions\t{:,}'.format(total_num)) stats.append(('Number of junctions used in only one ' 'gene\t{:,}').format(extDF.shape[0])) return extDF, stats
<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_sj_out( fns, external_db, total_jxn_cov_cutoff=20, define_sample_name=None, verbose=False, ): """Combine SJ.out.tab files from STAR by filtering based on coverage and comparing to an external annotation to discover novel junctions. Parameters fns : list of strings Filenames of SJ.out.tab files to combine. external_db : str Filename of splice junction information from external database. The file should have a header and contained the following columns 'gene', 'chrom', 'start', 'end', 'strand', 'chrom:start', 'chrom:end', 'donor', 'acceptor', 'intron'. total_jxn_cov_cutoff : int Discard junctions with less than this many reads summed over all samples. define_sample_name : function A function mapping the SJ.out.tab filenames to sample names. Returns ------- countDF : pandas.DataFrame Number of unique junction spanning reads for each junction that passed filtering criteria. annotDF : pandas.DataFrame Annotation information for junctions that passed filtering criteria. stats : list of strings Human readable statistics. """
if verbose: import sys # I'll start by figuring out which junctions we will keep. counts = _total_jxn_counts(fns) jxns = set(counts[counts >= total_jxn_cov_cutoff].index) if verbose: sys.stderr.write('Counting done\n') stats = [] sj_outD = _make_sj_out_dict(fns, jxns=jxns, define_sample_name=define_sample_name) stats.append('Number of junctions in SJ.out file per sample') for k in sj_outD.keys(): stats.append('{0}\t{1:,}'.format(k, sj_outD[k].shape[0])) stats.append('') if verbose: sys.stderr.write('Dict done\n') sj_outP, annotDF = _make_sj_out_panel(sj_outD, total_jxn_cov_cutoff) stats.append('SJ.out panel size\t{0}'.format(sj_outP.shape)) stats.append('') if verbose: sys.stderr.write('Panel done\n') extDF, ext_stats = read_external_annotation(external_db) stats += ext_stats stats.append('') if verbose: sys.stderr.write('DB read done\n') countsDF, annotDF, filter_stats = _filter_jxns_donor_acceptor(sj_outP, annotDF, extDF) if verbose: sys.stderr.write('Filter done\n') annotDF = _find_novel_donor_acceptor_dist(annotDF, extDF) if verbose: sys.stderr.write('Dist done\n') stats += filter_stats return countsDF, annotDF, stats
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _total_jxn_counts(fns): """Count the total unique coverage junction for junctions in a set of SJ.out.tab files."""
df = pd.read_table(fns[0], header=None, names=COLUMN_NAMES) df.index = (df.chrom + ':' + df.start.astype(int).astype(str) + '-' + df.end.astype(int).astype(str)) counts = df.unique_junction_reads for fn in fns[1:]: df = pd.read_table(fn, header=None, names=COLUMN_NAMES) df.index = (df.chrom + ':' + df.start.astype(int).astype(str) + '-' + df.end.astype(int).astype(str)) counts = counts.add(df.unique_junction_reads, fill_value=0) return counts
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _make_splice_targets_dict(df, feature, strand): """Make dict mapping each donor to the location of all acceptors it splices to or each acceptor to all donors it splices from. Parameters df : pandas.DataFrame Dataframe with splice junction information from external database containing columns 'gene', 'chrom', 'start', 'end', 'strand', 'chrom:start', 'chrom:end', 'donor', 'acceptor', 'intron'. feature : string Either 'donor' or 'acceptor'. strand : string Either '+' or '-'. Returns ------- d : dict If feature='donor', dict whose keys are all distinct donors in df and whose values are the distinct locations (integers) of the acceptors that donor splices to in a numpy array. If feature='acceptor', dict whose keys are all distinct acceptors in df and whose values are the distinct locations (integers) of the donors that acceptor splices from in a numpy array. """
g = df[df.strand == strand].groupby(feature) d = dict() if strand == '+': if feature == 'donor': target = 'end' if feature == 'acceptor': target = 'start' if strand == '-': if feature == 'donor': target = 'start' if feature == 'acceptor': target = 'end' for k in g.groups.keys(): d[k] = np.array(list(set(df.ix[g.groups[k], target]))) d[k].sort() return 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 _read_log(fn, define_sample_name=None): """Read STAR Log.final.out file. Parameters fn : string Path to Log.final.out file. define_sample_name : function that takes string as input Function mapping filename to sample name. For instance, you may have the sample name in the path and use a regex to extract it. The sample name will be used as the column name. If not provided, the column name will be the filename. Returns ------- df : pandas.DataFrame DataFrame with info from log file. """
if define_sample_name == None: define_sample_name = lambda x: x df = pd.read_table(fn, '|', header=None).dropna() df.index = df.ix[:,0].apply(lambda x: x.strip()) df = pd.DataFrame(df.ix[:,1].apply(lambda x: x.strip())) if define_sample_name: df.columns = [define_sample_name(fn)] else: df.columns = [fn] 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 make_logs_df(fns, define_sample_name=None): """Make pandas DataFrame from multiple STAR Log.final.out files. Parameters fns : string List of paths to Log.final.out files. define_sample_name : function that takes string as input Function mapping filename to sample name. For instance, you may have the sample name in the path and use a regex to extract it. The sample names will be used as the column names. If this is not provided, the columns will be named as the input files. Returns ------- df : pandas.DataFrame DataFrame with info from log file. """
dfs = [] for fn in fns: dfs.append(_read_log(fn, define_sample_name=define_sample_name)) df = pd.concat(dfs,axis=1) df = df.T for label in [ 'Mapping speed, Million of reads per hour', 'Number of input reads', 'Average input read length', 'Uniquely mapped reads number', 'Average mapped length', 'Number of splices: Total', 'Number of splices: GT/AG', 'Number of splices: GC/AG', 'Number of splices: AT/AC', 'Number of splices: Non-canonical', 'Number of reads mapped to multiple loci', 'Number of reads mapped to too many loci']: df[label] = df[label].astype(float) for label in [ 'Uniquely mapped reads %', 'Mismatch rate per base, %', 'Deletion rate per base', 'Insertion rate per base', '% of reads mapped to multiple loci', '% of reads mapped to too many loci', '% of reads unmapped: too many mismatches', '% of reads unmapped: too short', '% of reads unmapped: other']: df[label] = df[label].apply(lambda x: x.strip('%')).astype(float) 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 uptime(): """Uptime of the host machine"""
from datetime import timedelta with open('/proc/uptime', 'r') as f: uptime_seconds = float(f.readline().split()[0]) uptime_string = str(timedelta(seconds=uptime_seconds)) bob.says(uptime_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 value_to_sql_str(v): """ transform a python variable to the appropriate representation in SQL """
if v is None: return 'null' if type(v) in (types.IntType, types.FloatType, types.LongType): return str(v) if type(v) in (types.StringType, types.UnicodeType): return "'%s'" %(v.replace(u"'", u"\\'")) if isinstance(v, datetime): return "'%s'" %(v.strftime("%Y-%m-%d %H:%M:%S")) if isinstance(v, date): return "'%s'" %(v.strftime("%Y-%m-%d")) return str(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 find_component_tarball(bucket, comp_name, comp_config): """ Returns True if the component tarball is found in the bucket. Otherwise, returns False. """
values = { 'name': comp_name, 'version': comp_config['version'], 'platform': comp_config['platform'], } template = comp_config.get('archive_template') if template: key_name = template % values else: key_name = '%(name)s/%(name)s-%(version)s.tar.gz' % values if not bucket.get_key(key_name): log.error('%s not found' % key_name) return False return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _prepare_servers(self): """ Prepare the variables that are exposed to the servers. Most attributes in the server config are used directly. However, due to variations in how cloud providers treat regions and availability zones, this method allows either the ``availability_zone`` or the ``region_name`` to be used as the target availability zone for a server. If both are specified, then ``availability_zone`` is used. If ``availability_zone`` is not specified in the server config, then the ``region_name`` value is used as the target availability zone. """
stack = { A.NAME: self[A.NAME], A.VERSION: self[A.VERSION], } for server in self.get(R.SERVERS, []): # default cloud values if A.PROVIDER in server: if A.server.LAUNCH_TIMEOUT not in server: server[A.server.LAUNCH_TIMEOUT] = DEFAULT_LAUNCH_TIMEOUT_S if A.server.POST_DELAY not in server: server[A.server.POST_DELAY] = DEFAULT_LAUNCH_TIMEOUT_S if A.server.AZ not in server: server[A.server.AZ] = server[A.server.REGION] # distribute the config scope attributes svars = { A.STACK: stack, A.SERVER_CLASS: server[A.NAME], } for scope in server.get(A.server.SCOPES, []): # allow scopes to be defined inline if isinstance(scope, collections.Mapping): svars.update(scope) else: svars[scope] = self[scope] # make all of the launch-time attributes (e.g. disk_image_id, # launch_timeout_s, ssh_key_name, etc...) available as facts in # case you need them in a playbook. sattrs = server.copy() sattrs.pop(A.server.SCOPES, None) svars[A.server.BANG_ATTRS] = sattrs server[A.server.VARS] = svars
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _prepare_load_balancers(self): """ Prepare load balancer variables """
stack = { A.NAME: self[A.NAME], A.VERSION: self[A.VERSION], } for load_balancer in self.get(R.LOAD_BALANCERS, []): svars = {A.STACK: stack} load_balancer[A.loadbalancer.VARS] = svars
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepare(self): """ Reorganizes the data such that the deployment logic can find it all where it expects to be. The raw configuration file is intended to be as human-friendly as possible partly through the following mechanisms: - In order to minimize repetition, any attributes that are common to all server configurations can be specified in the ``server_common_attributes`` stanza even though the stanza itself does not map directly to a deployable resource. - For reference locality, each security group stanza contains its list of rules even though rules are actually created in a separate stage from the groups themselves. In order to make the :class:`Config` object more useful to the program logic, this method performs the following transformations: - Distributes the ``server_common_attributes`` among all the members of the ``servers`` stanza. - Extracts security group rules to a top-level key, and interpolates all source and target values. """
# TODO: take server_common_attributes and disperse it among the various # server stanzas # First stage - turn all the dicts (SERVER, SECGROUP, DATABASE, LOADBAL) # into lists now they're merged properly for stanza_key, name_key in ( (R.SERVERS, A.server.NAME), (R.SERVER_SECURITY_GROUPS, A.secgroup.NAME), (R.LOAD_BALANCERS, A.loadbalancer.NAME), (R.DATABASES, A.database.NAME), (R.BUCKETS, A.NAME), (R.QUEUES, A.NAME)): self[stanza_key] = self._convert_to_list(stanza_key, name_key) self._prepare_ssh_keys() self._prepare_secgroups() self._prepare_tags() self._prepare_dbs() self._prepare_servers() self._prepare_load_balancers() self._prepare_ansible()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def autoinc(self): """ Conditionally updates the stack version in the file associated with this config. This handles both official releases (i.e. QA configs), and release candidates. Assumptions about version: - Official release versions are MAJOR.minor, where MAJOR and minor are both non-negative integers. E.g. 2.9 2.10 2.11 3.0 3.1 3.2 - Release candidate versions are MAJOR.minor-rc.N, where MAJOR, minor, and N are all non-negative integers. 3.5-rc.1 3.5-rc.2 """
if not self.get('autoinc_version'): return oldver = self['version'] newver = bump_version_tail(oldver) config_path = self.filepath temp_fd, temp_name = tempfile.mkstemp( dir=os.path.dirname(config_path), ) with open(config_path) as old: with os.fdopen(temp_fd, 'w') as new: for oldline in old: if oldline.startswith('version:'): new.write("version: '%s'\n" % newver) continue new.write(oldline) # no need to backup the old file, it's under version control anyway - # right??? log.info('Incrementing stack version %s -> %s' % (oldver, newver)) os.rename(temp_name, config_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 setup(name, path='log', enable_debug=False): """ Prepare a NestedSetup. :param name: the channel name :param path: the path where the logs will be written :param enable_debug: do we want to save the message at the DEBUG level :return a nested Setup """
path_tmpl = os.path.join(path, '{name}_{level}.log') info = path_tmpl.format(name=name, level='info') warn = path_tmpl.format(name=name, level='warn') err = path_tmpl.format(name=name, level='err') crit = path_tmpl.format(name=name, level='crit') # a nested handler setup can be used to configure more complex setups setup = [ # make sure we never bubble up to the stderr handler # if we run out of setup handling NullHandler(), # then write messages that are at least info to to a logfile TimedRotatingFileHandler(info, level='INFO', encoding='utf-8', date_format='%Y-%m-%d'), # then write messages that are at least warnings to to a logfile TimedRotatingFileHandler(warn, level='WARNING', encoding='utf-8', date_format='%Y-%m-%d'), # then write messages that are at least errors to to a logfile TimedRotatingFileHandler(err, level='ERROR', encoding='utf-8', date_format='%Y-%m-%d'), # then write messages that are at least critical errors to to a logfile TimedRotatingFileHandler(crit, level='CRITICAL', encoding='utf-8', date_format='%Y-%m-%d'), ] if enable_debug: debug = path_tmpl.format(name=name, level='debug') setup.insert(1, TimedRotatingFileHandler(debug, level='DEBUG', encoding='utf-8', date_format='%Y-%m-%d')) if src_server is not None and smtp_server is not None \ and smtp_port != 0 and len(dest_mails) != 0: mail_tmpl = '{name}_error@{src}' from_mail = mail_tmpl.format(name=name, src=src_server) subject = 'Error in {}'.format(name) # errors should then be delivered by mail and also be kept # in the application log, so we let them bubble up. setup.append(MailHandler(from_mail, dest_mails, subject, level='ERROR', bubble=True, server_addr=(smtp_server, smtp_port))) return NestedSetup(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 mail_setup(path): """ Set the variables to be able to send emails. :param path: path to the config file """
global dest_mails global smtp_server global smtp_port global src_server config = configparser.RawConfigParser() config.readfp(path) dest_mails = config.get('mail', 'dest_mail').split(',') smtp_server = config.get('mail', 'smtp_server') smtp_port = config.get('mail', 'smtp_port') src_server = config.get('mail', 'src_server')
<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(log_name, path, debug=False, mail=None, timeout=0): """ Run a subscriber and pass the messages to the logbook setup. Stays alive as long as the pubsub instance listen to something. :param log_name: the channel to listen to :param path: the path where the log files will be written :param debug: True if you want to save the debug messages too :param mail: Path to the config file for the mails """
global pubsub global channel channel = log_name if use_tcp_socket: r = redis.StrictRedis(host=hostname, port=port) else: r = redis.StrictRedis(unix_socket_path=unix_socket) pubsub = r.pubsub() pubsub.psubscribe(channel + '.*') if timeout != 0: deadline = time.time() + timeout logger = Logger(channel) if mail is not None: mail_setup(mail) if os.path.exists(path) and not os.path.isdir(path): raise Exception("The path you want to use to save the file is invalid (not a directory).") if not os.path.exists(path): os.mkdir(path) with setup(channel, path, debug): while True: msg = pubsub.get_message() if msg: if msg['type'] == 'pmessage': level = msg['channel'].decode('utf-8').split('.')[1] message = msg['data'] try: message = message.decode('utf-8') except: pass logger.log(level, message) time.sleep(0.01) if timeout > 0: if time.time() >= deadline: break
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_options(cls, options): """Pass options through to this plugin."""
cls.ignore_decorators = options.ignore_decorators cls.exclude_from_doctest = options.exclude_from_doctest if not isinstance(cls.exclude_from_doctest, list): cls.exclude_from_doctest = [cls.exclude_from_doctest]
<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_source(self): """Load the source for the specified file."""
if self.filename in self.STDIN_NAMES: self.filename = 'stdin' self.source = pycodestyle.stdin_get_value() else: with pep257.tokenize_open(self.filename) as fd: self.source = fd.read()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepare(self, data_source): """ Called with the training data. @param data_source: Either a pandas.DataFrame or a file-like object. """
dataframe = self.__get_dataframe(data_source, use_target=True) self.__config.get_data_model().set_features_types_from_dataframe(dataframe) dataframe = self.__cleaner.prepare(dataframe) return self.__transformer.prepare(dataframe)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fix_rst_heading(heading, below): """If the 'below' line looks like a reST line, give it the correct length. This allows for different characters being used as header lines. """
if len(below) == 0: return below first = below[0] if first not in '-=`~': return below if not len(below) == len([char for char in below if char == first]): # The line is not uniformly the same character return below below = first * len(heading) return below
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sanity_check(vcs): """Do sanity check before making changes Check that we are not on a tag and/or do not have local changes. Returns True when all is fine. """
if not vcs.is_clean_checkout(): q = ("This is NOT a clean checkout. You are on a tag or you have " "local changes.\n" "Are you sure you want to continue?") if not ask(q, default=False): sys.exit(1)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_recommended_files(data, vcs): """Do check for recommended files. Returns True when all is fine. """
main_files = os.listdir(data['workingdir']) if not 'setup.py' in main_files and not 'setup.cfg' in main_files: # Not a python package. We have no recommendations. return True if not 'MANIFEST.in' in main_files and not 'MANIFEST' in main_files: q = ("This package is missing a MANIFEST.in file. This file is " "recommended. " "See http://docs.python.org/distutils/sourcedist.html" " for more info. Sample contents:" "\n" "recursive-include main_directory *" "recursive-include docs *" "include *" "global-exclude *.pyc" "\n" "You may want to quit and fix this.") if not vcs.is_setuptools_helper_package_installed(): q += "Installing %s may help too.\n" % \ vcs.setuptools_helper_package # We could ask, but simply printing it is nicer. Well, okay, # let's avoid some broken eggs on PyPI, per # https://github.com/zestsoftware/zest.releaser/issues/10 q += "Do you want to continue with the release?" if not ask(q, default=False): return False print(q) 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 cleanup_version(version): """Check if the version looks like a development version."""
for w in WRONG_IN_VERSION: if version.find(w) != -1: logger.debug("Version indicates development: %s.", version) version = version[:version.find(w)].strip() logger.debug("Removing debug indicators: %r", version) version = version.rstrip('.') # 1.0.dev0 -> 1.0. -> 1.0 return 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 pager(__text: str, *, pager: Optional[str] = 'less'): """Pass output through pager. See :manpage:`less(1)`, if you wish to configure the default pager. For example, you may wish to check ``FRSX`` options. Args: __text: Text to page pager: Pager to use """
if pager: run([pager, ], input=__text.encode()) else: print(__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 listen(self, **kwargs: Any) -> Server: """ bind host, port or sock """
loop = cast(asyncio.AbstractEventLoop, self._loop) return (yield from loop.create_server( lambda: self._protocol( loop=loop, handle=self._handle, requset_charset=self.requset_charset, response_charset=self.response_charset, ), **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 type_and_model_to_query(self, request): """ Return JSON for an individual Model instance If the required parameters are wrong, return 400 Bad Request If the parameters are correct but there is no data, return empty JSON """
try: content_type_id = request.GET["content_type_id"] object_id = request.GET["object_id"] except KeyError: return HttpResponseBadRequest() try: content_type = ContentType.objects.get(pk=content_type_id) model = content_type.model_class() result = model.objects.get(pk=object_id) except ObjectDoesNotExist: data = "" else: data = '%s: "%d: %s"' % (content_type.model, result.pk, result) return JsonResponse({"query": 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 load(self, paths, params=None): """ Load data from configuration files. Configuration values are read from a sequence of one or more YAML files. Files are read in the given order, and a duplicate value will overwrite the existing value. The optional 'params' argument is a dict-like object to use for parameter substitution in the config files. Any text matching "%key;" will be replaced with the value for 'key' in params. """
def replace(match): """ Callback for re.sub to do parameter replacement. """ # This allows for multi-pattern substitution in a single pass. return params[match.group(0)] params = {r"%{:s};".format(key): val for (key, val) in params.iteritems()} if params else {} regex = compile("|".join(params) or r"^(?!)") for path in paths: with open(path, "r") as stream: # Global text substitution is used for parameter replacement. # Two drawbacks of this are 1) the entire config file has to be # read into memory first; 2) it might be nice if comments were # excluded from replacement. A more elegant (but complex) # approach would be to use PyYAML's various hooks to do the # substitution as the file is parsed. logger.info("reading config data from {:s}".format(path)) yaml = regex.sub(replace, stream.read()) try: self.update(load(yaml)) except TypeError: # load() returned None logger.warn("config file '{:s}' is empty".format(yaml)) 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 get_repositories(path): """ Return an array of tuples with the name and path for repositories found in a directory. :param str path: The path to find repositories in :returns: tuple """
return [get_repository(os.path.join(path, subdir)) for subdir in os.listdir(path) if os.path.isdir( os.path.join(path, subdir, '.git'))]
<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_repository_names(path): """ Return an array of the path name for repositories found in a directory. :param str path: The path to find repositories in :returns: array """
return [subdir for subdir in os.listdir(path) if os.path.isdir(os.path.join(path, subdir, '.git'))]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_schemas(repo): """ Return a list of parsed avro schemas as dictionaries. :param Repo repo: The git repository. :returns: dict """
schema_files = glob.glob( os.path.join(repo.working_dir, '_schemas', '*.avsc')) schemas = {} for schema_file in schema_files: with open(schema_file, 'r') as fp: schema = json.load(fp) schemas['%(namespace)s.%(name)s' % schema] = schema return schemas
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_content_types(repo): """ Return a list of content types in a repository. :param Repo repo: The git repository. :returns: list """
schema_files = glob.glob( os.path.join(repo.working_dir, '_schemas', '*.avsc')) return [os.path.splitext(os.path.basename(schema_file))[0] for schema_file in schema_files]
<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_schema(repo, content_type): """ Return a schema for a content type in a repository. :param Repo repo: The git repository. :returns: dict """
try: with open( os.path.join(repo.working_dir, '_schemas', '%s.avsc' % (content_type,)), 'r') as fp: data = fp.read() return avro.schema.parse(data) except IOError: # pragma: no cover raise NotFound('Schema does not exist.')
<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_mapping(repo, content_type): """ Return an ES mapping for a content type in a repository. :param Repo repo: This git repository. :returns: dict """
try: with open( os.path.join(repo.working_dir, '_mappings', '%s.json' % (content_type,)), 'r') as fp: return json.load(fp) except IOError: raise NotFound('Mapping does not exist.')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def format_repo(repo): """ Return a dictionary representing the repository It returns ``None`` for things we do not support or are not relevant. :param str repo_name: The name of the repository. :param git.Repo repo: The repository object. :param str base_url: The base URL for the repository's links. :returns: dict """
commit = repo.commit() return { 'name': os.path.basename(repo.working_dir), 'branch': repo.active_branch.name, 'commit': commit.hexsha, 'timestamp': datetime.fromtimestamp( commit.committed_date).isoformat(), 'author': '%s <%s>' % (commit.author.name, commit.author.email), 'schemas': list_schemas(repo) }
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def format_diffindex(diff_index): """ Return a JSON formattable representation of a DiffIndex. Returns a generator that returns dictionaries representing the changes. .. code:: [ { 'type': 'A', 'path': 'path/to/added/file.txt', }, { 'type': 'D', 'path': 'path/to/deleted/file.txt', }, { 'type': 'M', 'path': 'path/to/modified/file.txt', }, { 'type': 'R', 'rename_from': 'original/path/to/file.txt', 'rename_to': 'new/path/to/file.txt', }, ] :returns: generator """
for diff in diff_index: if diff.new_file: yield format_diff_A(diff) elif diff.deleted_file: yield format_diff_D(diff) elif diff.renamed: yield format_diff_R(diff) elif diff.a_blob and diff.b_blob and diff.a_blob != diff.b_blob: yield format_diff_M(diff)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def format_content_type(repo, content_type): """ Return a list of all content objects for a given content type in a repository. :param Repo repo: The git repository. :param str content_type: The content type to list :returns: list """
storage_manager = StorageManager(repo) model_class = load_model_class(repo, content_type) return [dict(model_obj) for model_obj in storage_manager.iterate(model_class)]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def format_content_type_object(repo, content_type, uuid): """ Return a content object from a repository for a given content_type and uuid :param Repo repo: The git repository. :param str content_type: The content type to list :returns: dict """
try: storage_manager = StorageManager(repo) model_class = load_model_class(repo, content_type) return dict(storage_manager.get(model_class, uuid)) except GitCommandError: raise NotFound('Object does not exist.')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def format_repo_status(repo): """ Return a dictionary representing the repository status It returns ``None`` for things we do not support or are not relevant. :param str repo_name: The name of the repository. :returns: dict """
commit = repo.commit() return { 'name': os.path.basename(repo.working_dir), 'commit': commit.hexsha, 'timestamp': datetime.fromtimestamp( commit.committed_date).isoformat(), }
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save_content_type_object(repo, schema, uuid, data): """ Save an object as a certain content type """
storage_manager = StorageManager(repo) model_class = deserialize(schema, module_name=schema['namespace']) model = model_class(data) commit = storage_manager.store(model, 'Updated via PUT request.') return commit, model
<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_content_type_object(repo, content_type, uuid): """ Delete an object of a certain content type """
storage_manager = StorageManager(repo) model_class = load_model_class(repo, content_type) model = storage_manager.get(model_class, uuid) commit = storage_manager.delete(model, 'Deleted via DELETE request.') return commit, model
<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_model_class(repo, content_type): """ Return a model class for a content type in a repository. :param Repo repo: The git repository. :param str content_type: The content type to list :returns: class """
schema = get_schema(repo, content_type).to_json() return deserialize(schema, module_name=schema['namespace'])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def search_composite(self, query, source, payload=None): '''Shortcut search with composite source''' source = '+'.join(source) if payload is None: payload = dict(Sources=quote(source)) else: payload['Sources'] = quote(source) return self.search(query, 'Composite', payload)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def key_of(d): """ Returns the key of a single element dict. """
if len(d) > 1 and not type(d) == dict(): raise ValueError('key_of(d) may only except single element dict') else: return keys_of(d)[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 open_grindstone(self): """ Opens a grindstone file and populates the grindstone with it's contents. Returns an empty grindstone json object if a file does not exist. """
try: with open(self.grindstone_path, 'r') as f: # Try opening the file return json.loads(f.read()) # If the file is empty except json.decoder.JSONDecodeError: # Default return empty object with empty tasks list return {'tasks': []} # The file does not yet exist except FileNotFoundError: # Default return empty object with empty tasks list return {'tasks': []}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_task(self, task=None): """ Deletes a given task by name. """
# Iterate over the list of tasks for t in self.grindstone['tasks']: # If they key of the task matches the task given if key_of(t) == task: # Remove that task self.grindstone['tasks'].remove(t) # Return True because something did happen return True # Return false because nothing happened 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 write_grindstone(self): """ Writes self.gs to self.grindstone_path. """
with open(self.grindstone_path, 'w') as f: # Write the JSON dump of the file f.write(json.dumps(self.grindstone))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def datetime2unix(T): """ converts datetime to UT1 unix epoch time """
T = atleast_1d(T) ut1_unix = empty(T.shape, dtype=float) for i, t in enumerate(T): if isinstance(t, (datetime, datetime64)): pass elif isinstance(t, str): try: ut1_unix[i] = float(t) # it was ut1_unix in a string continue except ValueError: t = parse(t) # datetime in a string elif isinstance(t, (float, int)): # assuming ALL are ut1_unix already return T else: raise TypeError('I only accept datetime or parseable date string') # ut1 seconds since unix epoch, need [] for error case ut1_unix[i] = forceutc(t).timestamp() return ut1_unix
<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_iterable(val): """Ensure that a value is iterable and not some sort of string"""
try: iter(val) except (ValueError, TypeError): return False else: return not isinstance(val, basestring)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download_url(url, destination, retries=None, retry_delay=None, runner=None): """Download the given URL with wget to the provided path. The command is run via Fabric on the current remote machine. Therefore, the destination path should be for the remote machine. :param str url: URL to download onto the remote machine :param str destination: Path to download the URL to on the remote machine :param int retries: Max number of times to retry downloads after a failure :param float retry_delay: Number of seconds between download retries :param FabRunner runner: Optional runner to use for executing commands. :return: The results of the wget call """
runner = runner if runner is not None else FabRunner() return try_repeatedly( lambda: runner.run("wget --quiet --output-document '{0}' '{1}'".format(destination, url)), max_retries=retries, delay=retry_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_install_sources(self): """Construct arguments to use alternative package indexes if there were sources supplied, empty string if there were not. """
if not self._sources: return '' parts = ['--no-index'] for source in self._sources: parts.append("--find-links '{0}'".format(source)) return ' '.join(parts)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def install(self, release_id, upgrade=False): """Install target packages into a virtual environment. If the virtual environment for the given release ID does not exist on the remote system, it will be created. The virtual environment will be created according to the standard Tunic directory structure (see :doc:`design`). If ``upgrade=True`` is passed, packages will be updated to the most recent version if they are already installed in the virtual environment. :param str release_id: Timestamp-based identifier for this deployment. If this ID corresponds to a virtual environment that already exists, packages will be installed into this environment. :param bool upgrade: Should packages be updated if they are already installed in the virtual environment. :return: The results of running the installation command using Fabric. Note that this return value is a decorated version of a string that contains additional meta data about the result of the command, in addition to the output generated. :rtype: str """
release_path = os.path.join(self._releases, release_id) if not self._runner.exists(release_path): self._runner.run("{0} '{1}'".format(self._venv_path, release_path)) cmd = [os.path.join(release_path, 'bin', 'pip'), 'install'] if upgrade: cmd.append('--upgrade') sources = self._get_install_sources() if sources: cmd.append(sources) cmd.extend("'{0}'".format(package) for package in self._packages) return self._runner.run(' '.join(cmd))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def install(self, release_id): """Install the contents of the local directory into a release directory. If the directory for the given release ID does not exist on the remote system, it will be created. The directory will be created according to the standard Tunic directory structure (see :doc:`design`). Note that the name and path of the local directory is irrelevant, only the contents of the specified directory will be transferred to the remote server. The contents will end up as children of the release directory on the remote server. :param str release_id: Timestamp-based identifier for this deployment. If this ID corresponds to a directory that already exists, contents of the local directory will be copied into this directory. :return: The results of the ``put`` command using Fabric. This return value is an iterable of the paths of all files uploaded on the remote server. """
release_path = os.path.join(self._releases, release_id) if not self._runner.exists(release_path): self._runner.run("mkdir -p '{0}'".format(release_path)) # Make sure to remove any user supplied globs or trailing slashes # so that we can ensure exactly the glob behavior we want from the # put command. local_path = self._local_path.strip('*').strip(os.path.sep) return self._runner.put(os.path.join(local_path, '*'), release_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 install(self, release_id): """Install the local artifact into the remote release directory, optionally with a different name than the artifact had locally. If the directory for the given release ID does not exist on the remote system, it will be created. The directory will be created according to the standard Tunic directory structure (see :doc:`design`). :param str release_id: Timestamp-based identifier for this deployment. :param int retries: Max number of times to retry downloads after a failure :param float retry_delay: Number of seconds between download retries :return: The results of the ``put`` command using Fabric. This return value is an iterable of the paths of all files uploaded on the remote server. """
release_path = os.path.join(self._releases, release_id) if not self._runner.exists(release_path): self._runner.run("mkdir -p '{0}'".format(release_path)) # The artifact can optionally be renamed when being uploaded to # remote server. Useful for when we need a consistent name for # each deploy on the remote server but the local artifact includes # version numbers or something. if self._remote_name is not None: destination = os.path.join(release_path, self._remote_name) else: destination = release_path return self._runner.put(self._local_file, destination, mirror_local_mode=True)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_file_from_url(url): """Get the filename part of the path component from a URL."""
path = urlparse(url).path if not path: raise ValueError("Could not extract path from URL '{0}'".format(url)) name = os.path.basename(path) if not name: raise ValueError("Could not extract file name from path '{0}'".format(path)) return name
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def install(self, release_id): """Download and install an artifact into the remote release directory, optionally with a different name the the artifact had. If the directory for the given release ID does not exist on the remote system, it will be created. The directory will be created according to the standard Tunic directory structure (see :doc:`design`). :param str release_id: Timestamp-based identifier for this deployment. :return: The results of the download function being run. This return value should be the result of running a command with Fabric. By default this will be the result of running ``wget``. """
release_path = os.path.join(self._releases, release_id) if not self._runner.exists(release_path): self._runner.run("mkdir -p '{0}'".format(release_path)) # The artifact can optionally be renamed to something specific when # downloaded on the remote server. In that case use the provided name # in the download path. Otherwise, just use the last component of # of the URL we're downloading. if self._remote_name is not None: destination = os.path.join(release_path, self._remote_name) else: destination = os.path.join(release_path, self._get_file_from_url(self._artifact_url)) # Note that although the default implementation of a download method # accepts a FabRunner instance, we aren't passing our instance here. # The reason being, that's only needed for testing the download_url # method. If we were testing class, we'd mock out the download method # anyway. So, it's not part of the public API of the download interface # and we don't deal with it here. return self._downloader( self._artifact_url, destination, retries=self._retries, retry_delay=self._retry_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 pool_process(func, iterable, process_name='Pool processing', cpus=cpu_count()): """ Apply a function to each element in an iterable and return a result list. :param func: A function that returns a value :param iterable: A list or set of elements to be passed to the func as the singular parameter :param process_name: Name of the process, for printing purposes only :param cpus: Number of CPUs :return: Result list """
with Timer('\t{0} ({1}) completed in'.format(process_name, str(func))): pool = Pool(cpus) vals = pool.map(func, 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 remover(file_path): """Delete a file or directory path only if it exists."""
if os.path.isfile(file_path): os.remove(file_path) return True elif os.path.isdir(file_path): shutil.rmtree(file_path) return True else: return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def creation_date(path_to_file, return_datetime=True): """ Retrieve a file's creation date. Try to get the date that a file was created, falling back to when it was last modified if that isn't possible. See http://stackoverflow.com/a/39501288/1709587 for explanation. :param path_to_file: File path :param return_datetime: Bool, returns value in Datetime format :return: Creation date """
if platform.system() == 'Windows': created_at = os.path.getctime(path_to_file) else: stat = os.stat(path_to_file) try: created_at = stat.st_birthtime except AttributeError: # We're probably on Linux. No easy way to get creation dates here, # so we'll settle for when its content was last modified. created_at = stat.st_mtime if return_datetime: return datetime.fromtimestamp(created_at) else: return created_at
<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_filepaths(self): """Filters list of file paths to remove non-included, remove excluded files and concatenate full paths."""
self._printer(str(self.__len__()) + " file paths have been parsed in " + str(self.timer.end)) if self._hash_files: return pool_hash(self.filepaths) else: return self.filepaths
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def files(self): """Return list of files in root directory"""
self._printer('\tFiles Walk') for directory in self.directory: for path in os.listdir(directory): full_path = os.path.join(directory, path) if os.path.isfile(full_path): if not path.startswith('.'): self.filepaths.append(full_path) return self._get_filepaths()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def folders(self): """Return list of folders in root directory"""
for directory in self.directory: for path in os.listdir(directory): full_path = os.path.join(directory, path) if os.path.isdir(full_path): if not path.startswith('.'): self.filepaths.append(full_path) return self._get_filepaths()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def url(self, pattern, method=None, name=None): """Decorator to map url pattern to the callable. Args: pattern (:obj:`str`): URL pattern to add. This is usually '/' separated path. Parts of the URL can be parameterised using curly braces. Examples: "/", "/path/to/resource", "/resoures/{param}" method (:obj:`str`, :obj:`list` of :obj:`str`, optional): HTTP methods for the path specied. By default, GET method is added. Value can be either a single method, by passing a string, or multiple methods, by passing a list of strings. name (:obj:`str`): Name for the pattern that can be used for reverse matching Note: A trailing '/' is always assumed in the pattern. Example: See Also: :func:`drongo.managers.url.UrlManager.add` """
def _inner(call): self._url_manager.add(pattern, method, call, name) return call return _inner
<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_exif_data(self, image): """Returns a dictionary from the exif data of an PIL Image item. Also converts the GPS Tags"""
exif_data = {} info = image._getexif() if info: for tag, value in info.items(): decoded = TAGS.get(tag, tag) if decoded == "GPSInfo": gps_data = {} for t in value: sub_decoded = GPSTAGS.get(t, t) gps_data[sub_decoded] = value[t] exif_data[decoded] = gps_data else: exif_data[decoded] = value return exif_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 _convert_to_degress(self, value): """Helper function to convert the GPS coordinates stored in the EXIF to degress in float format"""
d0 = value[0][0] d1 = value[0][1] d = float(d0) / float(d1) m0 = value[1][0] m1 = value[1][1] m = float(m0) / float(m1) s0 = value[2][0] s1 = value[2][1] s = float(s0) / float(s1) return d + (m / 60.0) + (s / 3600.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 add_reader( self, fd: IFileLike, callback: typing.Callable[[IFileLike], typing.Any], ) -> None: """Add a file descriptor to the processor and wait for READ. Args: fd (IFileLike): Any obect that exposes a 'fileno' method that returns a valid file descriptor integer. callback (typing.Callable[[IFileLike], typing.Any]): A function that consumes the IFileLike object whenever the READ event is fired. """
raise NotImplementedError()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _load(self, path='config', filetype=None, relaxed=False, ignore=False): """ load key value pairs from a file Parameters: path - path to configuration data (see Note 1) filetype - type component of dot-delimited path relaxed - if True, define keys on the fly (see Note 2) ignore - if True, ignore undefined keys in path Return: self Notes: 1. The path can be: * an open file object with a readlines method * a dot delimited path to a file (see normalize_path) * an os-specific path to a file (relative to cwd) * an iterable of key=value strings 2. Normally keys read from the file must conform to keys previously defined for the Config. If the relaxed flag is True, any keys found in the file will be accepted. If the ignore flag is True, and kyes found in the file that are not previously defined are ignored. """
for num, line in enumerate( un_comment(load_lines_from_path(path, filetype)), start=1, ): if not line: continue try: key, val = line.split('=', 1) key = key.strip() val = val.strip() if relaxed: self._define(key) try: level, itemname = self.__lookup(key) except KeyError: if ignore: continue raise item = level.get(itemname) if item is None: raise KeyError(itemname) item.load(val) except Exception as e: args = e.args or ('',) msg = 'line {} of config: {}'. format(num, args[0]) e.args = (msg,) + args[1:] raise return self