INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Generate a MongoDB sort order list using the Django ORM style. | def S(Document, *fields):
"""Generate a MongoDB sort order list using the Django ORM style."""
result = []
for field in fields:
if isinstance(field, tuple): # Unpack existing tuple.
field, direction = field
result.append((field, direction))
continue
direction = ASCENDING
if not field.starts... |
Reads data from CNPJ list and write results to output directory. | def run(self):
"""Reads data from CNPJ list and write results to output directory."""
self._assure_output_dir(self.output)
companies = self.read()
print '%s CNPJs found' % len(companies)
pbar = ProgressBar(
widgets=[Counter(), ' ', Percentage(), ' ', Bar(), ' ', Time... |
Reads data from the CSV file. | def read(self):
"""Reads data from the CSV file."""
companies = []
with open(self.file) as f:
reader = unicodecsv.reader(f)
for line in reader:
if len(line) >= 1:
cnpj = self.format(line[0])
if self.valid(cnpj):
... |
Writes json data to the output directory. | def write(self, data):
"""Writes json data to the output directory."""
cnpj, data = data
path = os.path.join(self.output, '%s.json' % cnpj)
with open(path, 'w') as f:
json.dump(data, f, encoding='utf-8') |
Check if a CNPJ is valid. | def valid(self, cnpj):
"""Check if a CNPJ is valid.
We should avoid sending invalid CNPJ to the web service as we know
it is going to be a waste of bandwidth. Assumes CNPJ is a string.
"""
if len(cnpj) != 14:
return False
tam = 12
nums = cnpj[:tam]
... |
Writes out data from taxon to the output stream to demonstrate the attributes of a taxon object. ( currently some lines are commented out until the web - services call returns more info. See: https:// github. com/ OpenTreeOfLife/ taxomachine/ issues/ 85 ). If include_anc is True then ancestor information was requested ... | def write_taxon_info(taxon, include_anc, output):
"""Writes out data from `taxon` to the `output` stream to demonstrate
the attributes of a taxon object.
(currently some lines are commented out until the web-services call returns more info. See:
https://github.com/OpenTreeOfLife/taxomachine/issues/8... |
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
import codecs
# have to be ready to deal with utf-8 names
out = codecs.getwriter('utf-8')(sys.stdout)
description = 'Uses Open Tree of Lif... |
Returns the configuration filepath. | def get_default_config_filename():
"""Returns the configuration filepath.
If PEYOTL_CONFIG_FILE is in the env that is the preferred choice; otherwise ~/.peyotl/config is preferred.
If the preferred file does not exist, then the packaged peyotl/default.conf from the installation of peyotl is
used.
A... |
Returns a ConfigParser object and a list of filenames that were parsed to initialize it | def get_raw_default_config_and_read_file_list():
"""Returns a ConfigParser object and a list of filenames that were parsed to initialize it"""
global _CONFIG, _READ_DEFAULT_FILES
if _CONFIG is not None:
return _CONFIG, _READ_DEFAULT_FILES
with _CONFIG_LOCK:
if _CONFIG is not None:
... |
Read ( section param ) from config_obj. If not found return default | def _raw_config_setting(config_obj, section, param, default=None, config_filename='', warn_on_none_level=logging.WARN):
"""Read (section, param) from `config_obj`. If not found, return `default`
If the setting is not found and `default` is None, then an warn-level message is logged.
`config_filename` can b... |
Creates a two - level dictionary of d [ section ] [ option ] from a config parser object. | def _create_overrides_from_config(config):
"""Creates a two-level dictionary of d[section][option] from a config parser object."""
d = {}
for s in config.sections():
d[s] = {}
for opt in config.options(s):
d[s][opt] = config.get(s, opt)
return d |
Thread - safe accessor for the immutable default ConfigWrapper object | def get_config_object():
"""Thread-safe accessor for the immutable default ConfigWrapper object"""
global _DEFAULT_CONFIG_WRAPPER
if _DEFAULT_CONFIG_WRAPPER is not None:
return _DEFAULT_CONFIG_WRAPPER
with _DEFAULT_CONFIG_WRAPPER_LOCK:
if _DEFAULT_CONFIG_WRAPPER is not None:
... |
return the first non - None setting from a series where each element in sec_param_list is a section param pair suitable for a get_config_setting call. | def get_from_config_setting_cascade(self, sec_param_list, default=None, warn_on_none_level=logging.WARN):
"""return the first non-None setting from a series where each
element in `sec_param_list` is a section, param pair suitable for
a get_config_setting call.
Note that non-None values ... |
Takes an obj that is an amendment object. retain_deprecated if False then obj may be modified to replace deprecated constructs with new syntax. If it is True the obj will not be modified. Returns the pair: errors adaptor errors is a simple list of error messages adaptor will be an instance of amendments. validation. ad... | def validate_amendment(obj, retain_deprecated=True, **kwargs):
"""Takes an `obj` that is an amendment object.
`retain_deprecated` if False, then `obj` may be modified to replace
deprecated constructs with new syntax. If it is True, the `obj` will
not be modified.
Returns the pair:
er... |
Returns a list from [ ott_id ott_id s par... root ott_id ] | def create_anc_lineage_from_id2par(id2par_id, ott_id):
"""Returns a list from [ott_id, ott_id's par, ..., root ott_id]"""
curr = ott_id
n = id2par_id.get(curr)
if n is None:
raise KeyError('The OTT ID {} was not found'.format(ott_id))
lineage = [curr]
while n is not None:
lineage... |
Expecting a dict of id2parent ID or a pickled object ( passed in as file object stream or filepath ) | def parse_id2par_dict(id2par=None,
id_list=None,
id2par_stream=None,
id2par_filepath=None,
id_list_stream=None,
id_list_filepath=None,
_class=TreeWithPathsInEdges):
"""Expecting a dict... |
Applies the functions to each node in a subtree using an traversal in which encountered twice: once right before its descendants and once right after its last descendant | def before_after_apply(self, before_fn, after_fn, leaf_fn=None):
"""Applies the functions to each node in a subtree using an traversal in which
encountered twice: once right before its descendants, and once right
after its last descendant
"""
stack = [self]
while stack:
... |
From DendroPy Preorder traversal of self and its child_nodes. Returns self and all descendants such that a node is returned before its child_nodes ( and their child_nodes ). Filtered by filter_fn: node is only returned if no filter_fn is given or if filter_fn returns True. | def preorder_iter(self, filter_fn=None):
""" From DendroPy
Preorder traversal of self and its child_nodes. Returns self
and all descendants such that a node is returned before its
child_nodes (and their child_nodes). Filtered by filter_fn: node is
only returned if no filter_fn i... |
From DendroPy Postorder traversal of the self and its child_nodes. Returns self and all descendants such that a node s child_nodes ( and their child_nodes ) are visited before node. Filtered by filter_fn: node is only returned if no filter_fn is given or if filter_fn returns True. | def postorder_iter(self, filter_fn=None):
"""From DendroPy
Postorder traversal of the self and its child_nodes. Returns self
and all descendants such that a node's child_nodes (and their
child_nodes) are visited before node. Filtered by filter_fn:
node is only returned if no fi... |
Adds a long integer bits4subtree_ids to each node ( Fails cryptically if that field is already present! ) relevant_ids can be a dict of _id to bit representation. If it is not supplied a dict will be created by registering the leaf. _id into a dict ( and returning the dict ) the bits4subtree_ids will have a 1 bit if th... | def add_bits4subtree_ids(self, relevant_ids):
"""Adds a long integer bits4subtree_ids to each node (Fails cryptically if that field is already present!)
relevant_ids can be a dict of _id to bit representation.
If it is not supplied, a dict will be created by registering the leaf._id into a dict ... |
Parse the jsg in infilename and save the results in outfilename: param infilename: file containing jsg: param outfilename: target python file: param verbose: verbose output flag: return: true if success | def do_parse(infilename: str, outfilename: str, verbose: bool) -> bool:
"""
Parse the jsg in infilename and save the results in outfilename
:param infilename: file containing jsg
:param outfilename: target python file
:param verbose: verbose output flag
:return: true if success
"""
pytho... |
Parse the text in infile and save the results in outfile | def parse(input_: Union[str, FileStream], source: str) -> Optional[str]:
"""Parse the text in infile and save the results in outfile
:param input_: string or stream to parse
:param source: source name for python file header
:return: python text if successful
"""
# Step 1: Tokenize the input st... |
Create a command line parser: return: parser | def genargs() -> ArgumentParser:
"""
Create a command line parser
:return: parser
"""
parser = ArgumentParser()
parser.add_argument("infile", help="Input JSG specification")
parser.add_argument("-o", "--outfile", help="Output python file (Default: {infile}.py)")
parser.add_argument("-e",... |
Load fname as a module. Will raise an exception if there is an error: param module_name: resulting name of module: param fname: name to load | def evaluate(module_name: str, fname: str, verbose: bool):
"""
Load fname as a module. Will raise an exception if there is an error
:param module_name: resulting name of module
:param fname: name to load
"""
if verbose:
print("Testing {}".format(fname))
spec = importlib.util.spec_f... |
Executes a request by AsyncHTTPClient asynchronously returning an tornado. HTTPResponse. | def fetch(self, request, callback=None, raise_error=True, **kwargs):
"""Executes a request by AsyncHTTPClient,
asynchronously returning an `tornado.HTTPResponse`.
The ``raise_error=False`` argument currently suppresses
*all* errors, encapsulating them in `HTTPResponse` objects
... |
Query for a specific target: | def search_target_obj(target):
'''
Query for a specific target:
http://asterank.com/api/skymorph/search?<params>
target Target object (lookup in MPC).
'''
base_url = "http://asterank.com/api/skymorph/search?"
if not isinstance(target, str):
raise ValueError("The target arg you prov... |
Query based on orbital elements: | def search_orbit(**kwargs):
'''
Query based on orbital elements:
http://asterank.com/api/skymorph/search_orbit?<params>
epoch Epoch ([M]JD or ISO)
ecc eccentricity
per Perihelion distance (AU)
per_date Perihelion date ([M]JD or ISO)
om Longitude of ascending node (deg)
w Argument of... |
Query based on position and time ( +/ - 1 day ): | def search_position(**kwargs):
'''
Query based on position and time (+/- 1 day):
http://asterank.com/api/skymorph/search_position?<params>
ra Right ascension (HMS)
Dec Declination (DMS)
time Date and time (UTC)
per_date Perihelion date ([M]JD or ISO)
om Longitude of ascending node (deg)... |
Takes a collection object ( or a filepath to collection object ) returns each element of the decisions list that has the decision set to included. | def collection_to_included_trees(collection):
"""Takes a collection object (or a filepath to collection object), returns
each element of the `decisions` list that has the decision set to included.
"""
if is_str_type(collection):
collection = read_as_json(collection)
inc = []
for d in col... |
Takes a collection object ( or a filepath to collection object ) returns True if it includes a decision to include the specified tree | def tree_is_in_collection(collection, study_id=None, tree_id=None):
"""Takes a collection object (or a filepath to collection object), returns
True if it includes a decision to include the specified tree
"""
included = collection_to_included_trees(collection)
study_id = study_id.strip()
tree_id ... |
Call jsonschema validation to raise JSONValidation on non - compliance or silently pass. | def validate_config(key: str, config: dict) -> None:
"""
Call jsonschema validation to raise JSONValidation on non-compliance or silently pass.
:param key: validation schema key of interest
:param config: configuration dict to validate
"""
try:
jsonschema.validate(config, CONFIG_JSON_S... |
Generate an identifier for a callable signal receiver. | def __make_id(receiver):
"""Generate an identifier for a callable signal receiver.
This is used when disconnecting receivers, where we need to correctly
establish equivalence between the input receiver and the receivers assigned
to a signal.
Args:
receiver: A callable object.
Returns:... |
Remove all dead signal receivers from the global receivers collection. | def __purge():
"""Remove all dead signal receivers from the global receivers collection.
Note:
It is assumed that the caller holds the __lock.
"""
global __receivers
newreceivers = collections.defaultdict(list)
for signal, receivers in six.iteritems(__receivers):
alive = [x for... |
Return all signal handlers that are currently still alive for the input signal. | def __live_receivers(signal):
"""Return all signal handlers that are currently still alive for the
input `signal`.
Args:
signal: A signal name.
Returns:
A list of callable receivers for the input signal.
"""
with __lock:
__purge()
receivers = [funcref() for func... |
Return True if the method is a bound method ( attached to an class instance. | def __is_bound_method(method):
"""Return ``True`` if the `method` is a bound method (attached to an class
instance.
Args:
method: A method or function type object.
"""
if not(hasattr(method, "__func__") and hasattr(method, "__self__")):
return False
# Bound methods have a __sel... |
Register receiver method/ function as a receiver for the signal. | def connect(signal, receiver):
"""Register `receiver` method/function as a receiver for the `signal`.
When the signal is emitted, this receiver will be invoked along with
all other associated signals.
Args:
signal: A signal identifier (e.g., a signal name)
receiver: A callable object t... |
Disconnect the receiver func from the signal identified by signal_id. | def disconnect(signal, receiver):
"""Disconnect the receiver `func` from the signal, identified by
`signal_id`.
Args:
signal: The signal identifier.
receiver: The callable receiver to disconnect.
Returns:
True if the receiver was successfully disconnected. False otherwise.
... |
Emit a signal by serially calling each registered signal receiver for the signal. | def emit(signal, *args, **kwargs):
"""Emit a signal by serially calling each registered signal receiver for
the `signal`.
Note:
The receiver must accept the *args and/or **kwargs that have been
passed to it. There expected parameters are not dictated by
mixbox.
Args:
... |
Very fast uniqify routine for numpy arrays. | def arrayuniqify(X, retainorder=False):
"""
Very fast uniqify routine for numpy arrays.
**Parameters**
**X** : numpy array
Determine the unique elements of this numpy array.
**retainorder** : Boolean, optional
Whether or not to return in... |
Very fast uniqify routine for numpy record arrays ( or ndarrays with structured dtype ). | def recarrayuniqify(X, retainorder=False):
"""
Very fast uniqify routine for numpy record arrays (or ndarrays with
structured dtype).
Record array version of func:`tabular.fast.arrayuniqify`.
**Parameters**
**X** : numpy recarray
Determine the unique elements of... |
Indices of elements in a sorted numpy array equal to those in another. | def equalspairs(X, Y):
"""
Indices of elements in a sorted numpy array equal to those in another.
Given numpy array `X` and sorted numpy array `Y`, determine the indices in
Y equal to indices in X.
Returns `[A,B]` where `A` and `B` are numpy arrays of indices in `X` such
that::
... |
Indices of elements in a sorted numpy recarray ( or ndarray with structured dtype ) equal to those in another. | def recarrayequalspairs(X,Y,weak=True):
"""
Indices of elements in a sorted numpy recarray (or ndarray with
structured dtype) equal to those in another.
Record array version of func:`tabular.fast.equalspairs`, but slightly
different because the concept of being sorted is less well-defined for a
... |
Indices of elements in a numpy array that appear in another. | def isin(X,Y):
"""
Indices of elements in a numpy array that appear in another.
Fast routine for determining indices of elements in numpy array `X` that
appear in numpy array `Y`, returning a boolean array `Z` such that::
Z[i] = X[i] in Y
**Parameters**
**X** : numpy ar... |
Indices of elements in a numpy record array ( or ndarray with structured dtype ) that appear in another. | def recarrayisin(X,Y,weak=True):
"""
Indices of elements in a numpy record array (or ndarray with structured
dtype) that appear in another.
Fast routine for determining indices of elements in numpy record array `X`
that appear in numpy record array `Y`, returning a boolean array `Z` such
tha... |
Elements of a numpy array that do not appear in another. | def arraydifference(X,Y):
"""
Elements of a numpy array that do not appear in another.
Fast routine for determining which elements in numpy array `X`
do not appear in numpy array `Y`.
**Parameters**
**X** : numpy array
Numpy array to comapare to numpy array `Y`.
... |
Records of a numpy recarray ( or ndarray with structured dtype ) that do not appear in another. | def recarraydifference(X,Y):
"""
Records of a numpy recarray (or ndarray with structured dtype)
that do not appear in another.
Fast routine for determining which records in numpy array `X`
do not appear in numpy recarray `Y`.
Record array version of func:`tabular.fast.arraydifference`.
**... |
Fast vectorized max function for element - wise comparison of two numpy arrays. | def arraymax(X,Y):
"""
Fast "vectorized" max function for element-wise comparison of two numpy arrays.
For two numpy arrays `X` and `Y` of equal length,
return numpy array `Z` such that::
Z[i] = max(X[i],Y[i])
**Parameters**
**X** : numpy array
Numpy... |
Derive DID as per indy - sdk from seed. | async def _seed2did(self) -> str:
"""
Derive DID, as per indy-sdk, from seed.
:return: DID
"""
rv = None
dids_with_meta = json.loads(await did.list_my_dids_with_meta(self.handle)) # list
if dids_with_meta:
for did_with_meta in dids_with_meta: # di... |
Create wallet as configured and store DID or else re - use any existing configuration. Operation sequence create/ store - DID/ close does not auto - remove the wallet on close even if so configured. | async def create(self) -> 'Wallet':
"""
Create wallet as configured and store DID, or else re-use any existing configuration.
Operation sequence create/store-DID/close does not auto-remove the wallet on close,
even if so configured.
:return: current object
"""
L... |
Explicit entry. Open wallet as configured for later closure via close (). For use when keeping wallet open across multiple calls. | async def open(self) -> 'Wallet':
"""
Explicit entry. Open wallet as configured, for later closure via close().
For use when keeping wallet open across multiple calls.
:return: current object
"""
LOGGER.debug('Wallet.open >>>')
if not self.created:
... |
Remove serialized wallet if it exists. | async def remove(self) -> None:
"""
Remove serialized wallet if it exists.
"""
LOGGER.debug('Wallet.remove >>>')
try:
LOGGER.info('Removing wallet: %s', self.name)
await wallet.delete_wallet(json.dumps(self.cfg), json.dumps(self.access_creds))
ex... |
Returns a tuple: the boolean for whether or not pushes succeed and the entire object returned by a call to push_failure on the phylesystem - api. This should only be called with wrappers around remote services ( RuntimeError will be raised if you call this with a local wrapper. | def push_failure_state(self):
"""Returns a tuple: the boolean for whether or not pushes succeed, and the
entire object returned by a call to push_failure on the phylesystem-api.
This should only be called with wrappers around remote services (RuntimeError
will be raised if you call this ... |
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 tree_id = tree3 ) see: | 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. | 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. | 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. | 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. | 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 analysis in which guesses are ch... | 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. | 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 header and if so sets the h... | 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. | 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. | 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. | 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. | 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. | 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. | 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 | 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. | 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 ) | 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. | 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 | 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. | 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. | 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 | 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. | 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. | 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):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.