INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Syntactic sugar around to make it easier to get fine-grained access
to the parts of a file without composing a PhyloSchema object.
Possible invocations include:
w.get('pg_10')
w.get('pg_10', 'trees')
w.get('pg_10', 'trees', format='nexus')
w.get('pg_10', t... | def get(self, study_id, content=None, schema=None, **kwargs):
"""Syntactic sugar around to make it easier to get fine-grained access
to the parts of a file without composing a PhyloSchema object.
Possible invocations include:
w.get('pg_10')
w.get('pg_10', 'trees')
... |
Load a delimited text file to a numpy record array.
Basically, this function calls loadSVcols and combines columns returned by
that function into a numpy ndarray with stuctured dtype. Also uses and
returns metadata including column names, formats, coloring, &c. if these
items are determined during ... | def loadSV(fname, shape=None, titles=None, aligned=False, byteorder=None,
renamer=None, **kwargs):
"""
Load a delimited text file to a numpy record array.
Basically, this function calls loadSVcols and combines columns returned by
that function into a numpy ndarray with stuctured dtype. A... |
Load a separated value text file to a list of column arrays.
Basically, this function calls loadSVrecs, and transposes the string-valued
row data returned by that function into a Python list of numpy arrays
corresponding to columns, each a uniform Python type (int, float, str).
Also uses and return... | def loadSVcols(fname, usecols=None, excludecols=None, valuefixer=None,
colfixer=None, missingvalues=None, fillingvalues=None,
typeinferer=None, **kwargs):
"""
Load a separated value text file to a list of column arrays.
Basically, this function calls loadSVrecs, and transpose... |
Load a separated value text file to a list of lists of strings of records.
Takes a tabular text file with a specified delimeter and end-of-line
character, and return data as a list of lists of strings corresponding to
records (rows). Also uses and returns metadata (including column names,
formats, ... | def loadSVrecs(fname, uselines=None, skiprows=0, linefixer=None,
delimiter_regex=None, verbosity=DEFAULT_VERBOSITY, **metadata):
"""
Load a separated value text file to a list of lists of strings of records.
Takes a tabular text file with a specified delimeter and end-of-line
character... |
Save a tabarray to a separated-variable (CSV) file.
**Parameters**
**fname** : string
Path to a separated variable (CSV) text file.
**X** : tabarray
The actual data in a :class:`tabular.tab.tabarray`.
**comments** : string, optional
The character... | def saveSV(fname, X, comments=None, metadata=None, printmetadict=None,
dialect=None, delimiter=None, doublequote=True,
lineterminator='\n', escapechar = None,
quoting=csv.QUOTE_MINIMAL, quotechar='"',
skipinitialspace=False, stringifier=None... |
Attempts to convert infer dialect from csv file lines.
Essentially a small extension of the "sniff" function from Python CSV
module. csv.Sniffer().sniff attempts to infer the delimiter from a
putative delimited text file by analyzing character frequencies. This
function adds additional analy... | def inferdialect(fname=None, datalines=None, delimiter_regex=None,
verbosity=DEFAULT_VERBOSITY):
"""
Attempts to convert infer dialect from csv file lines.
Essentially a small extension of the "sniff" function from Python CSV
module. csv.Sniffer().sniff attempts to infer the d... |
Read metadata from a delimited text file. | def readstoredmetadata(fname, skiprows=0, linenumber=None, comments='#',
metametadata=None, verbosity=DEFAULT_VERBOSITY):
"""
Read metadata from a delimited text file.
"""
if is_string_like(fname):
fh = file(fname, 'rU')
elif hasattr(fname, 'readline'):
f... |
Process Metadata from stored (or "packed") state to functional state.
Metadata can come be read from a file "packed" in various ways,
e.g. with a string representation of a dialect or coloring dictionary.
This function "unpacks" the stored metadata into useable Python
objects. It consists of a list... | def processmetadata(metadata, items=None, comments=None, delimiter_regex=None,
ncols=None, verbosity=DEFAULT_VERBOSITY):
"""
Process Metadata from stored (or "packed") state to functional state.
Metadata can come be read from a file "packed" in various ways,
e.g. with a string repr... |
Infers header from a CSV or other tab-delimited file.
This is essentially small extension of the csv.Sniffer.has_header algorithm.
provided in the Python csv module. First, it checks to see whether a
metametadata dictionary is present, specifiying the lines numbers of
metadata lines in the head... | def inferheader(lines, comments=None, metadata=None,
verbosity=DEFAULT_VERBOSITY):
"""
Infers header from a CSV or other tab-delimited file.
This is essentially small extension of the csv.Sniffer.has_header algorithm.
provided in the Python csv module. First, it checks to see whet... |
Checks whether a given AST (abstract syntax tree) object represents a
metametadata dictionary. | def IsMetaMetaDict(AST):
"""
Checks whether a given AST (abstract syntax tree) object represents a
metametadata dictionary.
"""
isintpair = lambda x : (isinstance(x,Tuple) and (len(x.asList()) == 2) and
isctype(x.asList()[0], int) and
... |
Attempts to convert a string representation of a CSV
dialect (as would be read from a file header, for instance)
into an actual csv.Dialect object. | def dialectfromstring(s):
"""
Attempts to convert a string representation of a CSV
dialect (as would be read from a file header, for instance)
into an actual csv.Dialect object.
"""
try:
AST = compiler.parse(s)
except SyntaxError:
return
else:
try:
... |
Attempts to convert a string representation of a coloring dictionary (as
would be read from a file header, for instance) into an actual coloring
dictionary. | def coloringfromstring(s):
"""
Attempts to convert a string representation of a coloring dictionary (as
would be read from a file header, for instance) into an actual coloring
dictionary.
"""
try:
AST = compiler.parse(s)
except SyntaxError:
return
else:
try... |
Load a numpy binary file or archive created by tabular.io.savebinary.
Load a numpy binary file (``.npy``) or archive (``.npz``) created by
:func:`tabular.io.savebinary`.
The data and associated data type (e.g. `dtype`, including if given, column
names) are loaded and reconstituted.
If `fnam... | def loadbinary(fname):
"""
Load a numpy binary file or archive created by tabular.io.savebinary.
Load a numpy binary file (``.npy``) or archive (``.npz``) created by
:func:`tabular.io.savebinary`.
The data and associated data type (e.g. `dtype`, including if given, column
names) are load... |
Save a tabarray to a numpy binary file or archive.
Save a tabarray to a numpy binary file (``.npy``) or archive
(``.npz``) that can be loaded by :func:`tabular.io.savebinary`.
The ``.npz`` file is a zipped archive created using
:func:`numpy.savez` and containing one or more ``.npy`` files,
whi... | def savebinary(fname, X, savecoloring=True):
"""
Save a tabarray to a numpy binary file or archive.
Save a tabarray to a numpy binary file (``.npy``) or archive
(``.npz``) that can be loaded by :func:`tabular.io.savebinary`.
The ``.npz`` file is a zipped archive created using
:func:`numpy.... |
Parse the types from a structured numpy dtype object.
Return list of string representations of types from a structured numpy
dtype object, e.g. ['int', 'float', 'str'].
Used by :func:`tabular.io.saveSV` to write out type information in the
header.
**Parameters**
**dtype** : numpy dtyp... | def parsetypes(dtype):
"""
Parse the types from a structured numpy dtype object.
Return list of string representations of types from a structured numpy
dtype object, e.g. ['int', 'float', 'str'].
Used by :func:`tabular.io.saveSV` to write out type information in the
header.
**Parameters... |
Threshold a coloring dictionary for a given list of column names.
Threshold `coloring` based on `names`, a list of strings in::
coloring.values()
**Parameters**
**coloring** : dictionary
Hierarchical structure on the columns given in the header of the
file; an attr... | def thresholdcoloring(coloring, names):
"""
Threshold a coloring dictionary for a given list of column names.
Threshold `coloring` based on `names`, a list of strings in::
coloring.values()
**Parameters**
**coloring** : dictionary
Hierarchical structure on the columns g... |
Unified "strong" version of delete (remove) for files and directories.
Unified "strong" version of delete that uses `os.remove` for a file and
`shutil.rmtree` for a directory tree.
**Parameters**
**to_delete** : string
Path to a file or directory.
**See Also:**
`os <h... | def delete(to_delete):
"""
Unified "strong" version of delete (remove) for files and directories.
Unified "strong" version of delete that uses `os.remove` for a file and
`shutil.rmtree` for a directory tree.
**Parameters**
**to_delete** : string
Path to a file or directory.... |
"Strong" directory maker.
"Strong" version of `os.mkdir`. If `dir_name` already exists, this deletes
it first.
**Parameters**
**dir_name** : string
Path to a file directory that may or may not already exist.
**See Also:**
:func:`tabular.io.delete`,
`os <http... | def makedir(dir_name):
"""
"Strong" directory maker.
"Strong" version of `os.mkdir`. If `dir_name` already exists, this deletes
it first.
**Parameters**
**dir_name** : string
Path to a file directory that may or may not already exist.
**See Also:**
:func:`ta... |
HTTP REQUEST
GET https://api.nasa.gov/planetary/apod
QUERY PARAMETERS
Parameter Type Default Description
date YYYY-MM-DD today The date of the APOD image to retrieve
concept_tags bool False Return an ordered dictionary of concepts from the APOD explanation
api_key string DEMO_KEY api.nasa.gov... | def apod(date=None, concept_tags=None):
'''
HTTP REQUEST
GET https://api.nasa.gov/planetary/apod
QUERY PARAMETERS
Parameter Type Default Description
date YYYY-MM-DD today The date of the APOD image to retrieve
concept_tags bool False Return an ordered dictionary of concepts from the APOD ... |
Decorator to pass community. | def pass_community(f):
"""Decorator to pass community."""
@wraps(f)
def inner(community_id, *args, **kwargs):
c = Community.get(community_id)
if c is None:
abort(404)
return f(c, *args, **kwargs)
return inner |
Decorator to require permission. | def permission_required(action):
"""Decorator to require permission."""
def decorator(f):
@wraps(f)
def inner(community, *args, **kwargs):
permission = current_permission_factory(community, action=action)
if not permission.can():
abort(403)
ret... |
Render a template to a string with the provided item in context. | def format_item(item, template, name='item'):
"""Render a template to a string with the provided item in context."""
ctx = {name: item}
return render_template_to_string(template, **ctx) |
Index page with uploader and list of existing depositions. | def index():
"""Index page with uploader and list of existing depositions."""
ctx = mycommunities_ctx()
p = request.args.get('p', type=str)
so = request.args.get('so', type=str)
page = request.args.get('page', type=int, default=1)
so = so or current_app.config.get('COMMUNITIES_DEFAULT_SORTING_... |
Index page with uploader and list of existing depositions. | def generic_item(community, template, **extra_ctx):
"""Index page with uploader and list of existing depositions."""
# Check existence of community
ctx = mycommunities_ctx()
ctx.update({
'is_owner': community.id_user == current_user.get_id(),
'community': community,
'detail': Tru... |
Create a new community. | def new():
"""Create a new community."""
form = CommunityForm(formdata=request.values)
ctx = mycommunities_ctx()
ctx.update({
'form': form,
'is_new': True,
'community': None,
})
if form.validate_on_submit():
data = copy.deepcopy(form.data)
community_id ... |
Create or edit a community. | def edit(community):
"""Create or edit a community."""
form = EditCommunityForm(formdata=request.values, obj=community)
deleteform = DeleteCommunityForm()
ctx = mycommunities_ctx()
ctx.update({
'form': form,
'is_new': False,
'community': community,
'deleteform': delet... |
Delete a community. | def delete(community):
"""Delete a community."""
deleteform = DeleteCommunityForm(formdata=request.values)
ctx = mycommunities_ctx()
ctx.update({
'deleteform': deleteform,
'is_new': False,
'community': community,
})
if deleteform.validate_on_submit():
community.d... |
Index page with uploader and list of existing depositions.
:param community_id: ID of the community to curate. | def curate(community):
"""Index page with uploader and list of existing depositions.
:param community_id: ID of the community to curate.
"""
if request.method == 'POST':
action = request.json.get('action')
recid = request.json.get('recid')
# 'recid' is mandatory
if not ... |
Returns None if the taxanomy contributes no information to the rooting decision
(e.g. all of the tips are within one genus in the taxonomy)
TODO: need to coordinate with Jim Allman and see if we can
do this in a non- O(nm) manner (where n and m are the # of non-trivial edges in the phylo and taxo tree)... | def evaluate_tree_rooting(nexson, ott, tree_proxy):
"""
Returns None if the taxanomy contributes no information to the rooting decision
(e.g. all of the tips are within one genus in the taxonomy)
TODO: need to coordinate with Jim Allman and see if we can
do this in a non- O(nm) manner (where n ... |
Uses a peyotl wrapper around an Open Tree web service to get a list of trees including values `value` for a given property to be searched on `porperty`.
The oti_wrapper can be None (in which case the default wrapper from peyotl.sugar will be used.
All other arguments correspond to the arguments of the web-serv... | def ot_find_tree(arg_dict, exact=True, verbose=False, oti_wrapper=None):
"""Uses a peyotl wrapper around an Open Tree web service to get a list of trees including values `value` for a given property to be searched on `porperty`.
The oti_wrapper can be None (in which case the default wrapper from peyotl.sugar w... |
The `TreeRef` instance returned by the oti.find_trees(... wrap_response=True)
can be used as an argument to the phylesystem_api.get call.
If you pass in a string (instead of a TreeRef), the string will be interpreted as a study ID | def print_matching_trees(arg_dict, tree_format, exact, verbose):
"""The `TreeRef` instance returned by the oti.find_trees(... wrap_response=True)
can be used as an argument to the phylesystem_api.get call.
If you pass in a string (instead of a TreeRef), the string will be interpreted as a study ID
"""
... |
Resolve etype to an actual type if it is a forward reference | def proc_forward(etype, namespace: Dict[str, Any]):
""" Resolve etype to an actual type if it is a forward reference """
return etype._eval_type(namespace, namespace) if type(etype) is _ForwardRef else etype |
Determine whether etype is a List or other iterable | def is_iterable(etype) -> bool:
""" Determine whether etype is a List or other iterable """
return type(etype) is GenericMeta and issubclass(etype.__extra__, Iterable) |
Determine whether element conforms to at least one of the types in etype
:param element: element to test
:param etype: type to test against
:param namespace: Namespace to use for resolving forward references
:param conforms: conformance test function
:return: True if element conforms to at least on... | def union_conforms(element: Union, etype, namespace: Dict[str, Any], conforms: Callable) -> bool:
""" Determine whether element conforms to at least one of the types in etype
:param element: element to test
:param etype: type to test against
:param namespace: Namespace to use for resolving forward refe... |
This function sets up a command-line option parser and then calls fetch_and_write_mrca
to do all of the real work. | def main(argv):
"""This function sets up a command-line option parser and then calls fetch_and_write_mrca
to do all of the real work.
"""
import argparse
description = 'Uses Open Tree of Life web services to the MRCA for a set of OTT IDs.'
parser = argparse.ArgumentParser(prog='ot-tree-of-life-m... |
Send schema to ledger, then retrieve it as written to the ledger and return it.
If schema already exists on ledger, log error and return schema.
:param schema_data_json: schema data json with name, version, attribute names; e.g.,
::
{
'name': 'my-schema',
... | async def send_schema(self, schema_data_json: str) -> str:
"""
Send schema to ledger, then retrieve it as written to the ledger and return it.
If schema already exists on ledger, log error and return schema.
:param schema_data_json: schema data json with name, version, attribute names; ... |
Assumes that the caller has the _index_lock ! | def _locked_refresh_doc_ids(self):
"""Assumes that the caller has the _index_lock !
"""
d = {}
for s in self._shards:
for k in s.doc_index.keys():
if k in d:
raise KeyError('doc "{i}" found in multiple repos'.format(i=k))
d[... |
This will push the master branch to the remote named `remote_name`
using the mirroring strategy to cut down on locking of the working repo.
`doc_id` is used to determine which shard should be pushed.
if `doc_id` is None, all shards are pushed. | def push_doc_to_remote(self, remote_name, doc_id=None):
"""This will push the master branch to the remote named `remote_name`
using the mirroring strategy to cut down on locking of the working repo.
`doc_id` is used to determine which shard should be pushed.
if `doc_id` is None, all sha... |
This is the heart of the api's __finish_write_verb
It was moved to phylesystem to make it easier to coordinate it
with the caching decisions. We have been debating whether
to cache @id and @dateCreated attributes for the annotations
or cache the whole annotation. Since these ... | def annotate_and_write(self, # pylint: disable=R0201
git_data,
nexson,
doc_id,
auth_info,
adaptor,
annotation,
parent_sha,
... |
Generator that iterates over all detected documents (eg, nexson studies)
and returns the doc object (deserialized from JSON) for each doc.
Order is by shard, but arbitrary within shards.
@TEMP not locked to prevent doc creation/deletion | def iter_doc_objs(self, **kwargs):
"""Generator that iterates over all detected documents (eg, nexson studies)
and returns the doc object (deserialized from JSON) for each doc.
Order is by shard, but arbitrary within shards.
@TEMP not locked to prevent doc creation/deletion
"""
... |
Generator that iterates over all detected documents.
and returns the filesystem path to each doc.
Order is by shard, but arbitrary within shards.
@TEMP not locked to prevent doc creation/deletion | def iter_doc_filepaths(self, **kwargs):
"""Generator that iterates over all detected documents.
and returns the filesystem path to each doc.
Order is by shard, but arbitrary within shards.
@TEMP not locked to prevent doc creation/deletion
"""
for shard in self._shards:
... |
Form data. | def data(self):
"""Form data."""
d = super(CommunityForm, self).data
d.pop('csrf_token', None)
return d |
Validate field identifier. | def validate_identifier(self, field):
"""Validate field identifier."""
if field.data:
field.data = field.data.lower()
if Community.get(field.data, with_deleted=True):
raise validators.ValidationError(
_('The identifier already exists. '
... |
Open with mode=mode and permissions '-rw-rw-r--' group writable is
the default on some systems/accounts, but it is important that it be present on our deployment machine | def open_for_group_write(fp, mode, encoding='utf-8'):
"""Open with mode=mode and permissions '-rw-rw-r--' group writable is
the default on some systems/accounts, but it is important that it be present on our deployment machine
"""
d = os.path.split(fp)[0]
if not os.path.exists(d):
os.makedir... |
Returns the text content of `filepath` | def read_filepath(filepath, encoding='utf-8'):
"""Returns the text content of `filepath`"""
with codecs.open(filepath, 'r', encoding=encoding) as fo:
return fo.read() |
Writes `content` to the `filepath` Creates parent directory
if needed, and uses the specified file `mode` and data `encoding`.
If `group_writeable` is True, the output file will have permissions to be
writable by the group (on POSIX systems) | def write_to_filepath(content, filepath, encoding='utf-8', mode='w', group_writeable=False):
"""Writes `content` to the `filepath` Creates parent directory
if needed, and uses the specified file `mode` and data `encoding`.
If `group_writeable` is True, the output file will have permissions to be
wri... |
Returns the text fetched via http GET from URL, read as `encoding` | def download(url, encoding='utf-8'):
"""Returns the text fetched via http GET from URL, read as `encoding`"""
import requests
response = requests.get(url)
response.encoding = encoding
return response.text |
Writes `blob` as JSON to the filepath `dest` or the filestream `dest` (if it isn't a string)
uses utf-8 encoding if the filepath is given (does not change the encoding if dest is already open). | def write_as_json(blob, dest, indent=0, sort_keys=True):
"""Writes `blob` as JSON to the filepath `dest` or the filestream `dest` (if it isn't a string)
uses utf-8 encoding if the filepath is given (does not change the encoding if dest is already open).
"""
opened_out = False
if is_str_type(dest):
... |
shows JSON indented representation of d | def pretty_dict_str(d, indent=2):
"""shows JSON indented representation of d"""
b = StringIO()
write_pretty_dict_str(b, d, indent=indent)
return b.getvalue() |
writes JSON indented representation of `obj` to `out` | def write_pretty_dict_str(out, obj, indent=2):
"""writes JSON indented representation of `obj` to `out`"""
json.dump(obj,
out,
indent=indent,
sort_keys=True,
separators=(',', ': '),
ensure_ascii=False,
encoding="utf-8") |
study trees should be in {'study_id', 'tree_id'} objects, but
as legacy support we also need to support files that have the format:
pg_315_4246243 # comment | def parse_study_tree_list(fp):
"""study trees should be in {'study_id', 'tree_id'} objects, but
as legacy support we also need to support files that have the format:
pg_315_4246243 # comment
"""
# noinspection PyBroadException
try:
sl = read_as_json(fp)
except:
sl = []
... |
Get JSON dump indentation and separates. | def _format_args():
"""Get JSON dump indentation and separates."""
# Ensure we can run outside a application/request context.
try:
pretty_format = \
current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] and \
not request.is_xhr
except RuntimeError:
pretty_format = Fal... |
Create a community response serializer.
:param serializer: Serializer instance.
:param mimetype: MIME type of response. | def community_responsify(schema_class, mimetype):
"""Create a community response serializer.
:param serializer: Serializer instance.
:param mimetype: MIME type of response.
"""
def view(data, code=200, headers=None, links_item_factory=None,
page=None, urlkwargs=None, links_pagination_f... |
NOT thread-safe!
return stems or stem# where # is the smallest
positive integer for which the path does not exist.
useful for temp dirs where the client code wants an
obvious ordering. | def get_unique_filepath(stem):
"""NOT thread-safe!
return stems or stem# where # is the smallest
positive integer for which the path does not exist.
useful for temp dirs where the client code wants an
obvious ordering.
"""
fp = stem
if os.path.exists(stem):
n = 1
fp = ste... |
Wraps another Exception in an InternalError.
:param exc_info: The exception info for the wrapped exception
:type exc_info: (type, object, traceback)
:type json_encoder: json.JSONEncoder
:type debug_url: str | None
:rtype: InternalError
.. versionadded:: 0.1.0
..... | def from_error(exc_info, json_encoder, debug_url=None):
"""Wraps another Exception in an InternalError.
:param exc_info: The exception info for the wrapped exception
:type exc_info: (type, object, traceback)
:type json_encoder: json.JSONEncoder
:type debug_url: str | None
... |
This should only be called by propinquity - other code should be treating theses
filenames (and the keys that are based on them) as opaque strings.
Takes a filename (or key if strip_extension is False), returns (study_id, tree_id)
propinquity provides a map to look up the study ID and tree ID (and git SHA... | def propinquity_fn_to_study_tree(inp_fn, strip_extension=True):
"""This should only be called by propinquity - other code should be treating theses
filenames (and the keys that are based on them) as opaque strings.
Takes a filename (or key if strip_extension is False), returns (study_id, tree_id)
prop... |
Return whether the cache contains a schema for the input key, sequence number, or schema identifier.
:param index: schema key, sequence number, or sequence identifier
:return: whether the cache contains a schema for the input index | def contains(self, index: Union[SchemaKey, int, str]) -> bool:
"""
Return whether the cache contains a schema for the input key, sequence number, or schema identifier.
:param index: schema key, sequence number, or sequence identifier
:return: whether the cache contains a schema for the ... |
Take schemata from incoming list representation as schemata() returns, unless
cache already has schema for an incoming schema sequence number.
:param schemata: list of schema objects | def feed(self, schemata: list) -> None:
"""
Take schemata from incoming list representation as schemata() returns, unless
cache already has schema for an incoming schema sequence number.
:param schemata: list of schema objects
"""
LOGGER.debug('SchemaCache.feed >>> sche... |
Cull cache entry frame list to size, favouring most recent query time.
:param delta: True to operate on rev reg deltas, False for rev reg states | def cull(self, delta: bool) -> None:
"""
Cull cache entry frame list to size, favouring most recent query time.
:param delta: True to operate on rev reg deltas, False for rev reg states
"""
LOGGER.debug('RevoCacheEntry.cull >>> delta: %s', delta)
rr_frames = self.rr_de... |
Return default non-revocation interval from latest 'to' times on delta frames
of revocation cache entries on indices stemming from input cred def id.
Compute the 'from'/'to' values as the earliest/latest 'to' values of all
cached delta frames on all rev reg ids stemming from the input cred def ... | def dflt_interval(self, cd_id: str) -> (int, int):
"""
Return default non-revocation interval from latest 'to' times on delta frames
of revocation cache entries on indices stemming from input cred def id.
Compute the 'from'/'to' values as the earliest/latest 'to' values of all
c... |
Create symbolic link to tails file named tails_hash for rev reg id rr_id.
:param rr_id: rev reg id
:param tails_hash: hash of tails file, serving as file name | def associate(base_dir: str, rr_id: str, tails_hash: str) -> None:
"""
Create symbolic link to tails file named tails_hash for rev reg id rr_id.
:param rr_id: rev reg id
:param tails_hash: hash of tails file, serving as file name
"""
cd_id = rev_reg_id2cred_def_id(rr_id... |
Parse and update from archived cache files. Only accept new content;
do not overwrite any existing cache content.
:param base_dir: archive base directory
:param timestamp: epoch time of cache serving as subdirectory, default most recent
:return: epoch time of cache serving as subdirecto... | def parse(base_dir: str, timestamp: int = None) -> int:
"""
Parse and update from archived cache files. Only accept new content;
do not overwrite any existing cache content.
:param base_dir: archive base directory
:param timestamp: epoch time of cache serving as subdirectory, de... |
Return correct subdirectory of input base dir for artifacts corresponding to input rev reg id.
:param base_dir: base directory for tails files, thereafter split by cred def id
:param rr_id: rev reg id | def dir(base_dir: str, rr_id: str) -> str:
"""
Return correct subdirectory of input base dir for artifacts corresponding to input rev reg id.
:param base_dir: base directory for tails files, thereafter split by cred def id
:param rr_id: rev reg id
"""
return join(base_d... |
Get, from the specified directory, the path to the tails file associated with
the input revocation registry identifier, or None for no such file.
:param base_dir: base directory for tails files, thereafter split by cred def id
:param rr_id: rev reg id
:return: (stringified) path to tail... | def linked(base_dir: str, rr_id: str) -> str:
"""
Get, from the specified directory, the path to the tails file associated with
the input revocation registry identifier, or None for no such file.
:param base_dir: base directory for tails files, thereafter split by cred def id
:p... |
Return set of all paths to symbolic links (rev reg ids) associating
their respective tails files, in specified base tails directory, on
input issuer DID if specified.
:param base_dir: base directory for tails files, thereafter split by cred def id
:param issuer_did: issuer DID of intere... | def links(base_dir: str, issuer_did: str = None) -> set:
"""
Return set of all paths to symbolic links (rev reg ids) associating
their respective tails files, in specified base tails directory, on
input issuer DID if specified.
:param base_dir: base directory for tails files, th... |
Return all paths to tails files, in specified tails base directory (recursively),
without symbolic links associating revocation registry identifiers.
At an Issuer, tails files should not persist long without revocation registry identifier
association via symbolic link. At a HolderProver, a newl... | def unlinked(base_dir: str) -> set:
"""
Return all paths to tails files, in specified tails base directory (recursively),
without symbolic links associating revocation registry identifiers.
At an Issuer, tails files should not persist long without revocation registry identifier
... |
Return the next tag name available for a new rev reg id on input cred def id in base directory,
and suggested size of associated rev reg.
:param base_dir: base directory for tails files, thereafter split by cred def id
:param cd_id: credential definition identifier of interest
:return: ... | def next_tag(base_dir: str, cd_id: str) -> (str, int):
"""
Return the next tag name available for a new rev reg id on input cred def id in base directory,
and suggested size of associated rev reg.
:param base_dir: base directory for tails files, thereafter split by cred def id
:... |
Return the current revocation registry identifier for
input credential definition identifier, in input directory.
Raise AbsentTails if no corresponding tails file, signifying no such revocation registry defined.
:param base_dir: base directory for tails files, thereafter split by cred def id
... | def current_rev_reg_id(base_dir: str, cd_id: str) -> str:
"""
Return the current revocation registry identifier for
input credential definition identifier, in input directory.
Raise AbsentTails if no corresponding tails file, signifying no such revocation registry defined.
:par... |
Accessor for (stringified) path to current tails file.
:return: (stringified) path to current tails file. | def path(self) -> str:
"""
Accessor for (stringified) path to current tails file.
:return: (stringified) path to current tails file.
"""
cfg = json.loads(self._tails_cfg_json)
return join(cfg['base_dir'], cfg['file']) |
Function returns indices that contain non-noisy genes as an integer array
:param rawArray: numpy ndarray of data set
:return nnGenes : numpy ndarray of non-noise gene indices | def parseNoise(rawArray):
'''
Function returns indices that contain non-noisy genes as an integer array
:param rawArray: numpy ndarray of data set
:return nnGenes : numpy ndarray of non-noise gene indices
'''
nnGenes=[]
for i in range(0,(rawArray.shape[1])): #Checks all genes
count... |
Function returns ndarray of gene expression values from ndarray of unmodified data set and ndarray of gene indices
:param unparsedArr: numpy ndarray of unmodified data set
:param nnGeneIndex: numpy ndarray of indices of genes of interest
:return nnGeneExp: numpy ndarray of data set including all cells and ... | def mkIndexedArr(unparsedArr,nnGeneIndex):
'''
Function returns ndarray of gene expression values from ndarray of unmodified data set and ndarray of gene indices
:param unparsedArr: numpy ndarray of unmodified data set
:param nnGeneIndex: numpy ndarray of indices of genes of interest
:return nnGeneE... |
Function returns an ndarray by performing a pointwise inverse hyperbolic sine transformation on the input ndarray
:param inputArray: ndarray of gene expression data in raw count or RPKM format
:param contstant: some constant to normalize for total read count number
:return transformed: ndarray of transfor... | def pwArcsinh(inputArray,constant):
'''
Function returns an ndarray by performing a pointwise inverse hyperbolic sine transformation on the input ndarray
:param inputArray: ndarray of gene expression data in raw count or RPKM format
:param contstant: some constant to normalize for total read count nu... |
Function returns an adjacency matrix based on the euclidean distance of each gene's expression across all cells
:param traj_dist: ndarray of euclidean distances
:param k: int of the minimum number of connections needed for a minimally connected graph, calculated by min_conn_k()
:return adj_mat: ndarray repr... | def adaptive_knn_graph(traj_dist,k):
'''
Function returns an adjacency matrix based on the euclidean distance of each gene's expression across all cells
:param traj_dist: ndarray of euclidean distances
:param k: int of the minimum number of connections needed for a minimally connected graph, calculated... |
Function returns the minimum number of connections, k, that are required to form a fully connected graph based gene expression data
:param traj_exp: ndarray representing gene expression
:return k: int of the minimum number of connections needed for a minimally connected graph | def min_conn_k(traj_exp):
'''
Function returns the minimum number of connections, k, that are required to form a fully connected graph based gene expression data
:param traj_exp: ndarray representing gene expression
:return k: int of the minimum number of connections needed for a minimally connected gra... |
Function returns the sum of squared differences in the expression of a gene, per cell
:param i: int representing the index of the cell being processed
:param j: int representing the index of the gene being processed
:param traj_exp: ndarray representing gene expression
:param adj_mat: ndarray represent... | def dev_ij(i,j,traj_exp,adj_mat): #takes adjacency matrix and raw expression data
'''
Function returns the sum of squared differences in the expression of a gene, per cell
:param i: int representing the index of the cell being processed
:param j: int representing the index of the gene being processed
... |
Function returns an ndarray of ratios calculated by dividing the summed neighborhood variances by the global variance
:param traj_exp: ndarray representing gene expression
:param adj_mat: ndarray representing the calculated adjacency matrix
:return val: ndarray representing the ratio of summed neighborhood ... | def selection_val(traj_exp,adj_mat):
'''
Function returns an ndarray of ratios calculated by dividing the summed neighborhood variances by the global variance
:param traj_exp: ndarray representing gene expression
:param adj_mat: ndarray representing the calculated adjacency matrix
:return val: ndarr... |
Wrapper function to perform neighborhood variance based feature selection, will throw error if input is not ndarray
:param embedding: ndarray representing gene expression, consists of cells as rows and genes as columns
:return genes_mat: ndarray of selected genes | def select_genes(embedding):
'''
Wrapper function to perform neighborhood variance based feature selection, will throw error if input is not ndarray
:param embedding: ndarray representing gene expression, consists of cells as rows and genes as columns
:return genes_mat: ndarray of selected genes
'''... |
Function to generate randomly sampled datasets with replacement. This is in the context of cells in the native dataset
which are the rows of the matrix
:param partitions: int designating the number of evenly spaced sample sizes to randomly select from the native dataset
:param dataset: DataFrame of the nati... | def subsample(partitions,dataset,seed):
'''
Function to generate randomly sampled datasets with replacement. This is in the context of cells in the native dataset
which are the rows of the matrix
:param partitions: int designating the number of evenly spaced sample sizes to randomly select from the nati... |
Wrapper function that generates replicate datasets using the subsampling function.
:param repNumber: int number of replicates to generate based on the parameters given
:param partitions: int designating the number of evenly spaced sample sizes to randomly select from the native dataset
:param dataset: DataF... | def subsampleReplicates(repNumber,partitions,dataset,seed):
'''
Wrapper function that generates replicate datasets using the subsampling function.
:param repNumber: int number of replicates to generate based on the parameters given
:param partitions: int designating the number of evenly spaced sample si... |
Function to write dictionary data, from subsampleReplicates, to file an hdf5 file.
:param dictionary: nested dictionary returned by subsampleReplicates
:param replicateKey: string designating the replicate written to file
:param outFileName: string defining the hdf5 filename | def dictToFile(dictionary,replicateKey,outFileName):
'''
Function to write dictionary data, from subsampleReplicates, to file an hdf5 file.
:param dictionary: nested dictionary returned by subsampleReplicates
:param replicateKey: string designating the replicate written to file
:param outFileName: ... |
generator over all otus in all otus group elements.
yields a tuple of 3 items:
otus group ID,
otu ID,
the otu obj | def iter_otus(nexson, nexson_version=None):
"""generator over all otus in all otus group elements.
yields a tuple of 3 items:
otus group ID,
otu ID,
the otu obj
"""
if nexson_version is None:
nexson_version = detect_nexson_version(nexson)
if not _is_by_id_hbf(nexson_v... |
generator over all trees in all trees elements.
yields a tuple of 3 items:
trees element ID,
tree ID,
the tree obj | def iter_trees(nexson, nexson_version=None):
"""generator over all trees in all trees elements.
yields a tuple of 3 items:
trees element ID,
tree ID,
the tree obj
"""
if nexson_version is None:
nexson_version = detect_nexson_version(nexson)
nex = get_nexml_el(nexson)
... |
Takes a v1.2 otuById dict and, for every otu,
checks if ot:originalLabel exists. If it does not,
but @label does, then ot:originalLabel is set to
@label and @label is deleted. | def label_to_original_label_otu_by_id(otu_by_id):
"""Takes a v1.2 otuById dict and, for every otu,
checks if ot:originalLabel exists. If it does not,
but @label does, then ot:originalLabel is set to
@label and @label is deleted.
"""
for val in otu_by_id.values():
orig = val.get('^ot:orig... |
Takes a nexson object:
1. merges trees elements 2 - # trees into the first trees element.,
2. merges otus elements 2 - # otus into the first otus element.
3. if there is no ot:originalLabel field for any otu,
it sets that field based on @label and deletes @label
4. merges an ... | def merge_otus_and_trees(nexson_blob):
"""Takes a nexson object:
1. merges trees elements 2 - # trees into the first trees element.,
2. merges otus elements 2 - # otus into the first otus element.
3. if there is no ot:originalLabel field for any otu,
it sets that field based on @... |
Returns the nexml2json attribute or the default code for badgerfish | def detect_nexson_version(blob):
"""Returns the nexml2json attribute or the default code for badgerfish"""
n = get_nexml_el(blob)
assert isinstance(n, dict)
return n.get('@nexml2json', BADGER_FISH_NEXSON_VERSION) |
Returns d[k] or [d[k]] if the value is not a list | def _index_list_of_values(d, k):
"""Returns d[k] or [d[k]] if the value is not a list"""
v = d[k]
if isinstance(v, list):
return v
return [v] |
Like _index_list_of_values, but uses get to access and
returns an empty list if the key is absent.
Returns d[k] or [d[k]] if the value is not a list | def _get_index_list_of_values(d, k, def_value=None):
"""Like _index_list_of_values, but uses get to access and
returns an empty list if the key is absent.
Returns d[k] or [d[k]] if the value is not a list"""
v = d.get(k, def_value)
if v is None:
return []
if isinstance(v, list):
... |
Adds the `k`->`v` mapping to `d`, but if a previous element exists it changes
the value of for the key to list.
This is used in the BadgerFish mapping convention.
This is a simple multi-dict that is only suitable when you know that you'll never
store a list or `None` as a value in the dict. | def _add_value_to_dict_bf(d, k, v):
"""Adds the `k`->`v` mapping to `d`, but if a previous element exists it changes
the value of for the key to list.
This is used in the BadgerFish mapping convention.
This is a simple multi-dict that is only suitable when you know that you'll never
store a list o... |
Like _add_value_to_dict_bf but will not add v if another
element in under key `k` has the same value. | def _add_uniq_value_to_dict_bf(d, k, v):
"""Like _add_value_to_dict_bf but will not add v if another
element in under key `k` has the same value.
"""
prev = d.get(k)
if prev is None:
d[k] = v
elif isinstance(prev, list):
if not isinstance(v, list):
v = [v]
for... |
Debugging helper. Prints out `el` contents. | def _debug_dump_dom(el):
"""Debugging helper. Prints out `el` contents."""
import xml.dom.minidom
s = [el.nodeName]
att_container = el.attributes
for i in range(att_container.length):
attr = att_container.item(i)
s.append(' @{a}="{v}"'.format(a=attr.name, v=attr.value))
for c in... |
Removes the @about key from the `obj` dict if that value refers to the
dict's '@id' | def _cull_redundant_about(obj):
"""Removes the @about key from the `obj` dict if that value refers to the
dict's '@id'
"""
about_val = obj.get('@about')
if about_val:
id_val = obj.get('@id')
if id_val and (('#' + id_val) == about_val):
del obj['@about'] |
Returns 'xsd:string' or a more specific type for a <meta datatype="XYZ"...
syntax using introspection. | def _python_instance_to_nexml_meta_datatype(v):
"""Returns 'xsd:string' or a more specific type for a <meta datatype="XYZ"...
syntax using introspection.
"""
if isinstance(v, bool):
return 'xsd:boolean'
if is_int_type(v):
return 'xsd:int'
if isinstance(v, float):
return '... |
Convert to a BadgerFish-style dict for addition to a dict suitable for
addition to XML tree or for v1.0 to v0.0 conversion. | def _convert_hbf_meta_val_for_xml(key, val):
"""Convert to a BadgerFish-style dict for addition to a dict suitable for
addition to XML tree or for v1.0 to v0.0 conversion."""
if isinstance(val, list):
return [_convert_hbf_meta_val_for_xml(key, i) for i in val]
is_literal = True
content = Non... |
Returns the $ value of the first meta element with
the @property that matches @prop_name (or None). | def find_val_for_first_bf_l_meta(d, prop_name):
"""Returns the $ value of the first meta element with
the @property that matches @prop_name (or None).
"""
m_list = d.get('meta')
if not m_list:
return None
if not isinstance(m_list, list):
m_list = [m_list]
for m_el in m_list:
... |
Returns the $ value of the first meta element with
the @property that matches @prop_name (or None). | def find_nested_meta_first_bf(d, prop_name):
"""Returns the $ value of the first meta element with
the @property that matches @prop_name (or None).
"""
m_list = d.get('meta')
if not m_list:
return None
if not isinstance(m_list, list):
m_list = [m_list]
for m_el in m_list:
... |
Returns obj. for badgerfish and val for hbf. Appropriate for nested literals | def find_nested_meta_first(d, prop_name, version):
"""Returns obj. for badgerfish and val for hbf. Appropriate for nested literals"""
if _is_badgerfish_version(version):
return find_nested_meta_first_bf(d, prop_name)
p = '^' + prop_name
return d.get(p) |
Format
Requests are of the form:
http://asterank.com/api/asterank?query={query}&limit={limit}
Response data formats are largely derived from NASA/JPL's Small Body Database query browser. Exceptions to this are the delta-v field (dv), the mass field (GM), and the normalized spectral type field (spec). Addit... | def asterank(query=None, limit=None):
'''
Format
Requests are of the form:
http://asterank.com/api/asterank?query={query}&limit={limit}
Response data formats are largely derived from NASA/JPL's Small Body Database query browser. Exceptions to this are the delta-v field (dv), the mass field (GM), an... |
Encode credential attribute value, leaving any (stringified) int32 alone: indy-sdk predicates
operate on int32 values properly only when their encoded values match their raw values.
To disambiguate for decoding, the operation reserves a sentinel for the null value and otherwise adds
2**31 to any non-trivia... | def encode(raw: Any) -> str:
"""
Encode credential attribute value, leaving any (stringified) int32 alone: indy-sdk predicates
operate on int32 values properly only when their encoded values match their raw values.
To disambiguate for decoding, the operation reserves a sentinel for the null value and o... |
Decode encoded credential attribute value.
:param value: numeric string to decode
:return: decoded value, stringified if original was neither str, bool, int, nor float | def decode(value: str) -> Union[str, None, bool, int, float]:
"""
Decode encoded credential attribute value.
:param value: numeric string to decode
:return: decoded value, stringified if original was neither str, bool, int, nor float
"""
assert value.isdigit() or value[0] == '-' and value[1:].... |
Log txt (if any) to the log file (if any). Return value indicates whether it is ok to terminate on the first
error or whether we need to continue processing.
:param txt: text to log.
:return: True if we aren't logging, False if we are. | def log(self, txt: str) -> bool:
""" Log txt (if any) to the log file (if any). Return value indicates whether it is ok to terminate on the first
error or whether we need to continue processing.
:param txt: text to log.
:return: True if we aren't logging, False if we are.
"""
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.