INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
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. | 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... |
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. | 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... |
Wraps another Exception in an InternalError. | 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
... |
Return whether the cache contains a schema for the input key sequence number or schema identifier. | 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. | 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. | 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. | 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... |
Parse and update from archived cache files. Only accept new content ; do not overwrite any existing cache content. | 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... |
Create symbolic link to tails file named tails_hash for rev reg id rr_id. | 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... |
Return correct subdirectory of input base dir for artifacts corresponding to input 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. | 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. | 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. | 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. | 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. | 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. | 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 expression da... | 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 transformed inputArray | 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 representing the... | 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 representing the calculated... | 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 variances by... | 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 native dataset c... | 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: DataFrame of the ... | 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 | 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 otu elements using the rule: A. treat ( ottId... | 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. | 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 | 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 | 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 | 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: | 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. | 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. | 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. | 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.
"""
... |
An attribute with type None is equivalent to an absent attribute.: param d: Object with attributes: return: Object dictionary w/ Nones and underscores removed | def _strip_nones(d: Dict[str, Any])-> Dict[str, Any]:
"""
An attribute with type None is equivalent to an absent attribute.
:param d: Object with attributes
:return: Object dictionary w/ Nones and underscores removed
"""
return OrderedDict({k: None if isinstance(v, JSGNul... |
Return a serializable version of obj. Overrides JsonObj _default method: param obj: Object to be serialized: return: Serialized version of obj | def _default(self, obj: object):
""" Return a serializable version of obj. Overrides JsonObj _default method
:param obj: Object to be serialized
:return: Serialized version of obj
"""
return None if obj is JSGNull else obj.val if type(obj) is AnyType else \
JSGObject.... |
For doc_id returns a list of: [ 0 ] the repo name and [ 1 ] the path from the repo to the doc file. This is useful because ( if you know the remote ) it lets you construct the full path. | def get_repo_and_path_fragment(self, doc_id):
"""For `doc_id` returns a list of:
[0] the repo name and,
[1] the path from the repo to the doc file.
This is useful because
(if you know the remote), it lets you construct the full path.
"""
shard = self.get_s... |
Returns a GitHub URL for the doc in question ( study collection... ) | def get_public_url(self, doc_id, branch='master'):
"""Returns a GitHub URL for the doc in question (study, collection, ...)
"""
name, path_frag = self.get_repo_and_path_fragment(doc_id)
return 'https://raw.githubusercontent.com/OpenTreeOfLife/' + name + '/' + branch + '/' + path_frag |
Validates that the given parameters are exactly the method s declared parameters. | def validate_params_match(method, parameters):
"""Validates that the given parameters are exactly the method's declared parameters.
:param method: The method to be called
:type method: function
:param parameters: The parameters to use in the call
:type parameters: dict[str, object] | list[object]
... |
Checks that the given parameters have the correct types. | def check_types(parameters, parameter_types, strict_floats):
"""Checks that the given parameters have the correct types.
:param parameters: List of (name, value) pairs of the given parameters
:type parameters: dict[str, object]
:param parameter_types: Parameter type by name.
:type parameter_types: ... |
Checks that exactly the given parameter names have declared types. | def check_type_declaration(parameter_names, parameter_types):
"""Checks that exactly the given parameter names have declared types.
:param parameter_names: The names of the parameters in the method declaration
:type parameter_names: list[str]
:param parameter_types: Parameter type by name
:type par... |
Checks that the given return value has the correct type. | def check_return_type(value, expected_type, strict_floats):
"""Checks that the given return value has the correct type.
:param value: Value returned by the method
:type value: object
:param expected_type: Expected return type
:type expected_type: type
:param strict_floats: If False, treat integ... |
Returns a dictionary of name - > filepath name is the repo name based on the dir name ( not the get repo ). It is not terribly useful but it is nice to have so that any mirrored repo directory can use the same naming convention. filepath will be the full path to the repo directory ( it will end in name ) | def get_repos(par_list=None, **kwargs):
"""Returns a dictionary of name -> filepath
`name` is the repo name based on the dir name (not the get repo). It is not
terribly useful, but it is nice to have so that any mirrored repo directory can
use the same naming convention.
`filepath` will be t... |
Searchers for *. json files in this repo and returns a map of study id == > ( tag dir study filepath ) where tag is typically the shard name | def create_id2study_info(path, tag):
"""Searchers for *.json files in this repo and returns
a map of study id ==> (`tag`, dir, study filepath)
where `tag` is typically the shard name
"""
d = {}
for triple in os.walk(path):
root, files = triple[0], triple[2]
for filename in files:... |
Only intended to be called by the Phylesystem singleton. | def _make_phylesystem_cache_region(**kwargs):
"""Only intended to be called by the Phylesystem singleton.
"""
global _CACHE_REGION_CONFIGURED, _REGION
if _CACHE_REGION_CONFIGURED:
return _REGION
_CACHE_REGION_CONFIGURED = True
try:
# noinspection PyPackageRequirements
fro... |
This function sets up a command - line option parser and then calls match_and_print to do all of the real work. | def main(argv):
"""This function sets up a command-line option parser and then calls match_and_print
to do all of the real work.
"""
import argparse
description = 'Uses Open Tree of Life web services to find information for each OTT ID.'
parser = argparse.ArgumentParser(prog='ot-taxon-info', des... |
Takes an obj that is a NexSON object. warning_codes_to_skip is None or an iterable collection of integers that correspond to facets of NexsonWarningCodes. Warnings associated with any code in the list will be suppressed. retain_deprecated if False then obj may be modified to replace deprecated constructs with new synta... | def validate_nexson(obj, warning_codes_to_skip=None, retain_deprecated=True, **kwargs):
"""Takes an `obj` that is a NexSON object.
`warning_codes_to_skip` is None or an iterable collection of integers
that correspond to facets of NexsonWarningCodes. Warnings associated
with any code in the list ... |
Returns three objects: an annotation dict ( NexSON formmatted ) the validation_log object created when NexSON validation was performed and the object of class NexSON which was created from nexson. This object may alias parts of the nexson dict that is passed in as an argument. | def ot_validate(nexson, **kwargs):
"""Returns three objects:
an annotation dict (NexSON formmatted),
the validation_log object created when NexSON validation was performed, and
the object of class NexSON which was created from nexson. This object may
alias parts of the nexson dic... |
In order to use this capability queries can be issued to the system with the following URI format: GET/ xml - api/ id_parameter Parameter Required? Value Description id_parameter Yes Type: String Default: None The id value of the TechPort record. TechPort values range from 0 - 20000. Not all values will yield results. ... | def techport(Id):
'''
In order to use this capability, queries can be issued to the system with the following URI
format:
GET /xml-api/id_parameter
Parameter Required? Value Description
id_parameter Yes Type: String
Default: None
The id value of the TechPort record.
TechPort values r... |
Not locked! | def get_HEAD_SHA1(git_dir):
"""Not locked!
"""
head_file = os.path.join(git_dir, 'HEAD')
with open(head_file, 'r') as hf:
head_contents = hf.read().strip()
assert head_contents.startswith('ref: ')
ref_filename = head_contents[5:] # strip off "ref: "
real_ref = os.path.join(git_dir, ... |
Returns doc_dir and doc_filepath for doc_id. | def path_for_doc(self, doc_id):
"""Returns doc_dir and doc_filepath for doc_id.
"""
full_path = self.path_for_doc_fn(self.repo, doc_id)
# _LOG.debug('>>>>>>>>>> GitActionBase.path_for_doc_fn: {}'.format(self.path_for_doc_fn))
# _LOG.debug('>>>>>>>>>> GitActionBase.path_for_doc re... |
Return the current branch name | def current_branch(self):
"""Return the current branch name"""
branch_name = git(self.gitdir, self.gitwd, "symbolic-ref", "HEAD")
return branch_name.replace('refs/heads/', '').strip() |
Returns true or false depending on if a branch exists | def branch_exists(self, branch):
"""Returns true or false depending on if a branch exists"""
try:
git(self.gitdir, self.gitwd, "rev-parse", branch)
except sh.ErrorReturnCode:
return False
return True |
fetch from a remote | def fetch(self, remote='origin'):
"""fetch from a remote"""
git(self.gitdir, "fetch", remote, _env=self.env()) |
Return a dict representation of this file s commit history | def get_version_history_for_file(self, filepath):
""" Return a dict representation of this file's commit history
This uses specially formatted git-log output for easy parsing, as described here:
http://blog.lost-theory.org/post/how-to-parse-git-log-output/
For a full list of availab... |
Low level function used internally when you have an absolute filepath to add and commit | def _add_and_commit(self, doc_filepath, author, commit_msg):
"""Low level function used internally when you have an absolute filepath to add and commit"""
try:
git(self.gitdir, self.gitwd, "add", doc_filepath)
git(self.gitdir, self.gitwd, "commit", author=author, message=commit_m... |
Merge the the given WIP branch to master ( or destination if specified ) | def merge(self, branch, destination="master"):
"""
Merge the the given WIP branch to master (or destination, if specified)
If the merge fails, the merge will be aborted
and then a MergeException will be thrown. The
message of the MergeException will be the
"git status" o... |
Return the blob [ 0 ] contents of the given doc_id blob [ 1 ] the SHA1 of the HEAD of branch ( or commit_sha ) blob [ 2 ] dictionary of WIPs for this doc. If the doc_id does not exist it returns the empty string. If commit_sha is provided that will be checked out and returned. otherwise the branch will be checked out. | def return_document(self, doc_id, branch='master', commit_sha=None, return_WIP_map=False):
"""Return the
blob[0] contents of the given doc_id,
blob[1] the SHA1 of the HEAD of branch (or `commit_sha`)
blob[2] dictionary of WIPs for this doc.
If the doc_id does not exis... |
Returns the set of documents that have changed on the master since commit ancestral_commit_sha or False ( on an error ) | def _get_changed_docs(self,
ancestral_commit_sha,
doc_id_from_repo_path,
doc_ids_to_check=None):
"""Returns the set of documents that have changed on the master since
commit `ancestral_commit_sha` or `False` (on an error)
... |
Remove a document Remove a document on the given branch and attribute the commit to author. Returns the SHA of the commit on branch. | def _remove_document(self, gh_user, doc_id, parent_sha, author, commit_msg=None):
"""Remove a document
Remove a document on the given branch and attribute the commit to author.
Returns the SHA of the commit on branch.
"""
# _LOG.debug("@@@@@@@@ GitActionBase._remove_document, doc... |
Given a document id temporary filename of content branch and auth_info | def write_document(self, gh_user, doc_id, file_content, branch, author, commit_msg=None):
"""Given a document id, temporary filename of content, branch and auth_info
Deprecated but needed until we merge api local-dep to master...
"""
parent_sha = None
fc = tempfile.NamedTempora... |
Given a doc_id temporary filename of content branch and auth_info | def write_doc_from_tmpfile(self,
doc_id,
tmpfi,
parent_sha,
auth_info,
commit_msg='',
doctype_display_name="document"):
"""Giv... |
Inefficient comparison of src and dest dicts. Recurses through dict and lists. returns None if there is no difference and a DictDiffObject of there are differences ** kwargs can contain: wrap_dict_in_list default False. If True and one value is present as a list and the other is a dict then the dict will be converted t... | def create(src, dest, **kwargs):
"""Inefficient comparison of src and dest dicts.
Recurses through dict and lists.
returns None if there is no difference and a
DictDiffObject of there are differences
**kwargs can contain:
wrap_dict_in_list default False. If True and o... |
Inefficient comparison of src and dest dicts. Recurses through dict and lists. returns ( is_identical modifications additions deletions ) where each is_identical is a boolean True if the dicts have contents that compare equal. and the other three are dicts: attributes both but with different values attributes in dest b... | def create(src, dest, **kwargs):
"""Inefficient comparison of src and dest dicts.
Recurses through dict and lists.
returns (is_identical, modifications, additions, deletions)
where each
is_identical is a boolean True if the dicts have
contents that compare equ... |
performs taxonomic name resolution. See https:// github. com/ OpenTreeOfLife/ opentree/ wiki/ Open - Tree - of - Life - APIs#match_names with the exception that ids in the API call is referred has the name id_list in this function. The most commonly used kwargs are: - context_name = <name > ( see contexts and infer_con... | def match_names(self, *valist, **kwargs):
"""performs taxonomic name resolution.
See https://github.com/OpenTreeOfLife/opentree/wiki/Open-Tree-of-Life-APIs#match_names
with the exception that "ids" in the API call is referred has the name "id_list" in this function.
The most commonly use... |
Remove an amendment Given a amendment_id branch and optionally an author remove an amendment on the given branch and attribute the commit to author. Returns the SHA of the commit on branch. | def remove_amendment(self, first_arg, sec_arg, third_arg, fourth_arg=None, commit_msg=None):
"""Remove an amendment
Given a amendment_id, branch and optionally an
author, remove an amendment on the given branch
and attribute the commit to author.
Returns the SHA of the commit on ... |
Given an amendment_id temporary filename of content branch and auth_info | def write_amendment(self, amendment_id, file_content, branch, author):
"""Given an amendment_id, temporary filename of content, branch and auth_info
Deprecated but needed until we merge api local-dep to master...
"""
gh_user = branch.split('_amendment_')[0]
msg = "Update Amendm... |
Given an amendment_id temporary filename of content branch and auth_info | def write_amendment_from_tmpfile(self, amendment_id, tmpfi, parent_sha, auth_info, commit_msg=''):
"""Given an amendment_id, temporary filename of content, branch and auth_info
"""
return self.write_doc_from_tmpfile(amendment_id,
tmpfi,
... |
arrayExpr: OBRACKET valueType ( BAR valueType ) * ebnfSuffix? CBRACKET ; | def visitArrayExpr(self, ctx: jsgParser.ArrayExprContext):
""" arrayExpr: OBRACKET valueType (BAR valueType)* ebnfSuffix? CBRACKET; """
from pyjsg.parser_impl.jsg_ebnf_parser import JSGEbnf
from pyjsg.parser_impl.jsg_valuetype_parser import JSGValueType
self._types = [JSGValueType(self.... |
For doc_id returns the path from the repo to the doc file. This is useful because ( if you know the remote ) it lets you construct the full path. | def get_rel_path_fragment(self, doc_id):
"""For `doc_id` returns the path from the
repo to the doc file. This is useful because
(if you know the remote), it lets you construct the full path.
"""
with self._index_lock:
r = self._doc_index[doc_id]
fp = r[-1]
... |
Returns a pair: ( doc_id absolute filepath of document file ) for each document in this repository. Order is arbitrary. | def iter_doc_filepaths(self, **kwargs): # pylint: disable=W0613
"""Returns a pair: (doc_id, absolute filepath of document file)
for each document in this repository.
Order is arbitrary.
"""
with self._index_lock:
for doc_id, info in self._doc_index.items():
... |
Returns a pair: ( doc_id nexson_blob ) for each document in this repository. Order is arbitrary. | def iter_doc_objs(self, **kwargs):
"""Returns a pair: (doc_id, nexson_blob)
for each document in this repository.
Order is arbitrary.
"""
_LOG = get_logger('TypeAwareGitShard')
try:
for doc_id, fp in self.iter_doc_filepaths(**kwargs):
if not se... |
Generic configuration may be overridden by type - specific version | def get_configuration_dict(self, secret_attrs=False):
"""Generic configuration, may be overridden by type-specific version"""
rd = {'name': self.name,
'path': self.path,
'git_dir': self.git_dir,
'assumed_doc_version': self.assumed_doc_version,
'doc... |
This will force the current branch to master! | def _read_master_branch_resource(self, fn, is_json=False):
"""This will force the current branch to master! """
with self._master_branch_repo_lock:
ga = self._create_git_action_for_global_resource()
with ga.lock():
ga.checkout_master()
if os.path.e... |
This will force the current branch to master! | def _write_master_branch_resource(self, content, fn, commit_msg, is_json=False):
"""This will force the current branch to master! """
# TODO: we might want this to push, but currently it is only called in contexts in which
# we are about to push anyway (document creation)
with self._mast... |
Create a record inclusion request to a community. | def create(cls, community, record, user=None, expires_at=None,
notify=True):
"""Create a record inclusion request to a community.
:param community: Community object.
:param record: Record API object.
:param expires_at: Time after which the request expires and shouldn't
... |
Get an inclusion request. | def get(cls, community_id, record_uuid):
"""Get an inclusion request."""
return cls.query.filter_by(
id_record=record_uuid, id_community=community_id
).one_or_none() |
Get a community. | def create(cls, community_id, user_id, **data):
"""Get a community."""
with db.session.begin_nested():
obj = cls(id=community_id, id_user=user_id, **data)
db.session.add(obj)
return obj |
Get a community. | def save_logo(self, stream, filename):
"""Get a community."""
logo_ext = save_and_validate_logo(stream, filename, self.id)
if logo_ext:
self.logo_ext = logo_ext
return True
return False |
Get a community. | def get(cls, community_id, with_deleted=False):
"""Get a community."""
q = cls.query.filter_by(id=community_id)
if not with_deleted:
q = q.filter(cls.deleted_at.is_(None))
return q.one_or_none() |
Get a community. | def get_by_user(cls, user_id, with_deleted=False):
"""Get a community."""
query = cls.query.filter_by(
id_user=user_id
)
if not with_deleted:
query = query.filter(cls.deleted_at.is_(None))
return query.order_by(db.asc(Community.title)) |
Search for communities. | def filter_communities(cls, p, so, with_deleted=False):
"""Search for communities.
Helper function which takes from database only those communities which
match search criteria. Uses parameter 'so' to set communities in the
correct order.
Parameter 'page' is introduced to restri... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.