_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q55200 | set_custom_image | train | def set_custom_image(user_context, app_id, image_path):
"""Sets the custom image for `app_id` to be the image located at
`image_path`. If there already exists a custom image for `app_id` it will
be deleted. Returns True is setting the image was successful."""
if image_path is None:
return False
if not os... | python | {
"resource": ""
} |
q55201 | Profile.from_file | train | def from_file(cls, fname, form=None):
"""
Read an orthography profile from a metadata file or a default tab-separated profile file.
"""
try:
tg = TableGroup.from_file(fname)
opfname = None
except JSONDecodeError:
tg = TableGroup.fromvalue(cls.M... | python | {
"resource": ""
} |
q55202 | Profile.from_text | train | def from_text(cls, text, mapping='mapping'):
"""
Create a Profile instance from the Unicode graphemes found in `text`.
Parameters
----------
text
mapping
Returns
-------
A Profile instance.
"""
graphemes = Counter(grapheme_patter... | python | {
"resource": ""
} |
q55203 | split_fasta | train | def split_fasta(f, id2f):
"""
split fasta file into separate fasta files based on list of scaffolds
that belong to each separate file
"""
opened = {}
for seq in parse_fasta(f):
id = seq[0].split('>')[1].split()[0]
if id not in id2f:
continue
fasta = id2f[id]
... | python | {
"resource": ""
} |
q55204 | Steam._is_user_directory | train | def _is_user_directory(self, pathname):
"""Check whether `pathname` is a valid user data directory
This method is meant to be called on the contents of the userdata dir.
As such, it will return True when `pathname` refers to a directory name
that can be interpreted as a users' userID.
"""... | python | {
"resource": ""
} |
q55205 | Steam.local_users | train | def local_users(self):
"""Returns an array of user ids for users on the filesystem"""
# Any users on the machine will have an entry inside of the userdata
# folder. As such, the easiest way to find a list of all users on the
# machine is to just list the folders inside userdata
u... | python | {
"resource": ""
} |
q55206 | _calculate_degree_days | train | def _calculate_degree_days(temperature_equivalent, base_temperature, cooling=False):
"""
Calculates degree days, starting with a series of temperature equivalent values
Parameters
----------
temperature_equivalent : Pandas Series
base_temperature : float
cooling : bool
Set True if y... | python | {
"resource": ""
} |
q55207 | Classifiers.status | train | def status(self):
"""Development status."""
return {self._acronym_status(l): l for l in self.resp_text.split('\n')
if l.startswith(self.prefix_status)} | python | {
"resource": ""
} |
q55208 | Classifiers.licenses | train | def licenses(self):
"""OSI Approved license."""
return {self._acronym_lic(l): l for l in self.resp_text.split('\n')
if l.startswith(self.prefix_lic)} | python | {
"resource": ""
} |
q55209 | Classifiers.licenses_desc | train | def licenses_desc(self):
"""Remove prefix."""
return {self._acronym_lic(l): l.split(self.prefix_lic)[1]
for l in self.resp_text.split('\n')
if l.startswith(self.prefix_lic)} | python | {
"resource": ""
} |
q55210 | Classifiers._acronym_lic | train | def _acronym_lic(self, license_statement):
"""Convert license acronym."""
pat = re.compile(r'\(([\w+\W?\s?]+)\)')
if pat.search(license_statement):
lic = pat.search(license_statement).group(1)
if lic.startswith('CNRI'):
acronym_licence = lic[:4]
... | python | {
"resource": ""
} |
q55211 | calcMD5 | train | def calcMD5(path):
"""
calc MD5 based on path
"""
# check that file exists
if os.path.exists(path) is False:
yield False
else:
command = ['md5sum', path]
p = Popen(command, stdout = PIPE)
for line in p.communicate()[0].splitlines():
yield line.decode('... | python | {
"resource": ""
} |
q55212 | wget | train | def wget(ftp, f = False, exclude = False, name = False, md5 = False, tries = 10):
"""
download files with wget
"""
# file name
if f is False:
f = ftp.rsplit('/', 1)[-1]
# downloaded file if it does not already exist
# check md5s on server (optional)
t = 0
while md5check(f, ft... | python | {
"resource": ""
} |
q55213 | check | train | def check(line, queries):
"""
check that at least one of
queries is in list, l
"""
line = line.strip()
spLine = line.replace('.', ' ').split()
matches = set(spLine).intersection(queries)
if len(matches) > 0:
return matches, line.split('\t')
return matches, False | python | {
"resource": ""
} |
q55214 | entrez | train | def entrez(db, acc):
"""
search entrez using specified database
and accession
"""
c1 = ['esearch', '-db', db, '-query', acc]
c2 = ['efetch', '-db', 'BioSample', '-format', 'docsum']
p1 = Popen(c1, stdout = PIPE, stderr = PIPE)
p2 = Popen(c2, stdin = p1.stdout, stdout = PIPE, stderr = PIP... | python | {
"resource": ""
} |
q55215 | searchAccession | train | def searchAccession(acc):
"""
attempt to use NCBI Entrez to get
BioSample ID
"""
# try genbank file
# genome database
out, error = entrez('genome', acc)
for line in out.splitlines():
line = line.decode('ascii').strip()
if 'Assembly_Accession' in line or 'BioSample' in lin... | python | {
"resource": ""
} |
q55216 | getFTPs | train | def getFTPs(accessions, ftp, search, exclude, convert = False, threads = 1, attempt = 1,
max_attempts = 2):
"""
download genome info from NCBI
"""
info = wget(ftp)[0]
allMatches = []
for genome in open(info, encoding = 'utf8'):
genome = str(genome)
matches, genomeInfo... | python | {
"resource": ""
} |
q55217 | download | train | def download(args):
"""
download genomes from NCBI
"""
accessions, infoFTP = set(args['g']), args['i']
search, exclude = args['s'], args['e']
FTPs = getFTPs(accessions, infoFTP, search, exclude, threads = args['t'],
convert = args['convert'])
if args['test'] is True:
for ... | python | {
"resource": ""
} |
q55218 | fix_fasta | train | def fix_fasta(fasta):
"""
remove pesky characters from fasta file header
"""
for seq in parse_fasta(fasta):
seq[0] = remove_char(seq[0])
if len(seq[1]) > 0:
yield seq | python | {
"resource": ""
} |
q55219 | _calc_frames | train | def _calc_frames(stats):
"""
Compute a DataFrame summary of a Stats object.
"""
timings = []
callers = []
for key, values in iteritems(stats.stats):
timings.append(
pd.Series(
key + values[:-1],
index=timing_colnames,
)
)
... | python | {
"resource": ""
} |
q55220 | unmapped | train | def unmapped(sam, mates):
"""
get unmapped reads
"""
for read in sam:
if read.startswith('@') is True:
continue
read = read.strip().split()
if read[2] == '*' and read[6] == '*':
yield read
elif mates is True:
if read[2] == '*' or re... | python | {
"resource": ""
} |
q55221 | parallel | train | def parallel(processes, threads):
"""
execute jobs in processes using N threads
"""
pool = multithread(threads)
pool.map(run_process, processes)
pool.close()
pool.join() | python | {
"resource": ""
} |
q55222 | define_log_renderer | train | def define_log_renderer(fmt, fpath, quiet):
"""
the final log processor that structlog requires to render.
"""
# it must accept a logger, method_name and event_dict (just like processors)
# but must return the rendered string, not a dictionary.
# TODO tty logic
if fmt:
return struct... | python | {
"resource": ""
} |
q55223 | _structlog_default_keys_processor | train | def _structlog_default_keys_processor(logger_class, log_method, event):
''' Add unique id, type and hostname '''
global HOSTNAME
if 'id' not in event:
event['id'] = '%s_%s' % (
datetime.utcnow().strftime('%Y%m%dT%H%M%S'),
uuid.uuid1().hex
)
if 'type' not in even... | python | {
"resource": ""
} |
q55224 | define_log_processors | train | def define_log_processors():
"""
log processors that structlog executes before final rendering
"""
# these processors should accept logger, method_name and event_dict
# and return a new dictionary which will be passed as event_dict to the next one.
return [
structlog.processors.TimeStamp... | python | {
"resource": ""
} |
q55225 | _configure_logger | train | def _configure_logger(fmt, quiet, level, fpath,
pre_hooks, post_hooks, metric_grouping_interval):
"""
configures a logger when required write to stderr or a file
"""
# NOTE not thread safe. Multiple BaseScripts cannot be instantiated concurrently.
level = getattr(logging, level.upper())
gl... | python | {
"resource": ""
} |
q55226 | BoundLevelLogger._add_base_info | train | def _add_base_info(self, event_dict):
"""
Instead of using a processor, adding basic information like caller, filename etc
here.
"""
f = sys._getframe()
level_method_frame = f.f_back
caller_frame = level_method_frame.f_back
return event_dict | python | {
"resource": ""
} |
q55227 | BoundLevelLogger._proxy_to_logger | train | def _proxy_to_logger(self, method_name, event, *event_args,
**event_kw):
"""
Propagate a method call to the wrapped logger.
This is the same as the superclass implementation, except that
it also preserves positional arguments in the `event_dict` so
that ... | python | {
"resource": ""
} |
q55228 | translate | train | def translate(rect, x, y, width=1):
"""
Given four points of a rectangle, translate the
rectangle to the specified x and y coordinates and,
optionally, change the width.
:type rect: list of tuples
:param rect: Four points describing a rectangle.
:type x: float
:param x: The amount to sh... | python | {
"resource": ""
} |
q55229 | remove_bad | train | def remove_bad(string):
"""
remove problem characters from string
"""
remove = [':', ',', '(', ')', ' ', '|', ';', '\'']
for c in remove:
string = string.replace(c, '_')
return string | python | {
"resource": ""
} |
q55230 | get_ids | train | def get_ids(a):
"""
make copy of sequences with short identifier
"""
a_id = '%s.id.fa' % (a.rsplit('.', 1)[0])
a_id_lookup = '%s.id.lookup' % (a.rsplit('.', 1)[0])
if check(a_id) is True:
return a_id, a_id_lookup
a_id_f = open(a_id, 'w')
a_id_lookup_f = open(a_id_lookup, 'w')
... | python | {
"resource": ""
} |
q55231 | convert2phylip | train | def convert2phylip(convert):
"""
convert fasta to phylip because RAxML is ridiculous
"""
out = '%s.phy' % (convert.rsplit('.', 1)[0])
if check(out) is False:
convert = open(convert, 'rU')
out_f = open(out, 'w')
alignments = AlignIO.parse(convert, "fasta")
AlignIO.writ... | python | {
"resource": ""
} |
q55232 | run_iqtree | train | def run_iqtree(phy, model, threads, cluster, node):
"""
run IQ-Tree
"""
# set ppn based on threads
if threads > 24:
ppn = 24
else:
ppn = threads
tree = '%s.treefile' % (phy)
if check(tree) is False:
if model is False:
model = 'TEST'
dir = os.ge... | python | {
"resource": ""
} |
q55233 | fix_tree | train | def fix_tree(tree, a_id_lookup, out):
"""
get the names for sequences in the raxml tree
"""
if check(out) is False and check(tree) is True:
tree = open(tree).read()
for line in open(a_id_lookup):
id, name, header = line.strip().split('\t')
tree = tree.replace(id+'... | python | {
"resource": ""
} |
q55234 | create_cluster | train | def create_cluster(settings):
"""
Creates a new Nydus cluster from the given settings.
:param settings: Dictionary of the cluster settings.
:returns: Configured instance of ``nydus.db.base.Cluster``.
>>> redis = create_cluster({
>>> 'backend': 'nydus.db.backends.redis.Redis',
>>> '... | python | {
"resource": ""
} |
q55235 | MultilingualModel._get_translation | train | def _get_translation(self, field, code):
"""
Gets the translation of a specific field for a specific language code.
This raises ObjectDoesNotExist if the lookup was unsuccesful. As of
today, this stuff is cached. As the cache is rather aggressive it
might cause rather strange ef... | python | {
"resource": ""
} |
q55236 | MultilingualModel.unicode_wrapper | train | def unicode_wrapper(self, property, default=ugettext('Untitled')):
"""
Wrapper to allow for easy unicode representation of an object by
the specified property. If this wrapper is not able to find the
right translation of the specified property, it will return the
default value in... | python | {
"resource": ""
} |
q55237 | strip_inserts | train | def strip_inserts(fasta):
"""
remove insertion columns from aligned fasta file
"""
for seq in parse_fasta(fasta):
seq[1] = ''.join([b for b in seq[1] if b == '-' or b.isupper()])
yield seq | python | {
"resource": ""
} |
q55238 | Tokenizer.transform | train | def transform(self, word, column=Profile.GRAPHEME_COL, error=errors.replace):
"""
Transform a string's graphemes into the mappings given in a different column
in the orthography profile.
Parameters
----------
word : str
The input string to be tokenized.
... | python | {
"resource": ""
} |
q55239 | Tokenizer.rules | train | def rules(self, word):
"""
Function to tokenize input string and return output of str with ortho rules
applied.
Parameters
----------
word : str
The input string to be tokenized.
Returns
-------
result : str
Result of the ... | python | {
"resource": ""
} |
q55240 | Tokenizer.combine_modifiers | train | def combine_modifiers(self, graphemes):
"""
Given a string that is space-delimited on Unicode grapheme clusters,
group Unicode modifier letters with their preceding base characters,
deal with tie bars, etc.
Parameters
----------
string : str
A Unicode... | python | {
"resource": ""
} |
q55241 | parse_catalytic | train | def parse_catalytic(insertion, gff):
"""
parse catalytic RNAs to gff format
"""
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 ... | python | {
"resource": ""
} |
q55242 | parse_orf | train | def parse_orf(insertion, gff):
"""
parse ORF to gff format
"""
offset = insertion['offset']
if type(insertion['orf']) is not str:
return gff
for orf in parse_fasta(insertion['orf'].split('|')):
ID = orf[0].split('>')[1].split()[0]
Start, End, strand = [int(i) for i in orf... | python | {
"resource": ""
} |
q55243 | parse_insertion | train | def parse_insertion(insertion, gff):
"""
parse insertion to gff format
"""
offset = insertion['offset']
for ins in parse_fasta(insertion['insertion sequence'].split('|')):
strand = insertion['strand']
ID = ins[0].split('>')[1].split()[0]
Start, End = [int(i) for i in ins[0].s... | python | {
"resource": ""
} |
q55244 | parse_rRNA | train | def parse_rRNA(insertion, seq, gff):
"""
parse rRNA to gff format
"""
offset = insertion['offset']
strand = insertion['strand']
for rRNA in parse_masked(seq, 0)[0]:
rRNA = ''.join(rRNA)
Start = seq[1].find(rRNA) + 1
End = Start + len(rRNA) - 1
if strand == '-':
... | python | {
"resource": ""
} |
q55245 | iTable2GFF | train | def iTable2GFF(iTable, fa, contig = False):
"""
convert iTable to gff file
"""
columns = ['#seqname', 'source', 'feature', 'start', 'end', 'score', 'strand', 'frame', 'attribute']
gff = {c:[] for c in columns}
for insertion in iTable.iterrows():
insertion = insertion[1]
if insert... | python | {
"resource": ""
} |
q55246 | summarize_taxa | train | def summarize_taxa(biom):
"""
Given an abundance table, group the counts by every
taxonomic level.
"""
tamtcounts = defaultdict(int)
tot_seqs = 0.0
for row, col, amt in biom['data']:
tot_seqs += amt
rtax = biom['rows'][row]['metadata']['taxonomy']
for i, t in enumera... | python | {
"resource": ""
} |
q55247 | Game.custom_image | train | def custom_image(self, user):
"""Returns the path to the custom image set for this game, or None if
no image is set"""
for ext in self.valid_custom_image_extensions():
image_location = self._custom_image_path(user, ext)
if os.path.isfile(image_location):
r... | python | {
"resource": ""
} |
q55248 | Game.set_image | train | def set_image(self, user, image_path):
"""Sets a custom image for the game. `image_path` should refer to
an image file on disk"""
_, ext = os.path.splitext(image_path)
shutil.copy(image_path, self._custom_image_path(user, ext)) | python | {
"resource": ""
} |
q55249 | sam_list | train | def sam_list(sam):
"""
get a list of mapped reads
"""
list = []
for file in sam:
for line in file:
if line.startswith('@') is False:
line = line.strip().split()
id, map = line[0], int(line[1])
if map != 4 and map != 8:
list.append(id)
return set(list) | python | {
"resource": ""
} |
q55250 | sam_list_paired | train | def sam_list_paired(sam):
"""
get a list of mapped reads
require that both pairs are mapped in the sam file in order to remove the reads
"""
list = []
pair = ['1', '2']
prev = ''
for file in sam:
for line in file:
if line.startswith('@') is False:
line = line.strip().split()
id, map = line[0], int(... | python | {
"resource": ""
} |
q55251 | filter_paired | train | def filter_paired(list):
"""
require that both pairs are mapped in the sam file in order to remove the reads
"""
pairs = {}
filtered = []
for id in list:
read = id.rsplit('/')[0]
if read not in pairs:
pairs[read] = []
pairs[read].append(id)
for read in pairs:
ids = pairs[read]
if len(ids) == 2:
f... | python | {
"resource": ""
} |
q55252 | sam2fastq | train | def sam2fastq(line):
"""
print fastq from sam
"""
fastq = []
fastq.append('@%s' % line[0])
fastq.append(line[9])
fastq.append('+%s' % line[0])
fastq.append(line[10])
return fastq | python | {
"resource": ""
} |
q55253 | check_mismatches | train | def check_mismatches(read, pair, mismatches, mm_option, req_map):
"""
- check to see if the read maps with <= threshold number of mismatches
- mm_option = 'one' or 'both' depending on whether or not one or both reads
in a pair need to pass the mismatch threshold
- pair can be False if read does n... | python | {
"resource": ""
} |
q55254 | check_region | train | def check_region(read, pair, region):
"""
determine whether or not reads map to specific region of scaffold
"""
if region is False:
return True
for mapping in read, pair:
if mapping is False:
continue
start, length = int(mapping[3]), len(mapping[9])
r = [s... | python | {
"resource": ""
} |
q55255 | get_steam | train | def get_steam():
"""
Returns a Steam object representing the current Steam installation on the
users computer. If the user doesn't have Steam installed, returns None.
"""
# Helper function which checks if the potential userdata directory exists
# and returns a new Steam instance with that userdata directory... | python | {
"resource": ""
} |
q55256 | zero_to_one | train | def zero_to_one(table, option):
"""
normalize from zero to one for row or table
"""
if option == 'table':
m = min(min(table))
ma = max(max(table))
t = []
for row in table:
t_row = []
if option != 'table':
m, ma = min(row), max(row)
for i in row... | python | {
"resource": ""
} |
q55257 | pertotal | train | def pertotal(table, option):
"""
calculate percent of total
"""
if option == 'table':
total = sum([i for line in table for i in line])
t = []
for row in table:
t_row = []
if option != 'table':
total = sum(row)
for i in row:
if total == 0:
... | python | {
"resource": ""
} |
q55258 | scale | train | def scale(table):
"""
scale table based on the column with the largest sum
"""
t = []
columns = [[] for i in table[0]]
for row in table:
for i, v in enumerate(row):
columns[i].append(v)
sums = [float(sum(i)) for i in columns]
scale_to = float(max(sums))
scale_fact... | python | {
"resource": ""
} |
q55259 | norm | train | def norm(table):
"""
fit to normal distribution
"""
print('# norm dist is broken', file=sys.stderr)
exit()
from matplotlib.pyplot import hist as hist
t = []
for i in table:
t.append(np.ndarray.tolist(hist(i, bins = len(i), normed = True)[0]))
return t | python | {
"resource": ""
} |
q55260 | log_trans | train | def log_trans(table):
"""
log transform each value in table
"""
t = []
all = [item for sublist in table for item in sublist]
if min(all) == 0:
scale = min([i for i in all if i != 0]) * 10e-10
else:
scale = 0
for i in table:
t.append(np.ndarray.tolist(np.log10([j +... | python | {
"resource": ""
} |
q55261 | box_cox | train | def box_cox(table):
"""
box-cox transform table
"""
from scipy.stats import boxcox as bc
t = []
for i in table:
if min(i) == 0:
scale = min([j for j in i if j != 0]) * 10e-10
else:
scale = 0
t.append(np.ndarray.tolist(bc(np.array([j + scale for j i... | python | {
"resource": ""
} |
q55262 | inh | train | def inh(table):
"""
inverse hyperbolic sine transformation
"""
t = []
for i in table:
t.append(np.ndarray.tolist(np.arcsinh(i)))
return t | python | {
"resource": ""
} |
q55263 | diri | train | def diri(table):
"""
from SparCC - "randomly draw from the corresponding posterior
Dirichlet distribution with a uniform prior"
"""
t = []
for i in table:
a = [j + 1 for j in i]
t.append(np.ndarray.tolist(np.random.mtrand.dirichlet(a)))
return t | python | {
"resource": ""
} |
q55264 | generate_barcodes | train | def generate_barcodes(nIds, codeLen=12):
"""
Given a list of sample IDs generate unique n-base barcodes for each.
Note that only 4^n unique barcodes are possible.
"""
def next_code(b, c, i):
return c[:i] + b + (c[i+1:] if i < -1 else '')
def rand_base():
return random.choice(['A... | python | {
"resource": ""
} |
q55265 | scrobble_data_dir | train | def scrobble_data_dir(dataDir, sampleMap, outF, qualF=None, idopt=None,
utf16=False):
"""
Given a sample ID and a mapping, modify a Sanger FASTA file
to include the barcode and 'primer' in the sequence data
and change the description line as needed.
"""
seqcount = 0
out... | python | {
"resource": ""
} |
q55266 | handle_program_options | train | def handle_program_options():
"""
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
"""
parser = argparse.ArgumentParser(description="Convert Sanger-sequencing \
... | python | {
"resource": ""
} |
q55267 | arcsin_sqrt | train | def arcsin_sqrt(biom_tbl):
"""
Applies the arcsine square root transform to the
given BIOM-format table
"""
arcsint = lambda data, id_, md: np.arcsin(np.sqrt(data))
tbl_relabd = relative_abd(biom_tbl)
tbl_asin = tbl_relabd.transform(arcsint, inplace=False)
return tbl_asin | python | {
"resource": ""
} |
q55268 | parse_sam | train | def parse_sam(sam, qual):
"""
parse sam file and check mapping quality
"""
for line in sam:
if line.startswith('@'):
continue
line = line.strip().split()
if int(line[4]) == 0 or int(line[4]) < qual:
continue
yield line | python | {
"resource": ""
} |
q55269 | rc_stats | train | def rc_stats(stats):
"""
reverse completement 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']
... | python | {
"resource": ""
} |
q55270 | parse_codons | train | def parse_codons(ref, start, end, strand):
"""
parse codon nucleotide positions in range start -> end, wrt strand
"""
codon = []
c = cycle([1, 2, 3])
ref = ref[start - 1:end]
if strand == -1:
ref = rc_stats(ref)
for pos in ref:
n = next(c)
codon.append(pos)
... | python | {
"resource": ""
} |
q55271 | calc_coverage | train | def calc_coverage(ref, start, end, length, nucs):
"""
calculate coverage for positions in range start -> end
"""
ref = ref[start - 1:end]
bases = 0
for pos in ref:
for base, count in list(pos.items()):
if base in nucs:
bases += count
return float(bases)/fl... | python | {
"resource": ""
} |
q55272 | parse_gbk | train | def parse_gbk(gbks):
"""
parse gbk file
"""
for gbk in gbks:
for record in SeqIO.parse(open(gbk), 'genbank'):
for feature in record.features:
if feature.type == 'gene':
try:
locus = feature.qualifiers['locus_tag'][0]
... | python | {
"resource": ""
} |
q55273 | parse_fasta_annotations | train | def parse_fasta_annotations(fastas, annot_tables, trans_table):
"""
parse gene call information from Prodigal fasta output
"""
if annot_tables is not False:
annots = {}
for table in annot_tables:
for cds in open(table):
ID, start, end, strand = cds.strip().spl... | python | {
"resource": ""
} |
q55274 | parse_annotations | train | def parse_annotations(annots, fmt, annot_tables, trans_table):
"""
parse annotations in either gbk or Prodigal fasta format
"""
annotations = {} # annotations[contig] = [features]
# gbk format
if fmt is False:
for contig, feature in parse_gbk(annots):
if contig not in annotat... | python | {
"resource": ""
} |
q55275 | codon2aa | train | def codon2aa(codon, trans_table):
"""
convert codon to amino acid
"""
return Seq(''.join(codon), IUPAC.ambiguous_dna).translate(table = trans_table)[0] | python | {
"resource": ""
} |
q55276 | find_consensus | train | def find_consensus(bases):
"""
find consensus base based on nucleotide
frequencies
"""
nucs = ['A', 'T', 'G', 'C', 'N']
total = sum([bases[nuc] for nuc in nucs if nuc in bases])
# save most common base as consensus (random nuc if there is a tie)
try:
top = max([bases[nuc] for nuc... | python | {
"resource": ""
} |
q55277 | print_consensus | train | def print_consensus(genomes):
"""
print consensensus sequences for each genome and sample
"""
# generate consensus sequences
cons = {} # cons[genome][sample][contig] = consensus
for genome, contigs in list(genomes.items()):
cons[genome] = {}
for contig, samples in list(contigs.it... | python | {
"resource": ""
} |
q55278 | parse_cov | train | def parse_cov(cov_table, scaffold2genome):
"""
calculate genome coverage from scaffold coverage table
"""
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')
... | python | {
"resource": ""
} |
q55279 | genome_coverage | train | def genome_coverage(covs, s2b):
"""
calculate genome coverage from scaffold coverage
"""
COV = []
for cov in covs:
COV.append(parse_cov(cov, s2b))
return pd.concat(COV) | python | {
"resource": ""
} |
q55280 | parse_s2bs | train | def parse_s2bs(s2bs):
"""
convert s2b files to dictionary
"""
s2b = {}
for s in s2bs:
for line in open(s):
line = line.strip().split('\t')
s, b = line[0], line[1]
s2b[s] = b
return s2b | python | {
"resource": ""
} |
q55281 | fa2s2b | train | def fa2s2b(fastas):
"""
convert fastas to s2b dictionary
"""
s2b = {}
for fa in fastas:
for seq in parse_fasta(fa):
s = seq[0].split('>', 1)[1].split()[0]
s2b[s] = fa.rsplit('/', 1)[-1].rsplit('.', 1)[0]
return s2b | python | {
"resource": ""
} |
q55282 | filter_ambiguity | train | def filter_ambiguity(records, percent=0.5): # , repeats=6)
"""
Filters out sequences with too much ambiguity as defined by the method
parameters.
:type records: list
:param records: A list of sequences
:type repeats: int
:param repeats: Defines the number of repeated N that trigger truncat... | python | {
"resource": ""
} |
q55283 | package_existent | train | def package_existent(name):
"""Search package.
* :class:`bootstrap_py.exceptions.Conflict` exception occurs
when user specified name has already existed.
* :class:`bootstrap_py.exceptions.BackendFailure` exception occurs
when PyPI service is down.
:param str name: package name
"""
... | python | {
"resource": ""
} |
q55284 | append_index_id | train | def append_index_id(id, ids):
"""
add index to id to make it unique wrt ids
"""
index = 1
mod = '%s_%s' % (id, index)
while mod in ids:
index += 1
mod = '%s_%s' % (id, index)
ids.append(mod)
return mod, ids | python | {
"resource": ""
} |
q55285 | de_rep | train | def de_rep(fastas, append_index, return_original = False):
"""
de-replicate fastas based on sequence names
"""
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:
... | python | {
"resource": ""
} |
q55286 | get | train | def get(postcode):
"""
Request data associated with `postcode`.
:param postcode: the postcode to search for. The postcode may
contain spaces (they will be removed).
:returns: a dict of the nearest postcode's data or None if no
postcode data is found.
"""
po... | python | {
"resource": ""
} |
q55287 | get_from_postcode | train | def get_from_postcode(postcode, distance):
"""
Request all postcode data within `distance` miles of `postcode`.
:param postcode: the postcode to search for. The postcode may
contain spaces (they will be removed).
:param distance: distance in miles to `postcode`.
:returns: a ... | python | {
"resource": ""
} |
q55288 | PostCoder._check_point | train | def _check_point(self, lat, lng):
""" Checks if latitude and longitude correct """
if abs(lat) > 90 or abs(lng) > 180:
msg = "Illegal lat and/or lng, (%s, %s) provided." % (lat, lng)
raise IllegalPointException(msg) | python | {
"resource": ""
} |
q55289 | PostCoder._lookup | train | def _lookup(self, skip_cache, fun, *args, **kwargs):
"""
Checks for cached responses, before requesting from
web-service
"""
if args not in self.cache or skip_cache:
self.cache[args] = fun(*args, **kwargs)
return self.cache[args] | python | {
"resource": ""
} |
q55290 | PostCoder.get_nearest | train | def get_nearest(self, lat, lng, skip_cache=False):
"""
Calls `postcodes.get_nearest` but checks correctness of `lat`
and `long`, and by default utilises a local cache.
:param skip_cache: optional argument specifying whether to skip
the cache and make an exp... | python | {
"resource": ""
} |
q55291 | PostCoder.get_from_postcode | train | def get_from_postcode(self, postcode, distance, skip_cache=False):
"""
Calls `postcodes.get_from_postcode` but checks correctness of
`distance`, and by default utilises a local cache.
:param skip_cache: optional argument specifying whether to skip
the cache ... | python | {
"resource": ""
} |
q55292 | PostCoder.get_from_geo | train | def get_from_geo(self, lat, lng, distance, skip_cache=False):
"""
Calls `postcodes.get_from_geo` but checks the correctness of
all arguments, and by default utilises a local cache.
:param skip_cache: optional argument specifying whether to skip
the cache and... | python | {
"resource": ""
} |
q55293 | insertions_from_masked | train | def insertions_from_masked(seq):
"""
get coordinates of insertions from insertion-masked sequence
"""
insertions = []
prev = True
for i, base in enumerate(seq):
if base.isupper() and prev is True:
insertions.append([])
prev = False
elif base.islower():
... | python | {
"resource": ""
} |
q55294 | seq_info | train | def seq_info(names, id2names, insertions, sequences):
"""
get insertion information from header
"""
seqs = {} # seqs[id] = [gene, model, [[i-gene_pos, i-model_pos, i-length, iseq, [orfs], [introns]], ...]]
for name in names:
id = id2names[name]
gene = name.split('fromHMM::', 1)[0].rs... | python | {
"resource": ""
} |
q55295 | check_overlap | train | def check_overlap(pos, ins, thresh):
"""
make sure thresh % feature is contained within insertion
"""
ins_pos = ins[0]
ins_len = ins[2]
ol = overlap(ins_pos, pos)
feat_len = pos[1] - pos[0] + 1
# print float(ol) / float(feat_len)
if float(ol) / float(feat_len) >= thresh:
retur... | python | {
"resource": ""
} |
q55296 | max_insertion | train | def max_insertion(seqs, gene, domain):
"""
length of largest insertion
"""
seqs = [i[2] for i in list(seqs.values()) if i[2] != [] and i[0] == gene and i[1] == domain]
lengths = []
for seq in seqs:
for ins in seq:
lengths.append(int(ins[2]))
if lengths == []:
retu... | python | {
"resource": ""
} |
q55297 | model_length | train | def model_length(gene, domain):
"""
get length of model
"""
if gene == '16S':
domain2max = {'E_coli_K12': int(1538), 'bacteria': int(1689), 'archaea': int(1563), 'eukarya': int(2652)}
return domain2max[domain]
elif gene == '23S':
domain2max = {'E_coli_K12': int(2903), 'bacter... | python | {
"resource": ""
} |
q55298 | setup_markers | train | def setup_markers(seqs):
"""
setup unique marker for every orf annotation
- change size if necessary
"""
family2marker = {} # family2marker[family] = [marker, size]
markers = cycle(['^', 'p', '*', '+', 'x', 'd', '|', 'v', '>', '<', '8'])
size = 60
families = []
for seq in list(seqs.v... | python | {
"resource": ""
} |
q55299 | plot_by_gene_and_domain | train | def plot_by_gene_and_domain(name, seqs, tax, id2name):
"""
plot insertions for each gene and domain
"""
for gene in set([seq[0] for seq in list(seqs.values())]):
for domain in set([seq[1] for seq in list(seqs.values())]):
plot_insertions(name, seqs, gene, domain, tax, id2name) | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.