Dataset Viewer
Auto-converted to Parquet Duplicate
description
stringlengths
9
5.32k
code
stringlengths
78
7.14k
From a list of args, extract the one param if supplied, returning the value and unused args. >>> extract_param('port', ['foo', '--port=999', 'bar'], type=int) (999, ['foo', 'bar']) >>> extract_param('port', ['foo', '--port', '999', 'bar'], type=int) (999, ['foo', 'bar']) >>> extract_param('port...
def extract_param(param, args, type=None): parser = argparse.ArgumentParser() parser.add_argument('--' + param, type=type) res, unused = parser.parse_known_args(args) return getattr(res, param), unused
Generates an orthonormal basis in the plane perpendicular to `normal` The orthonormal basis generated spans the plane defined with `normal` as its normal vector. The handedness of `on1` and `on2` in the returned basis is such that: .. math:: \mathsf{on1} \times \mathsf{on2} = ...
def ortho_basis(normal, ref_vec=None): # Imports for library functions import numpy as np from scipy import linalg as spla from scipy import random as sprnd from ..const import PRM from ..error import VectorError # Internal parameters # Magnitude of the perturbation from 'normal' in co...
If any exception comes, log them in the given Github obj.
def exception_to_github(github_obj_to_comment, summary=""): context = ExceptionContext() try: yield context except Exception: # pylint: disable=broad-except if summary: summary = ": ({})".format(summary) error_type = "an unknown error" try: raise ...
Find a field of any of the specified types.
def find_any_field(browser, field_types, field_name): return reduce( operator.add, (find_field(browser, field_type, field_name) for field_type in field_types) )
takes a large data file and produces a HTML summary as html
def summarise_file_as_html(fname): txt = '<H1>' + fname + '</H1>' num_lines = 0 print('Reading OpenCyc file - ', fname) with open(ip_folder + os.sep + fname, 'r') as f: txt += '<PRE>' for line in f: if line.strip() != '': num_lines += 1 if num...
Run setup tasks to set up a nicely configured desktop pc. This is highly biased on my personal preference. The task is defined in file fabsetup_custom/fabfile_addtitions/__init__.py and could be customized by Your own needs. More info: README.md
def setup_desktop(): run('sudo apt-get update') install_packages(packages_desktop) execute(custom.latex) execute(setup.ripping_of_cds) execute(setup.regex_repl) execute(setup.i3) execute(setup.solarized) execute(setup.vim) execute(setup.tmux) execute(setup.pyenv) # circumvent...
Function to acqure the keyfile SNS keys expire and Amazon does not promise they will use the same key for all SNS requests. So we need to keep a copy of the cert in our cache
def grab_keyfile(cert_url): key_cache = caches[getattr(settings, 'BOUNCY_KEY_CACHE', 'default')] pemfile = key_cache.get(cert_url) if not pemfile: response = urlopen(cert_url) pemfile = response.read() # Extract the first certificate in the file and confirm it's a valid # PE...
Loads data from a file. Determines the file type automatically ``"file"``, ``"fifo"``, ``"socket"``, but allows to specify the representation type ``"string"`` or ``"mmap"`` for memory mapped access to the file. Returns the loaded item as a ``str`` or ``mmap`` object. Internally creates an item from ...
def load_item(inbox, type="string", remove=True, buffer=None): is_file, is_fifo, is_socket = False, False, False file = inbox[0] try: file_type = file[0] except: raise ValueError("invalid inbox item") if file_type == "file": is_file = os.path.exists(file[1]) elif file_ty...
Create a comment, whatever the object is a PR, a commit or an issue.
def create_comment(github_object, body): try: return github_object.create_issue_comment(body) # It's a PR except AttributeError: return github_object.create_comment(body)
Run snpeff on an input vcf. :param toil.fileStore.FileID merged_mutation_file: fsID for input vcf :param dict univ_options: Dict of universal options used by almost all tools :param dict snpeff_options: Options specific to snpeff :return: fsID for the snpeffed vcf :rtype: toil.fileStore.FileID
def run_snpeff(job, merged_mutation_file, univ_options, snpeff_options): work_dir = os.getcwd() input_files = { 'merged_mutations.vcf': merged_mutation_file, 'snpeff_index.tar.gz': snpeff_options['index']} input_files = get_files_from_filestore(job, input_files, work_dir, docker=False) i...
convert codon to amino acid
def codon2aa(codon, trans_table): return Seq(''.join(codon), IUPAC.ambiguous_dna).translate(table = trans_table)[0]
First-Fit Decreasing This is perhaps the simplest packing heuristic; it simply packs items in the next available bin. This algorithm differs only from Next-Fit Decreasing in having a 'sort'; that is, the items are pre-sorted (largest to smallest). Complexity O(n^2)
def ffd(items, targets, **kwargs): sizes = zip(items, weight(items, **kwargs)) sizes = sorted(sizes, key=operator.itemgetter(1), reverse=True) items = map(operator.itemgetter(0), sizes) return ff(items, targets)
Takes a NexSON object and returns a dict of otu_id -> otu_obj
def gen_otu_dict(nex_obj, nexson_version=None): if nexson_version is None: nexson_version = detect_nexson_version(nex_obj) if _is_by_id_hbf(nexson_version): otus = nex_obj['nexml']['otusById'] if len(otus) > 1: d = {} for v in otus.values(): d.upda...
Generate a matrix from a configuration dictionary.
def from_config(config): matrix = {} variables = config.keys() for entries in product(*config.values()): combination = dict(zip(variables, entries)) include = True for value in combination.values(): for reducer in value.reducers: if reducer.pattern == '-':...
Clone the given URL to the folder. :param str branch_or_commit: If specified, switch to this branch. Branch must exist.
def clone_to_path(https_authenticated_url, folder, branch_or_commit=None): _LOGGER.info("Cloning repo") repo = Repo.clone_from(https_authenticated_url, str(folder)) # Do NOT clone and set branch at the same time, since we allow branch to be a SHA1 # And you can't clone a SHA1 if branch_or_commit: ...
reverse completement stats
def rc_stats(stats): rc_nucs = {'A':'T', 'T':'A', 'G':'C', 'C':'G', 'N':'N'} rcs = [] for pos in reversed(stats): rc = {} rc['reference frequencey'] = pos['reference frequency'] rc['consensus frequencey'] = pos['consensus frequency'] rc['In'] = pos['In'] rc['Del'] = p...
Make `value` suitable for a dictionary. * If `value` is an Entity, call to_dict() on it. * If value is a timestamp, turn it into a string value. * If none of the above are satisfied, return the input value
def _dictify(field, value): if value is None: return None elif field.type_: return value.to_dict() return field.dict_value(value)
Returns a dictionary of variables and their possibly os-dependent defaults.
def get_defaults(): DEFAULTS = {} # Determine the run-time pipe read/write buffer. if 'PC_PIPE_BUF' in os.pathconf_names: # unix x, y = os.pipe() DEFAULTS['PIPE_BUF'] = os.fpathconf(x, "PC_PIPE_BUF") else: # in Jython 16384 # on windows 512 # in jython in ...
Getter function to retrieve objects from a given object dictionary. Used mainly to provide get() inside patterns. :param object_dict: objects, which must have 'name' and 'plugin' as attribute :type object_dict: dictionary :param name: name of the object :type name: str :param plugin: plugin na...
def gw_get(object_dict, name=None, plugin=None): if plugin is not None: if name is None: object_list = {} for key in object_dict.keys(): if object_dict[key].plugin == plugin: object_list[key] = object_dict[key] return object_list ...
Add the entries in defaults dict into input_dict if they don't exist in input_dict This is based on the accepted answer at http://stackoverflow.com/questions/3232943/update-value-of-a-nested-dictionary-of-varying-depth :param dict input_dict: The dict to be updated :param dict defaults_dict: Dict cont...
def _add_default_entries(input_dict, defaults_dict): for key, value in defaults_dict.iteritems(): if key == 'patients': print('Cannot default `patients`.') continue if isinstance(value, dict): if key not in input_dict or input_dict[key] is None: # ...
Do all of the gruntwork associated with creating a new module.
def new_module(name): parent = None if '.' in name: parent_name = name.rsplit('.', 1)[0] parent = __import__(parent_name, fromlist=['']) module = imp.new_module(name) sys.modules[name] = module if parent: setattr(parent, name.rsplit('.', 1)[1], module) return module
Default update operation for a single parser property. If xpaths contains one xpath, then one element per value will be inserted at that location in the tree_to_update; otherwise, the number of values must match the number of xpaths.
def _update_property(tree_to_update, xpath_root, xpaths, values): # Inner function to update a specific XPATH with the values provided def update_element(elem, idx, root, path, vals): """ Internal helper function to encapsulate single item update """ has_root = bool(root and len(path) > len(r...
Load a separated value text file to a list of lists of strings of records. Takes a tabular text file with a specified delimeter and end-of-line character, and return data as a list of lists of strings corresponding to records (rows). Also uses and returns metadata (including column names, formats, ...
def loadSVrecs(fname, uselines=None, skiprows=0, linefixer=None, delimiter_regex=None, verbosity=DEFAULT_VERBOSITY, **metadata): """ Load a separated value text file to a list of lists of strings of records. Takes a tabular text file with a specified delimeter and end-of-line character...
Format the email message element for inclusion request notification. Formats the message according to the provided template file, using some default fields from 'increq' object as default context. Arbitrary context can be provided as keywords ('ctx'), and those will not be overwritten by the fields fro...
def format_request_email_templ(increq, template, **ctx): # Add minimal information to the contex (without overwriting). curate_link = '{site_url}/communities/{id}/curate/'.format( site_url=current_app.config['THEME_SITEURL'], id=increq.community.id) min_ctx = dict( record=Record.get...
Helper function to facilitate upsert. Args: ini_date - the dictionary of info to run upsert Exit: 0 - good 1 - bad
def start_upsert(ini_data): stack_driver = CloudStackUtility(ini_data) poll_stack = not ini_data.get('no_poll', False) if stack_driver.upsert(): logging.info('stack create/update was started successfully.') if poll_stack: stack_tool = None try: profil...
get top hits after sorting by column number
def top_hits(hits, num, column, reverse): hits.sort(key = itemgetter(column), reverse = reverse) for hit in hits[0:num]: yield hit
Convert a file size into natural readable format. Multiple formats are supported. :param value: size :param format: default ``decimal``, choices ``binary``, ``decimal`` or ``gnu`` :param digits: default ``2`` >>> print(filesize(123)) 123.00 B >>> print(filesize(123456)) ...
def filesize(value, format='decimal', digits=2): if format not in FILESIZE_SUFFIX: raise TypeError base = FILESIZE_BASE[format] size = int(value) sign = size < 0 and u'-' or '' size = abs(size) for i, suffix in enumerate(FILESIZE_SUFFIX[format]): unit = base ** (i + 1) ...
Test function to step through all functions in order to try and identify all features on a map This test function should be placed in a main section later
def TEST(fname): #fname = os.path.join(os.getcwd(), '..','..', # os.path.join(os.path.getcwd(), ' m = MapObject(fname, os.path.join(os.getcwd(), 'img_prog_results')) m.add_layer(ImagePathFollow('border')) m.add_layer(ImagePathFollow('river')) m.add_layer(ImagePathFollow('road')) m.add_laye...
calculate bin coverage
def calc_bin_cov(scaffolds, cov): bases = sum([cov[i][0] for i in scaffolds if i in cov]) length = sum([cov[i][1] for i in scaffolds if i in cov]) if length == 0: return 0 return float(float(bases)/float(length))
Rename column of a numpy ndarray with structured dtype, in-place. Implemented by the tabarray method :func:`tabular.tab.tabarray.renamecol`. **Parameters** **X** : numpy ndarray with structured dtype The numpy array for which a column is to be renamed. **ol...
def renamecol(X, old, new): NewNames = tuple([n if n != old else new for n in X.dtype.names]) X.dtype.names = NewNames
Use the factory to establish a connection to uri.
def connect(uri, factory=pymongo.MongoClient): warnings.warn( "do not use. Just call MongoClient directly.", DeprecationWarning) return factory(uri)
Time delta compared to ``t``. You can override ``now`` to specify what time to compare to. :param t: timestamp, :class:`datetime.date` or :class:`datetime.datetime` object :param now: default ``None``, optionally a :class:`datetime.datetime` object :param precision: defaul...
def duration(t, now=None, precision=1, pad=', ', words=None, justnow=datetime.timedelta(seconds=10)): ''' Time delta compared to ``t``. You can override ``now`` to specify what time to compare to. :param t: timestamp, :class:`datetime.date` or :class:`datetime.datetime` objec...
Vector rejection. Calculated by subtracting from `vec` the projection of `vec` onto `vec_onto`: .. math:: \mathsf{vec} - \mathrm{proj}\left(\mathsf{vec}, \ \mathsf{vec\_onto}\right) Parameters ---------- vec length-R |npfloat_| -- Vector to reject vec_ont...
def rej(vec, vec_onto): # Imports import numpy as np # Calculate and return. rej_vec = vec - proj(vec, vec_onto) return rej_vec
Index `bamfile` using samtools :param toil.fileStore.FileID bamfile: fsID for the bam file :param str sample_type: Description of the sample to inject into the filename :param dict univ_options: Dict of universal options used by almost all tools :param dict samtools_options: Options specific to samtool...
def index_bamfile(job, bamfile, sample_type, univ_options, samtools_options, sample_info=None, export=True): """ Index `bamfile` using samtools :param toil.fileStore.FileID bamfile: fsID for the bam file :param str sample_type: Description of the sample to inject into the filename ...
Intra field interlace to sequential converter. This uses a vertical filter with an aperture of 8 lines, generated by :py:class:`~pyctools.components.interp.filtergenerator.FilterGenerator`. The aperture (and other parameters) can be adjusted after the :py:class:`IntraField` component is created.
def IntraField(config={}): return Compound( config = config, deint = SimpleDeinterlace(), interp = Resize(), filgen = FilterGenerator(yaperture=8, ycut=50), gain = Arithmetic(func='data * pt_float(2)'), linkages = { ('self', 'input') : [('deint', 'inp...
Calculate the total number of sequences in each OTU or SampleID. :type biomf: A BIOM file. :param biomf: OTU table format. :type sampleIDs: List :param sampleIDs: A list of column id's from BIOM format OTU table. By default, the list has been set to None. :type sample_abd: B...
def raw_abundance(biomf, sampleIDs=None, sample_abd=True): results = defaultdict(int) if sampleIDs is None: sampleIDs = biomf.ids() else: try: for sid in sampleIDs: assert sid in biomf.ids() except AssertionError: raise ValueError( ...
Check if some tracked fields have changed
def _has_changed(instance): for field, value in instance._original_fields.items(): if field != 'pk' and \ not isinstance(instance._meta.get_field(field), ManyToManyField): try: if field in getattr(instance, '_tracked_fields', []): if isinstance(inst...
Changes a given `changed_fields` on each object in a given `iterable`, saves objects and returns the changed objects.
def bulk_change_and_save(iterable, update_only_changed_fields=False, save_kwargs=None, **changed_fields): return [ change_and_save(obj, update_only_changed_fields=update_only_changed_fields, save_kwargs=save_kwargs, **changed_fields) for obj in iterable ]
Spawn a MuSE job for each chromosome on the DNA bams. :param dict tumor_bam: Dict of bam and bai for tumor DNA-Seq :param dict normal_bam: Dict of bam and bai for normal DNA-Seq :param dict univ_options: Dict of universal options used by almost all tools :param dict muse_options: Options specific to Mu...
def run_muse(job, tumor_bam, normal_bam, univ_options, muse_options): # Get a list of chromosomes to handle if muse_options['chromosomes']: chromosomes = muse_options['chromosomes'] else: chromosomes = sample_chromosomes(job, muse_options['genome_fai']) perchrom_muse = defaultdict() ...
Returns percentages of peak load for all days of the year. Data from the IEEE RTS.
def get_all_days(): weekly = get_weekly() daily = get_daily() return [w * (d / 100.0) for w in weekly for d in daily]
Check out target into the current directory. Target can be a branch, review Id, or commit. :param repository: Current git repository. :param target: Review ID, commit, branch. :return: Return the most recent commit ID (top of the git log).
def checkout(repository, target): # git fetch <remote> refs/changes/<review_id> #git checkout FETCH_HEAD repository.git.fetch([next(iter(repository.remotes)), target]) repository.git.checkout("FETCH_HEAD") return repository.git.rev_parse(["--short", "HEAD"]).encode('ascii', 'ignore')
convert checkM genome info tables to dictionary
def parse_checkM_tables(tables): g2info = {} for table in tables: for line in open(table): line = line.strip().split('\t') if line[0].startswith('Bin Id'): header = line header[8] = 'genome size (bp)' header[5] = '#SCGs' ...
Get a dictionary of file paths and timestamps. Paths matching `exclude` regex will be excluded.
def get_hashes(path, exclude=None): out = {} for f in Path(path).rglob('*'): if f.is_dir(): # We want to watch files, not directories. continue if exclude and re.match(exclude, f.as_posix()): retox_log.debug("excluding '{}'".format(f.as_posix())) c...
Patch pymongo's Collection object to add a tail method. While not nessicarily recommended, you can use this to inject `tail` as a method into Collection, making it generally accessible.
def _patch(): if not __debug__: # pragma: no cover import warnings warnings.warn("A catgirl has died.", ImportWarning) from pymongo.collection import Collection Collection.tail = tail
Iterate over items in a streaming response from the Docker client within a timeout. :param ~docker.types.daemon.CancellableStream stream: Stream from the Docker client to consume items from. :param timeout: Timeout value in seconds. :param timeout_msg: Message to raise in the ex...
def stream_timeout(stream, timeout, timeout_msg=None): timed_out = threading.Event() def timeout_func(): timed_out.set() stream.close() timer = threading.Timer(timeout, timeout_func) try: timer.start() for item in stream: yield item # A timeout look...
Concatenate url and argument dictionary >>> url_concat("http://example.com/foo?a=b", dict(c="d")) 'http://example.com/foo?a=b&c=d' :arg string url: URL being concat to. :arg dict args: Args being concat. :arg bool keep_existing: (Optional) Whether to keep the args which are ...
def url_concat(url, args, keep_existing=True): if not args: return url if keep_existing: if url[-1] not in ('?', '&'): url += '&' if ('?' in url) else '?' return url + urlencode(args, 1) else: url, seq, query = url.partition('?') query = urlparse.parse_qs...
takes a row from an n3 file and returns the triple NOTE - currently parses a CSV line already split via cyc_extract.py
def parse_n3(row, src='csv'): if row.strip() == '': return '','' l_root = 'opencyc' key = '' val = '' if src == 'csv': cols = row.split(',') if len(cols) < 3: #print('PARSE ISSUE : ', row) return '','' key = '' val = '' key = l...
Convenience function to get the expression from the patient dict :param dict patient_dict: dict of patient info :return: The gene and isoform expression :rtype: toil.fileStore.FileID
def get_patient_expression(job, patient_dict): expression_archive = job.fileStore.readGlobalFile(patient_dict['expression_files']) expression_archive = untargz(expression_archive, os.getcwd()) output_dict = {} for filename in 'rsem.genes.results', 'rsem.isoforms.results': output_dict[filename] =...
Read all the trial data and plot the result of applying a function on them.
def plot_all(*args, **kwargs): dfs = do_all(*args, **kwargs) ps = [] for line in dfs: f, df, config = line df.plot(title=config['name']) ps.append(df) return ps
split fasta file into separate fasta files based on list of scaffolds that belong to each separate file
def split_fasta(f, id2f): opened = {} for seq in parse_fasta(f): id = seq[0].split('>')[1].split()[0] if id not in id2f: continue fasta = id2f[id] if fasta not in opened: opened[fasta] = '%s.fa' % fasta seq[1] += '\n' with open(opened[fasta...
cutting nodes away from menus
def cut_levels(nodes, start_level): final = [] removed = [] for node in nodes: if not hasattr(node, 'level'): # remove and ignore nodes that don't have level information remove(node, removed) continue if node.attr.get('soft_root', False): # rem...
Return a select statement's results as dictionary. Parameters ---------- conn : database connection query : select query string params : query parameters. name : server side cursor name. defaults to client side. itersize : number of records fetched by server.
def select_dict(conn, query: str, params=None, name=None, itersize=5000): with conn.cursor(name, cursor_factory=RealDictCursor) as cursor: cursor.itersize = itersize cursor.execute(query, params) for result in cursor: yield result
Returns a case object from the given input file object. The data format may be optionally specified.
def read_case(input, format=None): # Map of data file types to readers. format_map = {"matpower": MATPOWERReader, "psse": PSSEReader, "pickle": PickleReader} # Read case data. if format_map.has_key(format): reader_klass = format_map[format] reader = reader_klass() case =...
Normalize collaboration string. Args: collaboration: a string containing collaboration(s) or None Returns: list: List of extracted and normalized collaborations Examples: >>> from inspire_schemas.utils import normalize_collaboration >>> normalize_collaboration('for the CMS...
def normalize_collaboration(collaboration): if not collaboration: return [] collaboration = collaboration.strip() if collaboration.startswith('(') and collaboration.endswith(')'): collaboration = collaboration[1:-1] collaborations = _RE_AND.split(collaboration) collaborations = (_R...
Skip un parseable functions. :type app: sphinx.application.Sphinx :param str what: the type of the object which the docstring belongs to (one of "module", "class", "exception", "function", "method", "attribute") :param str name: the fully qualified name of the object :param type obj: the object...
def autodoc_skip_member_handler(app, what, name, obj, skip, options): if 'YAMLTokens' in name: return True return False
Converts a model field to a dictionary
def field_to_dict(field, instance): # avoid a circular import from django.db.models.fields.related import ManyToManyField return (many_to_many_field_to_dict(field, instance) if isinstance(field, ManyToManyField) else field.value_from_object(instance))
Load catchment object from a ``.CD3`` or ``.xml`` file. If there is also a corresponding ``.AM`` file (annual maximum flow data) or a ``.PT`` file (peaks over threshold data) in the same folder as the CD3 file, these datasets will also be loaded. :param file_path: Location of CD3 or xml file :type fil...
def from_file(file_path, incl_pot=True): filename, ext = os.path.splitext(file_path) am_file_path = filename + '.AM' pot_file_path = filename + '.PT' parser_by_ext = { '.cd3': parsers.Cd3Parser, '.xml': parsers.XmlCatchmentParser } catchment = parser_by_ext[ext.lower()]().parse(f...
Transforms a pandas dataframe into a bedtool :param df: Pandas dataframe :returns: a bedtool
def dfTObedtool(df): df=df.astype(str) df=df.drop_duplicates() df=df.values.tolist() df=["\t".join(s) for s in df ] df="\n".join(df) df=BedTool(df, from_string=True) return df
Set Cache-Control headers for no caching Will generate proxy-revalidate, no-cache, no-store, must-revalidate, max-age=0.
def dont_cache(): def decorate_func(func): @wraps(func) def decorate_func_call(*a, **kw): callback = SetCacheControlHeadersForNoCachingCallback() registry_provider = AfterThisRequestCallbackRegistryProvider() registry = registry_provider.provide() regi...
optimize later? slow ... should combine with calculate_threshold module
def print_genome_matrix(hits, fastas, id2desc, file_name): out = open(file_name, 'w') fastas = sorted(fastas) print('## percent identity between genomes', file=out) print('# - \t %s' % ('\t'.join(fastas)), file=out) for fasta in fastas: line = [fasta] for other in fastas: ...
Takes a `datetime.timedelta` object and returns the delta in seconds. >>> _total_seconds(datetime.timedelta(23, 42, 123456)) 1987242 >>> _total_seconds(datetime.timedelta(23, 42, 654321)) 1987243
def _total_seconds(t): return sum([ int(t.days * 86400 + t.seconds), int(round(t.microseconds / 1000000.0)) ])
Setup the package.
def setup_package(): with open('requirements.txt', 'r') as req_file: install_reqs = req_file.read().split('\n') cmdclass_ = {'antlr': AntlrBuildCommand} cmdclass_.update(versioneer.get_cmdclass()) setup( version=versioneer.get_version(), name='pymoca', maintainer="James...
Check if given value is a valid URL string. :param value: a value to test :returns: True if the value is valid
def is_valid_url(value): match = URL_REGEX.match(value) host_str = urlparse(value).hostname return match and is_valid_host(host_str)
Uses KEGG to retrieve all ids for a given KEGG organism :param organism: an organism as listed in organismsKEGG() :returns: a Pandas dataframe of with 'gene_name' and 'KEGGid'.
def idsKEGG(organism): ORG=urlopen("http://rest.kegg.jp/list/"+organism).read() ORG=ORG.split("\n") final=[] for k in ORG: final.append(k.split("\t")) df=pd.DataFrame(final[0:len(final)-1])[[0,1]] df.columns=['KEGGid','description'] field = pd.DataFrame(df['description'].str.split(';...
Converts a fraction to a formatted percentage. :param value: number :param digits: default ``2`` >>> print(percentage(1)) 100.00 % >>> print(percentage(0.23, digits=0)) 23 % >>> print(percentage(23.421)) 2,342.10 %
def percentage(value, digits=2): value = float(value) * 100.0 return u'' + '%s %%' % (_format(value, digits),)
Traverse the input otu-sequence file, collect the non-unique OTU IDs and file the sequences associated with then under the unique OTU ID as defined by the input matrix. :@type otuF: file :@param otuF: The output file from QIIME's pick_otus.py :@type nuniqueF: file :@param nuniqueF: The matrix o...
def condense_otus(otuF, nuniqueF): uniqueOTUs = set() nuOTUs = {} # parse non-unique otu matrix for line in nuniqueF: line = line.split() uOTU = line[0] for nuOTU in line[1:]: nuOTUs[nuOTU] = uOTU uniqueOTUs.add(uOTU) otuFilter = defaultdict(list) # ...
Removes any integer represented as a word within text_string and returns the new string as type str. Keyword argument: - text_string: string instance Exceptions raised: - InputError: occurs should a non-string argument be passed
def remove_number_words(text_string): if text_string is None or text_string == "": return "" elif isinstance(text_string, str): for word in NUMBER_WORDS: text_string = re.sub(r'[\S]*\b'+word+r'[\S]*', "", text_string) return " ".join(text_string.split()) else: rai...
Get the distance to the weatherstation from wstation section of xml. wstation: weerstation section of buienradar xml (dict) latitude: our latitude longitude: our longitude
def __get_ws_distance(wstation, latitude, longitude): if wstation: try: wslat = float(wstation[__BRLAT]) wslon = float(wstation[__BRLON]) dist = vincenty((latitude, longitude), (wslat, wslon)) log.debug("calc distance: %s (latitude: %s, longitude: " ...
define ribosomal proteins and location of curated databases
def find_databases(databases): # 16 ribosomal proteins in their expected order proteins = ['L15', 'L18', 'L6', 'S8', 'L5', 'L24', 'L14', 'S17', 'L16', 'S3', 'L22', 'S19', 'L2', 'L4', 'L3', 'S10'] # curated databases protein_databases = { 'L14': 'rpL14_JGI_MDM.filtered.faa', ...
Retrieve how long ago a file has been accessed. :param filename: name of the file >>> print accessed(__file__) # doctest: +SKIP just now
def accessed(filename): if isinstance(filename, file): filename = filename.name return duration(os.stat(filename)[stat.ST_ATIME])
Create an 'index.html' for one package. :param package: Package object to use. :param index_dir: Where 'index.html' should be created.
def make_index_for(package, index_dir, verbose=True): index_template = """\ <html> <head><title>{title}</title></head> <body> <h1>{title}</h1> <ul> {packages} </ul> </body> </html> """ item_template = '<li><a href="{1}">{0}</a></li>' index_filename = os.path.join(index_dir, "index.html") if not os.path....
Attempts to parse `value` into an instance of ``datetime.date``. If `value` is ``None``, this function will return ``None``. Args: value: A timestamp. This can be a string, datetime.date, or datetime.datetime value.
def parse_date(value): if not value: return None if isinstance(value, datetime.date): return value return parse_datetime(value).date()
Create an identity for a given user instance. Primarily useful for testing.
def get_identity(user): identity = Identity(user.id) if hasattr(user, 'id'): identity.provides.add(UserNeed(user.id)) for role in getattr(user, 'roles', []): identity.provides.add(RoleNeed(role.name)) identity.user = user return identity
Normalize arXiv category to be schema compliant. This properly capitalizes the category and replaces the dash by a dot if needed. If the category is obsolete, it also gets converted it to its current equivalent. Example: >>> from inspire_schemas.utils import normalize_arxiv_category >>...
def normalize_arxiv_category(category): category = _NEW_CATEGORIES.get(category.lower(), category) for valid_category in valid_arxiv_categories(): if (category.lower() == valid_category.lower() or category.lower().replace('-', '.') == valid_category.lower()): return valid_cat...
Compares a name in question to a specified name separated into given and family. The name in question ``question_name`` can be of varying format, including "Kyle E. Niemeyer", "Kyle Niemeyer", "K. E. Niemeyer", "KE Niemeyer", and "K Niemeyer". Other possibilities include names with hyphens such as "Chi...
def compare_name(given_name, family_name, question_name): # lowercase everything given_name = given_name.lower() family_name = family_name.lower() question_name = question_name.lower() # rearrange names given as "last, first middle" if ',' in question_name: name_split = question_name.sp...
Parse the types from a structured numpy dtype object. Return list of string representations of types from a structured numpy dtype object, e.g. ['int', 'float', 'str']. Used by :func:`tabular.io.saveSV` to write out type information in the header. **Parameters** **dtype** : numpy dtyp...
def parsetypes(dtype): return [dtype[i].name.strip('1234567890').rstrip('ing') for i in range(len(dtype))]
Find a path from start to target where target is relative to start. >>> tmp = str(getfixture('tmpdir_as_cwd')) >>> findpath('d:\\') 'd:\\' >>> findpath('d:\\', tmp) 'd:\\' >>> findpath('\\bar', 'd:\\') 'd:\\bar' >>> findpath('\\bar', 'd:\\foo') # fails with '\\bar' 'd:\\bar' >>> findpath('bar', 'd:\\foo...
def resolve_path(target, start=os.path.curdir): r""" Find a path from start to target where target is relative to start. >>> tmp = str(getfixture('tmpdir_as_cwd')) >>> findpath('d:\\') 'd:\\' >>> findpath('d:\\', tmp) 'd:\\' >>> findpath('\\bar', 'd:\\') 'd:\\bar' >>> findpath('\\bar', 'd:\\foo') # fails...
Returns a task-agent tuple whose action is always minus one.
def get_neg_one_task_agent(generators, market, nOffer, maxSteps): env = pyreto.discrete.MarketEnvironment(generators, market, nOffer) task = pyreto.discrete.ProfitTask(env, maxSteps=maxSteps) agent = pyreto.util.NegOneAgent(env.outdim, env.indim) return task, agent
Run the strelka subgraph on the DNA bams. Optionally split the results into per-chromosome vcfs. :param dict tumor_bam: Dict of bam and bai for tumor DNA-Seq :param dict normal_bam: Dict of bam and bai for normal DNA-Seq :param dict univ_options: Dict of universal options used by almost all tools ...
def run_strelka(job, tumor_bam, normal_bam, univ_options, strelka_options, split=True): if strelka_options['chromosomes']: chromosomes = strelka_options['chromosomes'] else: chromosomes = sample_chromosomes(job, strelka_options['genome_fai']) num_cores = min(len(chromosomes), univ_options['m...
Return metadata on the NRFA data. Returned metadata is a dict with the following elements: - `url`: string with NRFA data download URL - `version`: string with NRFA version number, e.g. '3.3.4' - `published_on`: datetime of data release/publication (only month and year are accurate, rest should be ign...
def nrfa_metadata(): result = { 'url': config.get('nrfa', 'url', fallback=None) or None, # Empty strings '' become None 'version': config.get('nrfa', 'version', fallback=None) or None, 'published_on': config.get_datetime('nrfa', 'published_on', fallback=None) or None, 'downloaded_on...
calculate genome coverage from scaffold coverage table
def parse_cov(cov_table, scaffold2genome): size = {} # size[genome] = genome size mapped = {} # mapped[genome][sample] = mapped bases # parse coverage files for line in open(cov_table): line = line.strip().split('\t') if line[0].startswith('#'): samples = line[1:] ...
Generate a config file for a ProTECT run on hg19. :return: None
def generate_config_file(): shutil.copy(os.path.join(os.path.dirname(__file__), 'input_parameters.yaml'), os.path.join(os.getcwd(), 'ProTECT_config.yaml'))
Get the field name from a model and a sender from m2m_changed signal.
def _get_m2m_field(model, sender): for field in getattr(model, '_tracked_fields', []): if isinstance(model._meta.get_field(field), ManyToManyField): if getattr(model, field).through == sender: return field for field in getattr(model, '_tracked_related_fields', {}).keys(): ...
Create singleton from class
def singleton(klass): instances = {} def getinstance(*args, **kwargs): if klass not in instances: instances[klass] = klass(*args, **kwargs) return instances[klass] return wraps(klass)(getinstance)
convert stockholm to single line format
def stock2one(stock): lines = {} for line in stock: line = line.strip() if print_line(line) is True: yield line continue if line.startswith('//'): continue ID, seq = line.rsplit(' ', 1) if ID not in lines: lines[ID] = '' ...
Example to show AIKIF logging of results. Generates a sequence of random grids and runs the Game of Life, saving results
def main(): iterations = 9 # how many simulations to run years = 3 # how many times to run each simulation width = 22 # grid height height = 78 # grid width time_delay = 0.03 # delay when printing on screen lg = mod_log.Log('test') lg.record_process('Game ...
Fast "vectorized" max function for element-wise comparison of two numpy arrays. For two numpy arrays `X` and `Y` of equal length, return numpy array `Z` such that:: Z[i] = max(X[i],Y[i]) **Parameters** **X** : numpy array Numpy array; `len(X) = len(Y)`. ...
def arraymax(X,Y): Z = np.zeros((len(X),), int) A = X <= Y B = Y < X Z[A] = Y[A] Z[B] = X[B] return Z
Wrapper around os.path.join that works with Windows drive letters. >>> join('d:\\foo', '\\bar') 'd:\\bar'
def join(*paths): r""" Wrapper around os.path.join that works with Windows drive letters. >>> join('d:\\foo', '\\bar') 'd:\\bar' """ paths_with_drives = map(os.path.splitdrive, paths) drives, paths = zip(*paths_with_drives) # the drive we care about is the last one in the list drive = next(filter(None, revers...
Retrieve the installed path for the given schema. Args: schema(str): relative or absolute url of the schema to validate, for example, 'records/authors.json' or 'jobs.json', or just the name of the schema, like 'jobs'. resolved(bool): if True, the returned path points to a fu...
def get_schema_path(schema, resolved=False): def _strip_first_path_elem(path): """Pass doctests. Strip the first element of the given path, returning an empty string if there are no more elements. For example, 'something/other' will end up as 'other', but passing then 'other' will ...
Checkout this branch. Create it if necessary, and push it to origin.
def checkout_create_push_branch(repo, name): try: repo.git.checkout(name) _LOGGER.info("Checkout %s success", name) except GitCommandError: _LOGGER.info("Checkout %s was impossible (branch does not exist). Creating it and push it.", name) checkout_and_create_branch(repo, name) ...
converts and unknown type to string for display purposes.
def force_to_string(unknown): result = '' if type(unknown) is str: result = unknown if type(unknown) is int: result = str(unknown) if type(unknown) is float: result = str(unknown) if type(unknown) is dict: result = Dict2String(unknown) if type(unknown) is list: ...
Convert an xrb address to public key in bytes >>> xrb_address_to_public_key('xrb_1e3i81r51e3i81r51e3i81r51e3i' '81r51e3i81r51e3i81r51e3imxssakuq') b'00000000000000000000000000000000' :param address: xrb address :type address: bytes :return: public key in bytes ...
def xrb_address_to_public_key(address): address = bytearray(address, 'ascii') if not address.startswith(b'xrb_'): raise ValueError('address does not start with xrb_: %s' % address) if len(address) != 64: raise ValueError('address must be 64 chars long: %s' % address) address = bytes(...
parse catalytic RNAs to gff format
def parse_catalytic(insertion, gff): offset = insertion['offset'] GeneStrand = insertion['strand'] if type(insertion['intron']) is not str: return gff for intron in parse_fasta(insertion['intron'].split('|')): ID, annot, strand, pos = intron[0].split('>')[1].split() Start, End = ...
Aggregate all the called mutations. :param dict mutation_results: Dict of dicts of the various mutation callers in a per chromosome format :param dict univ_options: Dict of universal options used by almost all tools :returns: fsID for the merged mutations file :rtype: toil.fileStore.FileID
def run_mutation_aggregator(job, mutation_results, univ_options): # Setup an input data structure for the merge function out = {} for chrom in mutation_results['mutect'].keys(): out[chrom] = job.addChildJobFn(merge_perchrom_mutations, chrom, mutation_results, u...
Save NRFA metadata to local config file using retrieved config data :param remote_config: Downloaded JSON data, not a ConfigParser object!
def _update_nrfa_metadata(remote_config): config['nrfa']['oh_json_url'] = remote_config['nrfa_oh_json_url'] config['nrfa']['version'] = remote_config['nrfa_version'] config['nrfa']['url'] = remote_config['nrfa_url'] config.set_datetime('nrfa', 'published_on', datetime.utcfromtimestamp(remote_config['nrf...
Uses the built-in argparse module to handle command-line options for the program. :return: The gathered command-line options specified by the user :rtype: argparse.ArgumentParser
def handle_program_options(): parser = argparse.ArgumentParser(description="Convert Sanger-sequencing \ derived data files for use with the \ metagenomics analysis program QIIME, by \ extracting Sample ID ...
de-replicate fastas based on sequence names
def de_rep(fastas, append_index, return_original = False): ids = [] for fasta in fastas: for seq in parse_fasta(fasta): header = seq[0].split('>')[1].split() id = header[0] if id not in ids: ids.append(id) if return_original is True: ...
Splits text_string into a list of sentences based on NLTK's english.pickle tokenizer, and returns said list as type list of str. Keyword argument: - text_string: string instance Exceptions raised: - InputError: occurs should a non-string argument be passed
def create_sentence_list(text_string): if text_string is None or text_string == "": return [] elif isinstance(text_string, str): return SENTENCE_TOKENIZER.tokenize(text_string) else: raise InputError("non-string passed as argument for create_sentence_list")
Compute output = file1 operation file2. Parameters ---------- file1 : file object First FITS file. file2 : file object Second FITS file. operation : string Mathematical operation. output : file object Output FITS file. display : string Character strin...
def compute_operation(file1, file2, operation, output, display, args_z1z2, args_bbox, args_keystitle, args_geometry): """Compute output = file1 operation file2. Parameters ---------- file1 : file object First FITS file. file2 : file object Second FITS file. ...
calculate percent identity
def calc_pident_ignore_gaps(a, b): m = 0 # matches mm = 0 # mismatches for A, B in zip(list(a), list(b)): if A == '-' or A == '.' or B == '-' or B == '.': continue if A == B: m += 1 else: mm += 1 try: return float(float(m)/float((m + mm...
End of preview. Expand in Data Studio

Dataset Card for "desc-code"

More Information needed

Downloads last month
14