_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q55100 | raw_abundance | train | def raw_abundance(biomf, sampleIDs=None, sample_abd=True):
"""
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
... | python | {
"resource": ""
} |
q55101 | transform_raw_abundance | train | def transform_raw_abundance(biomf, fn=math.log10, sampleIDs=None, sample_abd=True):
"""
Function to transform the total abundance calculation for each sample ID to another
format based on user given transformation function.
:type biomf: A BIOM file.
:param biomf: OTU table format.
:param fn: M... | python | {
"resource": ""
} |
q55102 | print_MannWhitneyU | train | def print_MannWhitneyU(div_calc):
"""
Compute the Mann-Whitney U test for unequal group sample sizes.
"""
try:
x = div_calc.values()[0].values()
y = div_calc.values()[1].values()
except:
return "Error setting up input arrays for Mann-Whitney U Test. Skipping "\
... | python | {
"resource": ""
} |
q55103 | print_KruskalWallisH | train | def print_KruskalWallisH(div_calc):
"""
Compute the Kruskal-Wallis H-test for independent samples. A typical rule is that
each group must have at least 5 measurements.
"""
calc = defaultdict(list)
try:
for k1, v1 in div_calc.iteritems():
for k2, v2 in v1.iteritems():
... | python | {
"resource": ""
} |
q55104 | handle_program_options | train | def handle_program_options():
"""Parses the given options passed in at the command line."""
parser = argparse.ArgumentParser(description="Calculate the alpha diversity\
of a set of samples using one or more \
metrics and output a kernal d... | python | {
"resource": ""
} |
q55105 | blastdb | train | def blastdb(fasta, maxfile = 10000000):
"""
make blast db
"""
db = fasta.rsplit('.', 1)[0]
type = check_type(fasta)
if type == 'nucl':
type = ['nhr', type]
else:
type = ['phr', type]
if os.path.exists('%s.%s' % (db, type[0])) is False \
and os.path.exists('%s.... | python | {
"resource": ""
} |
q55106 | usearchdb | train | def usearchdb(fasta, alignment = 'local', usearch_loc = 'usearch'):
"""
make usearch db
"""
if '.udb' in fasta:
print('# ... database found: %s' % (fasta), file=sys.stderr)
return fasta
type = check_type(fasta)
db = '%s.%s.udb' % (fasta.rsplit('.', 1)[0], type)
if os.path.exi... | python | {
"resource": ""
} |
q55107 | _pp | train | def _pp(dict_data):
"""Pretty print."""
for key, val in dict_data.items():
# pylint: disable=superfluous-parens
print('{0:<11}: {1}'.format(key, val)) | python | {
"resource": ""
} |
q55108 | print_licences | train | def print_licences(params, metadata):
"""Print licenses.
:param argparse.Namespace params: parameter
:param bootstrap_py.classifier.Classifiers metadata: package metadata
"""
if hasattr(params, 'licenses'):
if params.licenses:
_pp(metadata.licenses_desc())
sys.exit(0) | python | {
"resource": ""
} |
q55109 | check_repository_existence | train | def check_repository_existence(params):
"""Check repository existence.
:param argparse.Namespace params: parameters
"""
repodir = os.path.join(params.outdir, params.name)
if os.path.isdir(repodir):
raise Conflict(
'Package repository "{0}" has already exists.'.format(repodir)) | python | {
"resource": ""
} |
q55110 | generate_package | train | def generate_package(params):
"""Generate package repository.
:param argparse.Namespace params: parameters
"""
pkg_data = package.PackageData(params)
pkg_tree = package.PackageTree(pkg_data)
pkg_tree.generate()
pkg_tree.move()
VCS(os.path.join(pkg_tree.outdir, pkg_tree.name), pkg_tree.p... | python | {
"resource": ""
} |
q55111 | print_single | train | def print_single(line, rev):
"""
print single reads to stderr
"""
if rev is True:
seq = rc(['', line[9]])[1]
qual = line[10][::-1]
else:
seq = line[9]
qual = line[10]
fq = ['@%s' % line[0], seq, '+%s' % line[0], qual]
print('\n'.join(fq), file = sys.stderr) | python | {
"resource": ""
} |
q55112 | sam2fastq | train | def sam2fastq(sam, singles = False, force = False):
"""
convert sam to fastq
"""
L, R = None, None
for line in sam:
if line.startswith('@') is True:
continue
line = line.strip().split()
bit = [True if i == '1' else False \
for i in bin(int(line[1])... | python | {
"resource": ""
} |
q55113 | sort_sam | train | def sort_sam(sam, sort):
"""
sort sam file
"""
tempdir = '%s/' % (os.path.abspath(sam).rsplit('/', 1)[0])
if sort is True:
mapping = '%s.sorted.sam' % (sam.rsplit('.', 1)[0])
if sam != '-':
if os.path.exists(mapping) is False:
os.system("\
... | python | {
"resource": ""
} |
q55114 | sub_sam | train | def sub_sam(sam, percent, sort = True, sbuffer = False):
"""
randomly subset sam file
"""
mapping = sort_sam(sam, sort)
pool = [1 for i in range(0, percent)] + [0 for i in range(0, 100 - percent)]
c = cycle([1, 2])
for line in mapping:
line = line.strip().split()
if line[0].s... | python | {
"resource": ""
} |
q55115 | fq2fa | train | def fq2fa(fq):
"""
convert fq to fa
"""
c = cycle([1, 2, 3, 4])
for line in fq:
n = next(c)
if n == 1:
seq = ['>%s' % (line.strip().split('@', 1)[1])]
if n == 2:
seq.append(line.strip())
yield seq | python | {
"resource": ""
} |
q55116 | change_return_type | train | def change_return_type(f):
"""
Converts the returned value of wrapped function to the type of the
first arg or to the type specified by a kwarg key return_type's value.
"""
@wraps(f)
def wrapper(*args, **kwargs):
if kwargs.has_key('return_type'):
return_type = kwargs['return_... | python | {
"resource": ""
} |
q55117 | convert_args_to_sets | train | def convert_args_to_sets(f):
"""
Converts all args to 'set' type via self.setify function.
"""
@wraps(f)
def wrapper(*args, **kwargs):
args = (setify(x) for x in args)
return f(*args, **kwargs)
return wrapper | python | {
"resource": ""
} |
q55118 | KBBI._init_entri | train | def _init_entri(self, laman):
"""Membuat objek-objek entri dari laman yang diambil.
:param laman: Laman respons yang dikembalikan oleh KBBI daring.
:type laman: Response
"""
sup = BeautifulSoup(laman.text, 'html.parser')
estr = ''
for label in sup.find('hr').nex... | python | {
"resource": ""
} |
q55119 | Entri._init_kata_dasar | train | def _init_kata_dasar(self, dasar):
"""Memproses kata dasar yang ada dalam nama entri.
:param dasar: ResultSet untuk label HTML dengan class="rootword"
:type dasar: ResultSet
"""
for tiap in dasar:
kata = tiap.find('a')
dasar_no = kata.find('sup')
... | python | {
"resource": ""
} |
q55120 | Entri.serialisasi | train | def serialisasi(self):
"""Mengembalikan hasil serialisasi objek Entri ini.
:returns: Dictionary hasil serialisasi
:rtype: dict
"""
return {
"nama": self.nama,
"nomor": self.nomor,
"kata_dasar": self.kata_dasar,
"pelafalan": self.p... | python | {
"resource": ""
} |
q55121 | Entri._makna | train | def _makna(self):
"""Mengembalikan representasi string untuk semua makna entri ini.
:returns: String representasi makna-makna
:rtype: str
"""
if len(self.makna) > 1:
return '\n'.join(
str(i) + ". " + str(makna)
for i, makna in enumera... | python | {
"resource": ""
} |
q55122 | Entri._nama | train | def _nama(self):
"""Mengembalikan representasi string untuk nama entri ini.
:returns: String representasi nama entri
:rtype: str
"""
hasil = self.nama
if self.nomor:
hasil += " [{}]".format(self.nomor)
if self.kata_dasar:
hasil = " » ".jo... | python | {
"resource": ""
} |
q55123 | Entri._varian | train | def _varian(self, varian):
"""Mengembalikan representasi string untuk varian entri ini.
Dapat digunakan untuk "Varian" maupun "Bentuk tidak baku".
:param varian: List bentuk tidak baku atau varian
:type varian: list
:returns: String representasi varian atau bentuk tidak baku
... | python | {
"resource": ""
} |
q55124 | Makna._init_kelas | train | def _init_kelas(self, makna_label):
"""Memproses kelas kata yang ada dalam makna.
:param makna_label: BeautifulSoup untuk makna yang ingin diproses.
:type makna_label: BeautifulSoup
"""
kelas = makna_label.find(color='red')
lain = makna_label.find(color='darkgreen')
... | python | {
"resource": ""
} |
q55125 | Makna._init_contoh | train | def _init_contoh(self, makna_label):
"""Memproses contoh yang ada dalam makna.
:param makna_label: BeautifulSoup untuk makna yang ingin diproses.
:type makna_label: BeautifulSoup
"""
indeks = makna_label.text.find(': ')
if indeks != -1:
contoh = makna_label.... | python | {
"resource": ""
} |
q55126 | Makna.serialisasi | train | def serialisasi(self):
"""Mengembalikan hasil serialisasi objek Makna ini.
:returns: Dictionary hasil serialisasi
:rtype: dict
"""
return {
"kelas": self.kelas,
"submakna": self.submakna,
"info": self.info,
"contoh": self.contoh
... | python | {
"resource": ""
} |
q55127 | build_sphinx | train | def build_sphinx(pkg_data, projectdir):
"""Build sphinx documentation.
:rtype: int
:return: subprocess.call return code
:param `bootstrap_py.control.PackageData` pkg_data: package meta data
:param str projectdir: project root directory
"""
try:
version, _minor_version = pkg_data.ve... | python | {
"resource": ""
} |
q55128 | bowtiedb | train | def bowtiedb(fa, keepDB):
"""
make bowtie db
"""
btdir = '%s/bt2' % (os.getcwd())
# make directory for
if not os.path.exists(btdir):
os.mkdir(btdir)
btdb = '%s/%s' % (btdir, fa.rsplit('/', 1)[-1])
if keepDB is True:
if os.path.exists('%s.1.bt2' % (btdb)):
retu... | python | {
"resource": ""
} |
q55129 | bowtie | train | def bowtie(sam, btd, f, r, u, opt, no_shrink, threads):
"""
generate bowtie2 command
"""
bt2 = 'bowtie2 -x %s -p %s ' % (btd, threads)
if f is not False:
bt2 += '-1 %s -2 %s ' % (f, r)
if u is not False:
bt2 += '-U %s ' % (u)
bt2 += opt
if no_shrink is False:
if f... | python | {
"resource": ""
} |
q55130 | crossmap | train | def crossmap(fas, reads, options, no_shrink, keepDB, threads, cluster, nodes):
"""
map all read sets against all fasta files
"""
if cluster is True:
threads = '48'
btc = []
for fa in fas:
btd = bowtiedb(fa, keepDB)
F, R, U = reads
if F is not False:
if... | python | {
"resource": ""
} |
q55131 | BaseCluster.get_conn | train | def get_conn(self, *args, **kwargs):
"""
Returns a connection object from the router given ``args``.
Useful in cases where a connection cannot be automatically determined
during all steps of the process. An example of this would be
Redis pipelines.
"""
connection... | python | {
"resource": ""
} |
q55132 | Crc.__get_nondirect_init | train | def __get_nondirect_init(self, init):
"""
return the non-direct init if the direct algorithm has been selected.
"""
crc = init
for i in range(self.Width):
bit = crc & 0x01
if bit:
crc^= self.Poly
crc >>= 1
if bit:
... | python | {
"resource": ""
} |
q55133 | Crc.reflect | train | def reflect(self, data, width):
"""
reflect a data word, i.e. reverts the bit order.
"""
x = data & 0x01
for i in range(width - 1):
data >>= 1
x = (x << 1) | (data & 0x01)
return x | python | {
"resource": ""
} |
q55134 | Crc.bit_by_bit | train | def bit_by_bit(self, in_data):
"""
Classic simple and slow CRC implementation. This function iterates bit
by bit over the augmented input message and returns the calculated CRC
value at the end.
"""
# If the input data is a string, convert to bytes.
if isinstance... | python | {
"resource": ""
} |
q55135 | Crc.gen_table | train | def gen_table(self):
"""
This function generates the CRC table used for the table_driven CRC
algorithm. The Python version cannot handle tables of an index width
other than 8. See the generated C code for tables with different sizes
instead.
"""
table_length = 1... | python | {
"resource": ""
} |
q55136 | Crc.table_driven | train | def table_driven(self, in_data):
"""
The Standard table_driven CRC algorithm.
"""
# If the input data is a string, convert to bytes.
if isinstance(in_data, str):
in_data = [ord(c) for c in in_data]
tbl = self.gen_table()
register = self.DirectInit <<... | python | {
"resource": ""
} |
q55137 | parse_masked | train | def parse_masked(seq, min_len):
"""
parse masked sequence into non-masked and masked regions
"""
nm, masked = [], [[]]
prev = None
for base in seq[1]:
if base.isupper():
nm.append(base)
if masked != [[]] and len(masked[-1]) < min_len:
nm.extend(mas... | python | {
"resource": ""
} |
q55138 | strip_masked | train | def strip_masked(fasta, min_len, print_masked):
"""
remove masked regions from fasta file as long as
they are longer than min_len
"""
for seq in parse_fasta(fasta):
nm, masked = parse_masked(seq, min_len)
nm = ['%s removed_masked >=%s' % (seq[0], min_len), ''.join(nm)]
yield ... | python | {
"resource": ""
} |
q55139 | get_relative_abundance | train | def get_relative_abundance(biomfile):
"""
Return arcsine transformed relative abundance from a BIOM format file.
:type biomfile: BIOM format file
:param biomfile: BIOM format file used to obtain relative abundances for each OTU in
a SampleID, which are used as node sizes in network... | python | {
"resource": ""
} |
q55140 | find_otu | train | def find_otu(otuid, tree):
"""
Find an OTU ID in a Newick-format tree.
Return the starting position of the ID or None if not found.
"""
for m in re.finditer(otuid, tree):
before, after = tree[m.start()-1], tree[m.start()+len(otuid)]
if before in ["(", ",", ")"] and after in [":", ";"... | python | {
"resource": ""
} |
q55141 | newick_replace_otuids | train | def newick_replace_otuids(tree, biomf):
"""
Replace the OTU ids in the Newick phylogenetic tree format with truncated
OTU names
"""
for val, id_, md in biomf.iter(axis="observation"):
otu_loc = find_otu(id_, tree)
if otu_loc is not None:
tree = tree[:otu_loc] + \
... | python | {
"resource": ""
} |
q55142 | genome_info | train | def genome_info(genome, info):
"""
return genome info for choosing representative
if ggKbase table provided - choose rep based on SCGs and genome length
- priority for most SCGs - extra SCGs, then largest genome
otherwise, based on largest genome
"""
try:
scg = info['#SCG... | python | {
"resource": ""
} |
q55143 | print_clusters | train | def print_clusters(fastas, info, ANI):
"""
choose represenative genome and
print cluster information
*if ggKbase table is provided, use SCG info to choose best genome
"""
header = ['#cluster', 'num. genomes', 'rep.', 'genome', '#SCGs', '#SCG duplicates', \
'genome size (bp)', 'fragm... | python | {
"resource": ""
} |
q55144 | parse_ggKbase_tables | train | def parse_ggKbase_tables(tables, id_type):
"""
convert ggKbase genome info tables to dictionary
"""
g2info = {}
for table in tables:
for line in open(table):
line = line.strip().split('\t')
if line[0].startswith('name'):
header = line
h... | python | {
"resource": ""
} |
q55145 | parse_checkM_tables | train | def parse_checkM_tables(tables):
"""
convert checkM genome info tables to dictionary
"""
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] ... | python | {
"resource": ""
} |
q55146 | genome_lengths | train | def genome_lengths(fastas, info):
"""
get genome lengths
"""
if info is False:
info = {}
for genome in fastas:
name = genome.rsplit('.', 1)[0].rsplit('/', 1)[-1].rsplit('.contigs')[0]
if name in info:
continue
length = 0
fragments = 0
for s... | python | {
"resource": ""
} |
q55147 | BaseRouter.get_dbs | train | def get_dbs(self, attr, args, kwargs, **fkwargs):
"""
Returns a list of db keys to route the given call to.
:param attr: Name of attribute being called on the connection.
:param args: List of arguments being passed to ``attr``.
:param kwargs: Dictionary of keyword arguments bein... | python | {
"resource": ""
} |
q55148 | BaseRouter.setup_router | train | def setup_router(self, args, kwargs, **fkwargs):
"""
Call method to perform any setup
"""
self._ready = self._setup_router(args=args, kwargs=kwargs, **fkwargs)
return self._ready | python | {
"resource": ""
} |
q55149 | BaseRouter._route | train | def _route(self, attr, args, kwargs, **fkwargs):
"""
Perform routing and return db_nums
"""
return self.cluster.hosts.keys() | python | {
"resource": ""
} |
q55150 | RoundRobinRouter.check_down_connections | train | def check_down_connections(self):
"""
Iterates through all connections which were previously listed as unavailable
and marks any that have expired their retry_timeout as being up.
"""
now = time.time()
for db_num, marked_down_at in self._down_connections.items():
... | python | {
"resource": ""
} |
q55151 | RoundRobinRouter.flush_down_connections | train | def flush_down_connections(self):
"""
Marks all connections which were previously listed as unavailable as being up.
"""
self._get_db_attempts = 0
for db_num in self._down_connections.keys():
self.mark_connection_up(db_num) | python | {
"resource": ""
} |
q55152 | standby | train | def standby(df, resolution='24h', time_window=None):
"""
Compute standby power
Parameters
----------
df : pandas.DataFrame or pandas.Series
Electricity Power
resolution : str, default='d'
Resolution of the computation. Data will be resampled to this resolution (as mean) before ... | python | {
"resource": ""
} |
q55153 | share_of_standby | train | def share_of_standby(df, resolution='24h', time_window=None):
"""
Compute the share of the standby power in the total consumption.
Parameters
----------
df : pandas.DataFrame or pandas.Series
Power (typically electricity, can be anything)
resolution : str, default='d'
Resolution... | python | {
"resource": ""
} |
q55154 | count_peaks | train | def count_peaks(ts):
"""
Toggle counter for gas boilers
Counts the number of times the gas consumption increases with more than 3kW
Parameters
----------
ts: Pandas Series
Gas consumption in minute resolution
Returns
-------
int
"""
on_toggles = ts.diff() > 3000
... | python | {
"resource": ""
} |
q55155 | load_factor | train | def load_factor(ts, resolution=None, norm=None):
"""
Calculate the ratio of input vs. norm over a given interval.
Parameters
----------
ts : pandas.Series
timeseries
resolution : str, optional
interval over which to calculate the ratio
default: resolution of the input ti... | python | {
"resource": ""
} |
q55156 | top_hits | train | def top_hits(hits, num, column, reverse):
"""
get top hits after sorting by column number
"""
hits.sort(key = itemgetter(column), reverse = reverse)
for hit in hits[0:num]:
yield hit | python | {
"resource": ""
} |
q55157 | numBlast_sort | train | def numBlast_sort(blast, numHits, evalueT, bitT):
"""
parse b6 output with sorting
"""
header = ['#query', 'target', 'pident', 'alen', 'mismatch', 'gapopen',
'qstart', 'qend', 'tstart', 'tend', 'evalue', 'bitscore']
yield header
hmm = {h:[] for h in header}
for line in blast:
... | python | {
"resource": ""
} |
q55158 | numBlast | train | def numBlast(blast, numHits, evalueT = False, bitT = False, sort = False):
"""
parse b6 output
"""
if sort is True:
for hit in numBlast_sort(blast, numHits, evalueT, bitT):
yield hit
return
header = ['#query', 'target', 'pident', 'alen', 'mismatch', 'gapopen',
... | python | {
"resource": ""
} |
q55159 | numDomtblout | train | def numDomtblout(domtblout, numHits, evalueT, bitT, sort):
"""
parse hmm domain table output
this version is faster but does not work unless the table is sorted
"""
if sort is True:
for hit in numDomtblout_sort(domtblout, numHits, evalueT, bitT):
yield hit
return
head... | python | {
"resource": ""
} |
q55160 | stock2fa | train | def stock2fa(stock):
"""
convert stockholm to fasta
"""
seqs = {}
for line in stock:
if line.startswith('#') is False and line.startswith(' ') is False and len(line) > 3:
id, seq = line.strip().split()
id = id.rsplit('/', 1)[0]
id = re.split('[0-9]\|', id,... | python | {
"resource": ""
} |
q55161 | week_schedule | train | def week_schedule(index, on_time=None, off_time=None, off_days=None):
""" Return boolean time series following given week schedule.
Parameters
----------
index : pandas.DatetimeIndex
Datetime index
on_time : str or datetime.time
Daily opening time. Default: '09:00'
off_time : st... | python | {
"resource": ""
} |
q55162 | carpet | train | def carpet(timeseries, **kwargs):
"""
Draw a carpet plot of a pandas timeseries.
The carpet plot reads like a letter. Every day one line is added to the
bottom of the figure, minute for minute moving from left (morning) to right
(evening).
The color denotes the level of consumption and is scale... | python | {
"resource": ""
} |
q55163 | calc_pident_ignore_gaps | train | def calc_pident_ignore_gaps(a, b):
"""
calculate percent identity
"""
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
t... | python | {
"resource": ""
} |
q55164 | remove_gaps | train | def remove_gaps(A, B):
"""
skip column if either is a gap
"""
a_seq, b_seq = [], []
for a, b in zip(list(A), list(B)):
if a == '-' or a == '.' or b == '-' or b == '.':
continue
a_seq.append(a)
b_seq.append(b)
return ''.join(a_seq), ''.join(b_seq) | python | {
"resource": ""
} |
q55165 | compare_seqs | train | def compare_seqs(seqs):
"""
compare pairs of sequences
"""
A, B, ignore_gaps = seqs
a, b = A[1], B[1] # actual sequences
if len(a) != len(b):
print('# reads are not the same length', file=sys.stderr)
exit()
if ignore_gaps is True:
pident = calc_pident_ignore_gaps(a, b... | python | {
"resource": ""
} |
q55166 | compare_seqs_leven | train | def compare_seqs_leven(seqs):
"""
calculate Levenshtein ratio of sequences
"""
A, B, ignore_gaps = seqs
a, b = remove_gaps(A[1], B[1]) # actual sequences
if len(a) != len(b):
print('# reads are not the same length', file=sys.stderr)
exit()
pident = lr(a, b) * 100
return A... | python | {
"resource": ""
} |
q55167 | pairwise_compare | train | def pairwise_compare(afa, leven, threads, print_list, ignore_gaps):
"""
make pairwise sequence comparisons between aligned sequences
"""
# load sequences into dictionary
seqs = {seq[0]: seq for seq in nr_fasta([afa], append_index = True)}
num_seqs = len(seqs)
# define all pairs
pairs = (... | python | {
"resource": ""
} |
q55168 | print_pairwise | train | def print_pairwise(pw, median = False):
"""
print matrix of pidents to stdout
"""
names = sorted(set([i for i in pw]))
if len(names) != 0:
if '>' in names[0]:
yield ['#'] + [i.split('>')[1] for i in names if '>' in i]
else:
yield ['#'] + names
for a in... | python | {
"resource": ""
} |
q55169 | print_comps | train | def print_comps(comps):
"""
print stats for comparisons
"""
if comps == []:
print('n/a')
else:
print('# min: %s, max: %s, mean: %s' % \
(min(comps), max(comps), np.mean(comps))) | python | {
"resource": ""
} |
q55170 | compare_clades | train | def compare_clades(pw):
"""
print min. pident within each clade and then matrix of between-clade max.
"""
names = sorted(set([i for i in pw]))
for i in range(0, 4):
wi, bt = {}, {}
for a in names:
for b in pw[a]:
if ';' not in a or ';' not in b:
... | python | {
"resource": ""
} |
q55171 | matrix2dictionary | train | def matrix2dictionary(matrix):
"""
convert matrix to dictionary of comparisons
"""
pw = {}
for line in matrix:
line = line.strip().split('\t')
if line[0].startswith('#'):
names = line[1:]
continue
a = line[0]
for i, pident in enumerate(line[1:]... | python | {
"resource": ""
} |
q55172 | setoption | train | def setoption(parser, metadata=None):
"""Set argument parser option."""
parser.add_argument('-v', action='version',
version=__version__)
subparsers = parser.add_subparsers(help='sub commands help')
create_cmd = subparsers.add_parser('create')
create_cmd.add_argument('name',
... | python | {
"resource": ""
} |
q55173 | parse_options | train | def parse_options(metadata):
"""Parse argument options."""
parser = argparse.ArgumentParser(description='%(prog)s usage:',
prog=__prog__)
setoption(parser, metadata=metadata)
return parser | python | {
"resource": ""
} |
q55174 | main | train | def main():
"""Execute main processes."""
try:
pkg_version = Update()
if pkg_version.updatable():
pkg_version.show_message()
metadata = control.retreive_metadata()
parser = parse_options(metadata)
argvs = sys.argv
if len(argvs) <= 1:
parser... | python | {
"resource": ""
} |
q55175 | PackageData._check_or_set_default_params | train | def _check_or_set_default_params(self):
"""Check key and set default vaule when it does not exists."""
if not hasattr(self, 'date'):
self._set_param('date', datetime.utcnow().strftime('%Y-%m-%d'))
if not hasattr(self, 'version'):
self._set_param('version', self.default_ve... | python | {
"resource": ""
} |
q55176 | PackageTree.move | train | def move(self):
"""Move directory from working directory to output directory."""
if not os.path.isdir(self.outdir):
os.makedirs(self.outdir)
shutil.move(self.tmpdir, os.path.join(self.outdir, self.name)) | python | {
"resource": ""
} |
q55177 | PackageTree.vcs_init | train | def vcs_init(self):
"""Initialize VCS repository."""
VCS(os.path.join(self.outdir, self.name), self.pkg_data) | python | {
"resource": ""
} |
q55178 | find_steam_location | train | def find_steam_location():
"""
Finds the location of the current Steam installation on Windows machines.
Returns None for any non-Windows machines, or for Windows machines where
Steam is not installed.
"""
if registry is None:
return None
key = registry.CreateKey(registry.HKEY_CURRENT_USER,"Software\... | python | {
"resource": ""
} |
q55179 | plot_PCoA | train | def plot_PCoA(cat_data, otu_name, unifrac, names, colors, xr, yr, outDir,
save_as, plot_style):
"""
Plot PCoA principal coordinates scaled by the relative abundances of
otu_name.
"""
fig = plt.figure(figsize=(14, 8))
ax = fig.add_subplot(111)
for i, cat in enumerate(cat_data):... | python | {
"resource": ""
} |
q55180 | split_by_category | train | def split_by_category(biom_cols, mapping, category_id):
"""
Split up the column data in a biom table by mapping category value.
"""
columns = defaultdict(list)
for i, col in enumerate(biom_cols):
columns[mapping[col['id']][category_id]].append((i, col))
return columns | python | {
"resource": ""
} |
q55181 | print_line | train | def print_line(l):
"""
print line if starts with ...
"""
print_lines = ['# STOCKHOLM', '#=GF', '#=GS', ' ']
if len(l.split()) == 0:
return True
for start in print_lines:
if l.startswith(start):
return True
return False | python | {
"resource": ""
} |
q55182 | stock2one | train | def stock2one(stock):
"""
convert stockholm to single line format
"""
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... | python | {
"resource": ""
} |
q55183 | math_func | train | def math_func(f):
"""
Statics the methods. wut.
"""
@wraps(f)
def wrapper(*args, **kwargs):
if len(args) > 0:
return_type = type(args[0])
if kwargs.has_key('return_type'):
return_type = kwargs['return_type']
kwargs.pop('return_type')
re... | python | {
"resource": ""
} |
q55184 | dump_stats | train | def dump_stats(myStats):
"""
Show stats when pings are done
"""
print("\n----%s PYTHON PING Statistics----" % (myStats.thisIP))
if myStats.pktsSent > 0:
myStats.fracLoss = (myStats.pktsSent - myStats.pktsRcvd) \
/ myStats.pktsSent
print(("%d packets transmitted, %d pack... | python | {
"resource": ""
} |
q55185 | Update.updatable | train | def updatable(self):
"""bootstrap-py package updatable?."""
if self.latest_version > self.current_version:
updatable_version = self.latest_version
else:
updatable_version = False
return updatable_version | python | {
"resource": ""
} |
q55186 | Update.show_message | train | def show_message(self):
"""Show message updatable."""
print(
'current version: {current_version}\n'
'latest version : {latest_version}'.format(
current_version=self.current_version,
latest_version=self.latest_version)) | python | {
"resource": ""
} |
q55187 | condense_otus | train | def condense_otus(otuF, nuniqueF):
"""
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 nu... | python | {
"resource": ""
} |
q55188 | rna_bases | train | def rna_bases(rna_cov, scaffold, bases, line):
"""
determine if read overlaps with rna, if so count bases
"""
start = int(line[3])
stop = start + bases - 1
if scaffold not in rna_cov:
return rna_cov
for pos in rna_cov[scaffold][2]:
ol = get_overlap([start, stop], pos)
... | python | {
"resource": ""
} |
q55189 | parse_s2bins | train | def parse_s2bins(s2bins):
"""
parse ggKbase scaffold-to-bin mapping
- scaffolds-to-bins and bins-to-scaffolds
"""
s2b = {}
b2s = {}
for line in s2bins:
line = line.strip().split()
s, b = line[0], line[1]
if 'UNK' in b:
continue
if len(line) > 2... | python | {
"resource": ""
} |
q55190 | filter_missing_rna | train | def filter_missing_rna(s2bins, bins2s, rna_cov):
"""
remove any bins that don't have 16S
"""
for bin, scaffolds in list(bins2s.items()):
c = 0
for s in scaffolds:
if s in rna_cov:
c += 1
if c == 0:
del bins2s[bin]
for scaffold, bin in l... | python | {
"resource": ""
} |
q55191 | calc_bin_cov | train | def calc_bin_cov(scaffolds, cov):
"""
calculate bin coverage
"""
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)) | python | {
"resource": ""
} |
q55192 | TranslationFormSet.clean | train | def clean(self):
"""
Make sure there is at least a translation has been filled in. If a
default language has been specified, make sure that it exists amongst
translations.
"""
# First make sure the super's clean method is called upon.
super(TranslationFormSet, se... | python | {
"resource": ""
} |
q55193 | TranslationFormSet._get_default_language | train | def _get_default_language(self):
"""
If a default language has been set, and is still available in
`self.available_languages`, return it and remove it from the list.
If not, simply pop the first available language.
"""
assert hasattr(self, 'available_languages'), \
... | python | {
"resource": ""
} |
q55194 | TranslationFormSet._construct_form | train | def _construct_form(self, i, **kwargs):
"""
Construct the form, overriding the initial value for `language_code`.
"""
if not settings.HIDE_LANGUAGE:
self._construct_available_languages()
form = super(TranslationFormSet, self)._construct_form(i, **kwargs)
if ... | python | {
"resource": ""
} |
q55195 | fq_merge | train | def fq_merge(R1, R2):
"""
merge separate fastq files
"""
c = itertools.cycle([1, 2, 3, 4])
for r1, r2 in zip(R1, R2):
n = next(c)
if n == 1:
pair = [[], []]
pair[0].append(r1.strip())
pair[1].append(r2.strip())
if n == 4:
yield pair | python | {
"resource": ""
} |
q55196 | Ketama._build_circle | train | def _build_circle(self):
"""
Creates hash ring.
"""
total_weight = 0
for node in self._nodes:
total_weight += self._weights.get(node, 1)
for node in self._nodes:
weight = self._weights.get(node, 1)
ks = math.floor((40 * len(self._... | python | {
"resource": ""
} |
q55197 | Ketama._gen_key | train | def _gen_key(self, key):
"""
Return long integer for a given key, that represent it place on
the hash ring.
"""
b_key = self._md5_digest(key)
return self._hashi(b_key, lambda x: x) | python | {
"resource": ""
} |
q55198 | has_custom_image | train | def has_custom_image(user_context, app_id):
"""Returns True if there exists a custom image for app_id."""
possible_paths = _valid_custom_image_paths(user_context, app_id)
return any(map(os.path.exists, possible_paths)) | python | {
"resource": ""
} |
q55199 | get_custom_image | train | def get_custom_image(user_context, app_id):
"""Returns the custom image associated with a given app. If there are
multiple candidate images on disk, one is chosen arbitrarily."""
possible_paths = _valid_custom_image_paths(user_context, app_id)
existing_images = filter(os.path.exists, possible_paths)
if len(ex... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.