_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q235400 | Query.count | train | def count(self, *, page_size=DEFAULT_BATCH_SIZE, **options):
"""Counts the number of entities that match this query.
Note:
Since Datastore doesn't provide a native way to count
entities by query, this method paginates through all the
entities' keys and counts them.
... | python | {
"resource": ""
} |
q235401 | Query.delete | train | def delete(self, *, page_size=DEFAULT_BATCH_SIZE, **options):
"""Deletes all the entities that match this query.
Note:
Since Datasotre doesn't provide a native way to delete
entities by query, this method paginates through all the
entities' keys and issues a single delete_... | python | {
"resource": ""
} |
q235402 | Query.get | train | def get(self, **options):
"""Run this query and get the first result.
Parameters:
\**options(QueryOptions, optional)
Returns:
Model: An entity or None if there were no results.
"""
sub_query = self.with_limit(1)
options = QueryOptions(sub_query).repl... | python | {
"resource": ""
} |
q235403 | Query.paginate | train | def paginate(self, *, page_size, **options):
"""Run this query and return a page iterator.
Parameters:
page_size(int): The number of entities to fetch per page.
\**options(QueryOptions, optional)
Returns:
Pages: An iterator for this query's pages of results.
... | python | {
"resource": ""
} |
q235404 | namespace | train | def namespace(namespace):
"""Context manager for stacking the current thread-local default
namespace. Exiting the context sets the thread-local default
namespace back to the previously-set namespace. If there is no
previous namespace, then the thread-local namespace is cleared.
Example:
>>>... | python | {
"resource": ""
} |
q235405 | lookup_model_by_kind | train | def lookup_model_by_kind(kind):
"""Look up the model instance for a given Datastore kind.
Parameters:
kind(str)
Raises:
RuntimeError: If a model for the given kind has not been
defined.
Returns:
model: The model class.
"""
model = _known_models.get(kind)
if model... | python | {
"resource": ""
} |
q235406 | delete_multi | train | def delete_multi(keys):
"""Delete a set of entitites from Datastore by their
respective keys.
Note:
This uses the adapter that is tied to the first model in the list.
If the keys have disparate adapters this function may behave in
unexpected ways.
Warning:
You must pass a **lis... | python | {
"resource": ""
} |
q235407 | get_multi | train | def get_multi(keys):
"""Get a set of entities from Datastore by their respective keys.
Note:
This uses the adapter that is tied to the first model in the
list. If the keys have disparate adapters this function may
behave in unexpected ways.
Warning:
You must pass a **list** and no... | python | {
"resource": ""
} |
q235408 | put_multi | train | def put_multi(entities):
"""Persist a set of entities to Datastore.
Note:
This uses the adapter that is tied to the first Entity in the
list. If the entities have disparate adapters this function may
behave in unexpected ways.
Warning:
You must pass a **list** and not a generator ... | python | {
"resource": ""
} |
q235409 | Key.from_path | train | def from_path(cls, *path, namespace=None):
"""Build up a Datastore key from a path.
Parameters:
\*path(tuple[str or int]): The path segments.
namespace(str): An optional namespace for the key. This is
applied to each key in the tree.
Returns:
anom.Key:... | python | {
"resource": ""
} |
q235410 | Property.validate | train | def validate(self, value):
"""Validates that `value` can be assigned to this Property.
Parameters:
value: The value to validate.
Raises:
TypeError: If the type of the assigned value is invalid.
Returns:
The value that should be assigned to the entity.
... | python | {
"resource": ""
} |
q235411 | Property.prepare_to_store | train | def prepare_to_store(self, entity, value):
"""Prepare `value` for storage. Called by the Model for each
Property, value pair it contains before handing the data off
to an adapter.
Parameters:
entity(Model): The entity to which the value belongs.
value: The value bei... | python | {
"resource": ""
} |
q235412 | Model.get | train | def get(cls, id_or_name, *, parent=None, namespace=None):
"""Get an entity by id.
Parameters:
id_or_name(int or str): The entity's id.
parent(anom.Key, optional): The entity's parent Key.
namespace(str, optional): The entity's namespace.
Returns:
Model: ... | python | {
"resource": ""
} |
q235413 | DotEnv.init_app | train | def init_app(self, app, env_file=None, verbose_mode=False):
"""Imports .env file."""
if self.app is None:
self.app = app
self.verbose_mode = verbose_mode
if env_file is None:
env_file = os.path.join(os.getcwd(), ".env")
if not os.path.exists(env_file):
... | python | {
"resource": ""
} |
q235414 | DotEnv.__import_vars | train | def __import_vars(self, env_file):
"""Actual importing function."""
with open(env_file, "r") as f: # pylint: disable=invalid-name
for line in f:
try:
line = line.lstrip()
if line.startswith('export'):
line = lin... | python | {
"resource": ""
} |
q235415 | CountryMiddleware.process_response | train | def process_response(self, request, response):
"""
Shares config with the language cookie as they serve a similar purpose
"""
if hasattr(request, 'COUNTRY_CODE'):
response.set_cookie(
key=constants.COUNTRY_COOKIE_NAME,
value=request.COUNTRY_CO... | python | {
"resource": ""
} |
q235416 | PrettyIDsMixin.create_option | train | def create_option(
self, name, value, label, selected, index,
subindex=None, attrs=None):
"""Patch to use nicer ids."""
index = str(index) if subindex is None else "%s%s%s" % (
index, self.id_separator, subindex)
if attrs is None:
attrs = {}
... | python | {
"resource": ""
} |
q235417 | current_version | train | def current_version():
"""Get current version of directory-components."""
filepath = os.path.abspath(
project_root / "directory_components" / "version.py")
version_py = get_file_string(filepath)
regex = re.compile(Utils.get_version)
if regex.search(version_py) is not None:
current_ve... | python | {
"resource": ""
} |
q235418 | get_file_string | train | def get_file_string(filepath):
"""Get string from file."""
with open(os.path.abspath(filepath)) as f:
return f.read() | python | {
"resource": ""
} |
q235419 | replace_in_dirs | train | def replace_in_dirs(version):
"""Look through dirs and run replace_in_files in each."""
print(color(
"Upgrading directory-components dependency in all repos...",
fg='blue', style='bold'))
for dirname in Utils.dirs:
replace = "directory-components=={}".format(version)
replace_... | python | {
"resource": ""
} |
q235420 | replace_in_files | train | def replace_in_files(dirname, replace):
"""Replace current version with new version in requirements files."""
filepath = os.path.abspath(dirname / "requirements.in")
if os.path.isfile(filepath) and header_footer_exists(filepath):
replaced = re.sub(Utils.exp, replace, get_file_string(filepath))
... | python | {
"resource": ""
} |
q235421 | header_footer_exists | train | def header_footer_exists(filepath):
"""Check if directory-components is listed in requirements files."""
with open(filepath) as f:
return re.search(Utils.exp, f.read()) | python | {
"resource": ""
} |
q235422 | linedelimited | train | def linedelimited (inlist,delimiter):
"""
Returns a string composed of elements in inlist, with each element
separated by 'delimiter.' Used by function writedelimited. Use '\t'
for tab-delimiting.
Usage: linedelimited (inlist,delimiter)
"""
outstr = ''
for item in inlist:
if type(item) != Strin... | python | {
"resource": ""
} |
q235423 | lineincustcols | train | def lineincustcols (inlist,colsizes):
"""
Returns a string composed of elements in inlist, with each element
right-aligned in a column of width specified by a sequence colsizes. The
length of colsizes must be greater than or equal to the number of columns
in inlist.
Usage: lineincustcols (inlist,colsizes)
Retur... | python | {
"resource": ""
} |
q235424 | list2string | train | def list2string (inlist,delimit=' '):
"""
Converts a 1D list to a single long string for file output, using
the string.join function.
Usage: list2string (inlist,delimit=' ')
Returns: the string created from inlist
"""
stringlist = [makestr(_) for _ in inlist]
return string.join(stringlist,delimit) | python | {
"resource": ""
} |
q235425 | replace | train | def replace (inlst,oldval,newval):
"""
Replaces all occurrences of 'oldval' with 'newval', recursively.
Usage: replace (inlst,oldval,newval)
"""
lst = inlst*1
for i in range(len(lst)):
if type(lst[i]) not in [ListType,TupleType]:
if lst[i]==oldval: lst[i]=newval
else:
... | python | {
"resource": ""
} |
q235426 | duplicates | train | def duplicates(inlist):
"""
Returns duplicate items in the FIRST dimension of the passed list.
Usage: duplicates (inlist)
"""
dups = []
for i in range(len(inlist)):
if inlist[i] in inlist[i+1:]:
dups.append(inlist[i])
return dups | python | {
"resource": ""
} |
q235427 | nonrepeats | train | def nonrepeats(inlist):
"""
Returns items that are NOT duplicated in the first dim of the passed list.
Usage: nonrepeats (inlist)
"""
nonrepeats = []
for i in range(len(inlist)):
if inlist.count(inlist[i]) == 1:
nonrepeats.append(inlist[i])
return nonrepeats | python | {
"resource": ""
} |
q235428 | lz | train | def lz (inlist, score):
"""
Returns the z-score for a given input score, given that score and the
list from which that score came. Not appropriate for population calculations.
Usage: lz(inlist, score)
"""
z = (score-mean(inlist))/samplestdev(inlist)
return z | python | {
"resource": ""
} |
q235429 | llinregress | train | def llinregress(x,y):
"""
Calculates a regression line on x,y pairs.
Usage: llinregress(x,y) x,y are equal-length lists of x-y coordinates
Returns: slope, intercept, r, two-tailed prob, sterr-of-estimate
"""
TINY = 1.0e-20
if len(x) != len(y):
raise ValueError('Input values not paired in l... | python | {
"resource": ""
} |
q235430 | lks_2samp | train | def lks_2samp (data1,data2):
"""
Computes the Kolmogorov-Smirnof statistic on 2 samples. From
Numerical Recipies in C, page 493.
Usage: lks_2samp(data1,data2) data1&2 are lists of values for 2 conditions
Returns: KS D-value, associated p-value
"""
j1 = 0
j2 = 0
fn1 = 0.0
fn2 = 0.0
n1 = len... | python | {
"resource": ""
} |
q235431 | lranksums | train | def lranksums(x,y):
"""
Calculates the rank sums statistic on the provided scores and
returns the result. Use only when the n in each condition is > 20 and you
have 2 independent samples of ranks.
Usage: lranksums(x,y)
Returns: a z-statistic, two-tailed p-value
"""
n1 = len(x)
n2 = len(y)
alldata = ... | python | {
"resource": ""
} |
q235432 | lkruskalwallish | train | def lkruskalwallish(*args):
"""
The Kruskal-Wallis H-test is a non-parametric ANOVA for 3 or more
groups, requiring at least 5 subjects in each group. This function
calculates the Kruskal-Wallis H-test for 3 or more independent samples
and returns the result.
Usage: lkruskalwallish(*args)
Returns: H-statistic... | python | {
"resource": ""
} |
q235433 | lksprob | train | def lksprob(alam):
"""
Computes a Kolmolgorov-Smirnov t-test significance level. Adapted from
Numerical Recipies.
Usage: lksprob(alam)
"""
fac = 2.0
sum = 0.0
termbf = 0.0
a2 = -2.0*alam*alam
for j in range(1,201):
term = fac*math.exp(a2*j*j)
sum = sum + term
if math.... | python | {
"resource": ""
} |
q235434 | outputpairedstats | train | def outputpairedstats(fname,writemode,name1,n1,m1,se1,min1,max1,name2,n2,m2,se2,min2,max2,statname,stat,prob):
"""
Prints or write to a file stats for two groups, using the name, n,
mean, sterr, min and max for each group, as well as the statistic name,
its value, and the associated p-value.
Usage: outputpaireds... | python | {
"resource": ""
} |
q235435 | GeneReader | train | def GeneReader( fh, format='gff' ):
""" yield chrom, strand, gene_exons, name """
known_formats = ( 'gff', 'gtf', 'bed')
if format not in known_formats:
print('%s format not in %s' % (format, ",".join( known_formats )), file=sys.stderr)
raise Exception('?')
if format == 'bed':
... | python | {
"resource": ""
} |
q235436 | SeqFile.get | train | def get(self, start, length):
"""
Fetch subsequence starting at position `start` with length `length`.
This method is picky about parameters, the requested interval must
have non-negative length and fit entirely inside the NIB sequence,
the returned string will contain exactly ... | python | {
"resource": ""
} |
q235437 | read_scoring_scheme | train | def read_scoring_scheme( f, gap_open, gap_extend, gap1="-", gap2=None, **kwargs ):
"""
Initialize scoring scheme from a file containint a blastz style text blob.
f can be either a file or the name of a file.
"""
close_it = False
if (type(f) == str):
f = file(f,"rt")
close_it = Tr... | python | {
"resource": ""
} |
q235438 | shuffle_columns | train | def shuffle_columns( a ):
"""Randomize the columns of an alignment"""
mask = range( a.text_size )
random.shuffle( mask )
for c in a.components:
c.text = ''.join( [ c.text[i] for i in mask ] ) | python | {
"resource": ""
} |
q235439 | Alignment.slice_by_component | train | def slice_by_component( self, component_index, start, end ):
"""
Return a slice of the alignment, corresponding to an coordinate interval in a specific component.
component_index is one of
an integer offset into the components list
a string indicating the src of the desi... | python | {
"resource": ""
} |
q235440 | Alignment.remove_all_gap_columns | train | def remove_all_gap_columns( self ):
"""
Remove any columns containing only gaps from alignment components,
text of components is modified IN PLACE.
"""
seqs = []
for c in self.components:
try:
seqs.append( list( c.text ) )
except Ty... | python | {
"resource": ""
} |
q235441 | Component.slice_by_coord | train | def slice_by_coord( self, start, end ):
"""
Return the slice of the component corresponding to a coordinate interval.
start and end are relative to the + strand, regardless of the component's strand.
"""
start_col = self.coord_to_col( start )
end_col = self.coord_to_col... | python | {
"resource": ""
} |
q235442 | Component.coord_to_col | train | def coord_to_col( self, pos ):
"""
Return the alignment column index corresponding to coordinate pos.
pos is relative to the + strand, regardless of the component's strand.
"""
start,end = self.get_forward_strand_start(),self.get_forward_strand_end()
if pos < start or p... | python | {
"resource": ""
} |
q235443 | get_components_for_species | train | def get_components_for_species( alignment, species ):
"""Return the component for each species in the list `species` or None"""
# If the number of components in the alignment is less that the requested number
# of species we can immediately fail
if len( alignment.components ) < len( species ): return No... | python | {
"resource": ""
} |
q235444 | read_next_maf | train | def read_next_maf( file, species_to_lengths=None, parse_e_rows=False ):
"""
Read the next MAF block from `file` and return as an `Alignment`
instance. If `parse_i_rows` is true, empty components will be created
when e rows are encountered.
"""
alignment = Alignment(species_to_lengths=species_t... | python | {
"resource": ""
} |
q235445 | readline | train | def readline( file, skip_blank=False ):
"""Read a line from provided file, skipping any blank or comment lines"""
while 1:
line = file.readline()
#print "every line: %r" % line
if not line: return None
if line[0] != '#' and not ( skip_blank and line.isspace() ):
retu... | python | {
"resource": ""
} |
q235446 | parse_attributes | train | def parse_attributes( fields ):
"""Parse list of key=value strings into a dict"""
attributes = {}
for field in fields:
pair = field.split( '=' )
attributes[ pair[0] ] = pair[1]
return attributes | python | {
"resource": ""
} |
q235447 | TransfacReader.as_dict | train | def as_dict( self, key="id" ):
"""
Return a dictionary containing all remaining motifs, using `key`
as the dictionary key.
"""
rval = {}
for motif in self:
rval[ getattr( motif, key ) ] = motif
return rval | python | {
"resource": ""
} |
q235448 | TransfacReader.parse_record | train | def parse_record( self, lines ):
"""
Parse a TRANSFAC record out of `lines` and return a motif.
"""
# Break lines up
temp_lines = []
for line in lines:
fields = line.rstrip( "\r\n" ).split( None, 1 )
if len( fields ) == 1:
fields.ap... | python | {
"resource": ""
} |
q235449 | bit_clone | train | def bit_clone( bits ):
"""
Clone a bitset
"""
new = BitSet( bits.size )
new.ior( bits )
return new | python | {
"resource": ""
} |
q235450 | throw_random | train | def throw_random( lengths, mask ):
"""
Try multiple times to run 'throw_random'
"""
saved = None
for i in range( maxtries ):
try:
return throw_random_bits( lengths, mask )
except MaxtriesException as e:
saved = e
continue
raise e | python | {
"resource": ""
} |
q235451 | as_bits | train | def as_bits( region_start, region_length, intervals ):
"""
Convert a set of intervals overlapping a region of a chromosome into
a bitset for just that region with the bits covered by the intervals
set.
"""
bits = BitSet( region_length )
for chr, start, stop in intervals:
bits.set_r... | python | {
"resource": ""
} |
q235452 | interval_lengths | train | def interval_lengths( bits ):
"""
Get the length distribution of all contiguous runs of set bits from
"""
end = 0
while 1:
start = bits.next_set( end )
if start == bits.size: break
end = bits.next_clear( start )
yield end - start | python | {
"resource": ""
} |
q235453 | count_overlap | train | def count_overlap( bits1, bits2 ):
"""
Count the number of bits that overlap between two sets
"""
b = BitSet( bits1.size )
b |= bits1
b &= bits2
return b.count_range( 0, b.size ) | python | {
"resource": ""
} |
q235454 | overlapping_in_bed | train | def overlapping_in_bed( fname, r_chr, r_start, r_stop ):
"""
Get from a bed all intervals that overlap the region defined by
r_chr, r_start, r_stop.
"""
rval = []
for line in open( fname ):
if line.startswith( "#" ) or line.startswith( "track" ):
continue
fields = lin... | python | {
"resource": ""
} |
q235455 | tile_interval | train | def tile_interval( sources, index, ref_src, start, end, seq_db=None ):
"""
Tile maf blocks onto an interval. The resulting block will span the interval
exactly and contain the column from the highest scoring alignment at each
position.
`sources`: list of sequence source names to include in final bl... | python | {
"resource": ""
} |
q235456 | get_fill_char | train | def get_fill_char( maf_status ):
"""
Return the character that should be used to fill between blocks
having a given status
"""
## assert maf_status not in ( maf.MAF_CONTIG_NESTED_STATUS, maf.MAF_NEW_NESTED_STATUS,
## maf.MAF_MAYBE_NEW_NESTED_STATUS ), \
## "Ne... | python | {
"resource": ""
} |
q235457 | guess_fill_char | train | def guess_fill_char( left_comp, right_comp ):
"""
For the case where there is no annotated synteny we will try to guess it
"""
# No left component, obiously new
return "*"
# First check that the blocks have the same src (not just species) and
# orientation
if ( left_comp.src == right_co... | python | {
"resource": ""
} |
q235458 | remove_all_gap_columns | train | def remove_all_gap_columns( texts ):
"""
Remove any columns containing only gaps from alignment texts
"""
seqs = [ list( t ) for t in texts ]
i = 0
text_size = len( texts[0] )
while i < text_size:
all_gap = True
for seq in seqs:
if seq[i] not in ( '-', '#', '*', '... | python | {
"resource": ""
} |
q235459 | cross_lists | train | def cross_lists(*sets):
"""Return the cross product of the arguments"""
wheels = [iter(_) for _ in sets]
digits = [next(it) for it in wheels]
while True:
yield digits[:]
for i in range(len(digits)-1, -1, -1):
try:
digits[i] = next(wheels[i])
br... | python | {
"resource": ""
} |
q235460 | read_lengths_file | train | def read_lengths_file( name ):
"""
Returns a hash from sequence name to length.
"""
chrom_to_length = {}
f = file ( name, "rt" )
for line in f:
line = line.strip()
if line == '' or line[0] == '#': continue
try:
fields = line.split()
if len(fields)... | python | {
"resource": ""
} |
q235461 | IntervalReader | train | def IntervalReader( f ):
"""
Iterator yielding chrom, start, end, strand, value.
Values are zero-based, half-open.
Regions which lack a score are ignored.
"""
current_chrom = None
current_pos = None
current_step = None
# always for wiggle data
strand = '+'
mode = "bed"
... | python | {
"resource": ""
} |
q235462 | fuse_list | train | def fuse_list( mafs ):
"""
Try to fuse a list of blocks by progressively fusing each adjacent pair.
"""
last = None
for m in mafs:
if last is None:
last = m
else:
fused = fuse( last, m )
if fused:
last = fused
else:
... | python | {
"resource": ""
} |
q235463 | ParserElement.setBreak | train | def setBreak(self,breakFlag = True):
"""Method to invoke the Python pdb debugger when this element is
about to be parsed. Set breakFlag to True to enable, False to
disable.
"""
if breakFlag:
_parseMethod = self._parse
def breaker(instring, loc, doAct... | python | {
"resource": ""
} |
q235464 | ParserElement.searchString | train | def searchString( self, instring, maxMatches=_MAX_INT ):
"""Another extension to scanString, simplifying the access to the tokens found
to match the given parse expression. May be called with optional
maxMatches argument, to clip searching after 'n' matches are found.
"""
... | python | {
"resource": ""
} |
q235465 | Chain._strfactory | train | def _strfactory(cls, line):
"""factory class method for Chain
:param line: header of a chain (in .chain format)
"""
assert type(line) == str, "this is a factory from string"
line = line.rstrip().split()[1:] # the first component is the keyword "chain"
tup = [t[0](t[1])... | python | {
"resource": ""
} |
q235466 | Chain.bedInterval | train | def bedInterval(self, who):
"return a BED6 entry, thus DOES coordinate conversion for minus strands"
if who == 't':
st, en = self.tStart, self.tEnd
if self.tStrand == '-':
st, en = self.tSize-en, self.tSize-st
return (self.tName, st, en, self.id, self... | python | {
"resource": ""
} |
q235467 | EPOitem._strfactory | train | def _strfactory(cls, line):
"""factory method for an EPOitem
:param line: a line of input"""
cmp = line.rstrip().split()
chrom = cmp[2]
if not chrom.startswith("chr"):
chrom = "chr%s" % chrom
instance = tuple.__new__(cls,
(cmp[0], cmp[1],
... | python | {
"resource": ""
} |
q235468 | binned_bitsets_proximity | train | def binned_bitsets_proximity( f, chrom_col=0, start_col=1, end_col=2, strand_col=5, upstream=0, downstream=0 ):
"""Read a file into a dictionary of bitsets"""
last_chrom = None
last_bitset = None
bitsets = dict()
for line in f:
if line.startswith("#"): continue
# print "input=%s" % ( ... | python | {
"resource": ""
} |
q235469 | binned_bitsets_from_list | train | def binned_bitsets_from_list( list=[] ):
"""Read a list into a dictionary of bitsets"""
last_chrom = None
last_bitset = None
bitsets = dict()
for l in list:
chrom = l[0]
if chrom != last_chrom:
if chrom not in bitsets:
bitsets[chrom] = BinnedBitSet(MAX)
... | python | {
"resource": ""
} |
q235470 | binned_bitsets_by_chrom | train | def binned_bitsets_by_chrom( f, chrom, chrom_col=0, start_col=1, end_col=2):
"""Read a file by chrom name into a bitset"""
bitset = BinnedBitSet( MAX )
for line in f:
if line.startswith("#"): continue
fields = line.split()
if fields[chrom_col] == chrom:
start, end = int( ... | python | {
"resource": ""
} |
q235471 | _double_as_bytes | train | def _double_as_bytes(dval):
"Use struct.unpack to decode a double precision float into eight bytes"
tmp = list(struct.unpack('8B',struct.pack('d', dval)))
if not _big_endian:
tmp.reverse()
return tmp | python | {
"resource": ""
} |
q235472 | _mantissa | train | def _mantissa(dval):
"""Extract the _mantissa bits from a double-precision floating
point value."""
bb = _double_as_bytes(dval)
mantissa = bb[1] & 0x0f << 48
mantissa += bb[2] << 40
mantissa += bb[3] << 32
mantissa += bb[4]
return mantissa | python | {
"resource": ""
} |
q235473 | _zero_mantissa | train | def _zero_mantissa(dval):
"""Determine whether the mantissa bits of the given double are all
zero."""
bb = _double_as_bytes(dval)
return ((bb[1] & 0x0f) | reduce(operator.or_, bb[2:])) == 0 | python | {
"resource": ""
} |
q235474 | load_scores_wiggle | train | def load_scores_wiggle( fname ):
"""
Read a wiggle file and return a dict of BinnedArray objects keyed
by chromosome.
"""
scores_by_chrom = dict()
for chrom, pos, val in bx.wiggle.Reader( misc.open_compressed( fname ) ):
if chrom not in scores_by_chrom:
scores_by_chrom[chrom... | python | {
"resource": ""
} |
q235475 | Index.new | train | def new( self, min, max ):
"""Create an empty index for intervals in the range min, max"""
# Ensure the range will fit given the shifting strategy
assert MIN <= min <= max <= MAX
self.min = min
self.max = max
# Determine offsets to use
self.offsets = offsets_for_m... | python | {
"resource": ""
} |
q235476 | FileCache.seek | train | def seek( self, offset, whence=0 ):
"""
Move the file pointer to a particular offset.
"""
# Determine absolute target position
if whence == 0:
target_pos = offset
elif whence == 1:
target_pos = self.file_pos + offset
elif whence == 2:
... | python | {
"resource": ""
} |
q235477 | LRUCache.mtime | train | def mtime(self, key):
"""Return the last modification time for the cache record with key.
May be useful for cache instances where the stored values can get
'stale', such as caching file or network resource contents."""
if key not in self.__dict:
raise CacheKeyError(key)
... | python | {
"resource": ""
} |
q235478 | class_space | train | def class_space(classlevel=3):
"returns the calling class' name and dictionary"
frame = sys._getframe(classlevel)
classname = frame.f_code.co_name
classdict = frame.f_locals
return classname, classdict | python | {
"resource": ""
} |
q235479 | Reader.build_alignment | train | def build_alignment(self,score,pieces):
"""converts a score and pieces to an alignment"""
# build text
self.open_seqs()
text1 = text2 = ""
end1 = end2 = None
for (start1,start2,length,pctId) in pieces:
if (end1 != None):
if (start1 == end1): # insertion in sequence 2
text1 += self.seq1_gap * ... | python | {
"resource": ""
} |
q235480 | bits_clear_in_range | train | def bits_clear_in_range( bits, range_start, range_end ):
"""
Yield start,end tuples for each span of clear bits in [range_start,range_end)
"""
end = range_start
while 1:
start = bits.next_clear( end )
if start >= range_end: break
end = min( bits.next_set( start ), range_end )... | python | {
"resource": ""
} |
q235481 | iterprogress | train | def iterprogress( sized_iterable ):
"""
Iterate something printing progress bar to stdout
"""
pb = ProgressBar( 0, len( sized_iterable ) )
for i, value in enumerate( sized_iterable ):
yield value
pb.update_and_print( i, sys.stderr ) | python | {
"resource": ""
} |
q235482 | FileCDBDict.to_file | train | def to_file( Class, dict, file, is_little_endian=True ):
"""
For constructing a CDB structure in a file. Able to calculate size on
disk and write to a file
"""
io = BinaryFileWriter( file, is_little_endian=is_little_endian )
start_offset = io.tell()
# Header is of... | python | {
"resource": ""
} |
q235483 | read_len | train | def read_len( f ):
"""Read a 'LEN' file and return a mapping from chromosome to length"""
mapping = dict()
for line in f:
fields = line.split()
mapping[ fields[0] ] = int( fields[1] )
return mapping | python | {
"resource": ""
} |
q235484 | eps_logo | train | def eps_logo( matrix, base_width, height, colors=DNA_DEFAULT_COLORS ):
"""
Return an EPS document containing a sequence logo for matrix where each
bases is shown as a column of `base_width` points and the total logo
height is `height` points. If `colors` is provided it is a mapping from
characters t... | python | {
"resource": ""
} |
q235485 | transform | train | def transform(elem, chain_CT_CQ, max_gap):
"""transform the coordinates of this elem into the other species.
elem intersects this chain's ginterval.
:return: a list of the type [(to_chr, start, end, elem[id]) ... ]"""
(chain, CT, CQ) = chain_CT_CQ
start, end = max(elem['start'], chain.tStart) - cha... | python | {
"resource": ""
} |
q235486 | loadChains | train | def loadChains(path):
"name says it."
EPO = epo.Chain._parse_file(path, True)
## convert coordinates w.r.t the forward strand (into slices)
## compute cummulative intervals
for i in range( len(EPO) ):
ch, S, T, Q = EPO[i]
if ch.tStrand == '-':
ch = ch._replace(tEnd = ch.... | python | {
"resource": ""
} |
q235487 | loadFeatures | train | def loadFeatures(path, opt):
"""
Load features. For BED, only BED4 columns are loaded.
For narrowPeak, all columns are loaded.
"""
log.info("loading from %s ..." % path)
data = []
if opt.in_format == "BED":
with open(path) as fd:
for line in fd:
c... | python | {
"resource": ""
} |
q235488 | GIntervalTree.add | train | def add(self, chrom, element):
"""insert an element. use this method as the IntervalTree one.
this will simply call the IntervalTree.add method on the right tree
:param chrom: chromosome
:param element: the argument of IntervalTree.insert_interval
:return: None
"""
... | python | {
"resource": ""
} |
q235489 | GIntervalTree.find | train | def find(self, chrom, start, end):
"""find the intersecting elements
:param chrom: chromosome
:param start: start
:param end: end
:return: a list of intersecting elements"""
tree = self._trees.get( chrom, None )
if tree:
return tree.find( start, end ... | python | {
"resource": ""
} |
q235490 | BaseMatrix.create_from_other | train | def create_from_other( Class, other, values=None ):
"""
Create a new Matrix with attributes taken from `other` but with the
values taken from `values` if provided
"""
m = Class()
m.alphabet = other.alphabet
m.sorted_alphabet = other.sorted_alphabet
m.char... | python | {
"resource": ""
} |
q235491 | FrequencyMatrix.to_logodds_scoring_matrix | train | def to_logodds_scoring_matrix( self, background=None, correction=DEFAULT_CORRECTION ):
"""
Create a standard logodds scoring matrix.
"""
alphabet_size = len( self.alphabet )
if background is None:
background = ones( alphabet_size, float32 ) / alphabet_size
# R... | python | {
"resource": ""
} |
q235492 | ScoringMatrix.score_string | train | def score_string( self, string ):
"""
Score each valid position in `string` using this scoring matrix.
Positions which were not scored are set to nan.
"""
rval = zeros( len( string ), float32 )
rval[:] = nan
_pwm.score_string( self.values, self.char_to_index, str... | python | {
"resource": ""
} |
q235493 | ComputeResponse._calc_resp | train | def _calc_resp(password_hash, server_challenge):
"""
Generate the LM response given a 16-byte password hash and the
challenge from the CHALLENGE_MESSAGE
:param password_hash: A 16-byte password hash
:param server_challenge: A random 8-byte response generated by the
s... | python | {
"resource": ""
} |
q235494 | DES.encrypt | train | def encrypt(self, data, pad=True):
"""
DES encrypts the data based on the key it was initialised with.
:param data: The bytes string to encrypt
:param pad: Whether to right pad data with \x00 to a multiple of 8
:return: The encrypted bytes string
"""
encrypted_da... | python | {
"resource": ""
} |
q235495 | DES.decrypt | train | def decrypt(self, data):
"""
DES decrypts the data based on the key it was initialised with.
:param data: The encrypted bytes string to decrypt
:return: The decrypted bytes string
"""
decrypted_data = b""
for i in range(0, len(data), 8):
block = data[... | python | {
"resource": ""
} |
q235496 | DES.key56_to_key64 | train | def key56_to_key64(key):
"""
This takes in an a bytes string of 7 bytes and converts it to a bytes
string of 8 bytes with the odd parity bit being set to every 8 bits,
For example
b"\x01\x02\x03\x04\x05\x06\x07"
00000001 00000010 00000011 00000100 00000101 00000110 0000... | python | {
"resource": ""
} |
q235497 | Check.visit_Method | train | def visit_Method(self, method):
"""
Ensure method has the same signature matching method on parent interface.
:param method: L{quarkc.ast.Method} instance.
"""
resolved_method = method.resolved.type
def get_params(method, extra_bindings):
# The Method should... | python | {
"resource": ""
} |
q235498 | get_doc | train | def get_doc(node):
"""
Return a node's documentation as a string, pulling from annotations
or constructing a simple fake as needed.
"""
res = " ".join(get_doc_annotations(node))
if not res:
res = "(%s)" % node.__class__.__name__.lower()
return res | python | {
"resource": ""
} |
q235499 | get_code | train | def get_code(node, coder=Coder()):
"""
Return a node's code
"""
return cgi.escape(str(coder.code(node)), quote=True) | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.