INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Aggregate a ndarray with structured dtype (or recarray) on columns for given functions. Aggregate a numpy recarray (or tabular tabarray) on a set of specified factors, using specified aggregation functions. Intuitively, this function will aggregate the dataset `X` on a set of columns, whose nam...
def aggregate(X, On=None, AggFuncDict=None, AggFunc=None, AggList=None, returnsort=False, KeepOthers=True, keyfuncdict=None): """ Aggregate a ndarray with structured dtype (or recarray) on columns for given functions. Aggregate a numpy recarray (or tabular tabarray) on a se...
Aggregate a ndarray with structured dtype or recarray and include original data in the result. Take aggregate of data set on specified columns, then add the resulting rows back into data set to make a composite object containing both original non-aggregate data rows as well as the aggregate rows. ...
def aggregate_in(Data, On=None, AggFuncDict=None, AggFunc=None, AggList=None, interspersed=True): """ Aggregate a ndarray with structured dtype or recarray and include original data in the result. Take aggregate of data set on specified columns, then add the resulting rows back i...
List of gray-scale colors in HSV space as web hex triplets. For integer argument k, returns list of `k` gray-scale colors, increasingly light, linearly in the HSV color space, as web hex triplets. Technical dependency of :func:`tabular.spreadsheet.aggregate_in`. **Parameters** **k** : ...
def grayspec(k): """ List of gray-scale colors in HSV space as web hex triplets. For integer argument k, returns list of `k` gray-scale colors, increasingly light, linearly in the HSV color space, as web hex triplets. Technical dependency of :func:`tabular.spreadsheet.aggregate_in`. **Parame...
Implements pivoting on numpy ndarrays (with structured dtype) or recarrays. See http://en.wikipedia.org/wiki/Pivot_table for information about pivot tables. Returns `X` pivoted on (a,b) with `a` as the row axis and `b` values as the column axis. So-called "nontrivial columns relative to `b`" in...
def pivot(X, a, b, Keep=None, NullVals=None, order = None, prefix='_'): ''' Implements pivoting on numpy ndarrays (with structured dtype) or recarrays. See http://en.wikipedia.org/wiki/Pivot_table for information about pivot tables. Returns `X` pivoted on (a,b) with `a` as the row axis and `b` va...
Append one or more records to the end of a numpy recarray or ndarray . Can take a single record, void or tuple, or a list of records, voids or tuples. Implemented by the tabarray method :func:`tabular.tab.tabarray.addrecords`. **Parameters** **X** : numpy ndarray with structured d...
def addrecords(X, new): """ Append one or more records to the end of a numpy recarray or ndarray . Can take a single record, void or tuple, or a list of records, voids or tuples. Implemented by the tabarray method :func:`tabular.tab.tabarray.addrecords`. **Parameters** **X*...
Add one or more columns to a numpy ndarray. Technical dependency of :func:`tabular.spreadsheet.aggregate_in`. Implemented by the tabarray method :func:`tabular.tab.tabarray.addcols`. **Parameters** **X** : numpy ndarray with structured dtype or recarray The recarra...
def addcols(X, cols, names=None): """ Add one or more columns to a numpy ndarray. Technical dependency of :func:`tabular.spreadsheet.aggregate_in`. Implemented by the tabarray method :func:`tabular.tab.tabarray.addcols`. **Parameters** **X** : numpy ndarray with structured dtyp...
Delete columns from a numpy ndarry or recarray. Can take a string giving a column name or comma-separated list of column names, or a list of string column names. Implemented by the tabarray method :func:`tabular.tab.tabarray.deletecols`. **Parameters** **X** : numpy recarray or nd...
def deletecols(X, cols): """ Delete columns from a numpy ndarry or recarray. Can take a string giving a column name or comma-separated list of column names, or a list of string column names. Implemented by the tabarray method :func:`tabular.tab.tabarray.deletecols`. **Parameters** ...
Rename column of a numpy ndarray with structured dtype, in-place. Implemented by the tabarray method :func:`tabular.tab.tabarray.renamecol`. **Parameters** **X** : numpy ndarray with structured dtype The numpy array for which a column is to be renamed. **ol...
def renamecol(X, old, new): """ Rename column of a numpy ndarray with structured dtype, in-place. Implemented by the tabarray method :func:`tabular.tab.tabarray.renamecol`. **Parameters** **X** : numpy ndarray with structured dtype The numpy array for which a co...
Replace value `old` with `new` everywhere it appears in-place. Implemented by the tabarray method :func:`tabular.tab.tabarray.replace`. **Parameters** **X** : numpy ndarray with structured dtype Numpy array for which in-place replacement of `old` with ...
def replace(X, old, new, strict=True, cols=None, rows=None): """ Replace value `old` with `new` everywhere it appears in-place. Implemented by the tabarray method :func:`tabular.tab.tabarray.replace`. **Parameters** **X** : numpy ndarray with structured dtype Nu...
Vertically stack a sequence of numpy ndarrays with structured dtype Analog of numpy.vstack Implemented by the tabarray method :func:`tabular.tab.tabarray.rowstack` which uses :func:`tabular.tabarray.tab_rowstack`. **Parameters** **seq** : sequence of numpy recarrays ...
def rowstack(seq, mode='nulls', nullvals=None): ''' Vertically stack a sequence of numpy ndarrays with structured dtype Analog of numpy.vstack Implemented by the tabarray method :func:`tabular.tab.tabarray.rowstack` which uses :func:`tabular.tabarray.tab_rowstack`. **Parameters** ...
Horizontally stack a sequence of numpy ndarrays with structured dtypes Analog of numpy.hstack for recarrays. Implemented by the tabarray method :func:`tabular.tab.tabarray.colstack` which uses :func:`tabular.tabarray.tab_colstack`. **Parameters** **seq** : sequence of numpy ndarra...
def colstack(seq, mode='abort',returnnaming=False): """ Horizontally stack a sequence of numpy ndarrays with structured dtypes Analog of numpy.hstack for recarrays. Implemented by the tabarray method :func:`tabular.tab.tabarray.colstack` which uses :func:`tabular.tabarray.tab_colstack`. ...
Combine two or more numpy ndarray with structured dtype on common key column(s). Merge a list (or dictionary) of numpy ndarray with structured dtype, given by `L`, on key columns listed in `keycols`. This function is actually a wrapper for :func:`tabular.spreadsheet.strictjoin`. The ``stric...
def join(L, keycols=None, nullvals=None, renamer=None, returnrenaming=False, Names=None): """ Combine two or more numpy ndarray with structured dtype on common key column(s). Merge a list (or dictionary) of numpy ndarray with structured dtype, given by `L`, on key columns listed in `keyc...
Combine two or more numpy ndarray with structured dtypes on common key column(s). Merge a list (or dictionary) of numpy arrays, given by `L`, on key columns listed in `keycols`. The ``strictjoin`` assumes the following restrictions: * each element of `keycol` must be a valid column name in `X`...
def strictjoin(L, keycols, nullvals=None, renaming=None, Names=None): """ Combine two or more numpy ndarray with structured dtypes on common key column(s). Merge a list (or dictionary) of numpy arrays, given by `L`, on key columns listed in `keycols`. The ``strictjoin`` assumes the following ...
Renames overlapping column names of numpy ndarrays with structured dtypes Rename the columns by using a simple convention: * If `L` is a list, it will append the number in the list to the key associated with the array. * If `L` is a dictionary, the algorithm will append the string r...
def DEFAULT_RENAMER(L, Names=None): """ Renames overlapping column names of numpy ndarrays with structured dtypes Rename the columns by using a simple convention: * If `L` is a list, it will append the number in the list to the key associated with the array. * If `L` is a dictionary,...
Helioviewer.org and JHelioviewer operate off of JPEG2000 formatted image data generated from science-quality FITS files. Use the APIs below to interact directly with these intermediary JPEG2000 files. Download a JP2 image for the specified datasource that is the closest match in time to the `date` requested. ...
def getjp2image(date, sourceId=None, observatory=None, instrument=None, detector=None, measurement=None): ''' Helioviewer.org and JHelioviewer operate off of JPEG2000 formatted image data generated from science-quality FITS files. U...
GET /api/v1/getJP2Header/ Get the XML header embedded in a JPEG2000 image. Includes the FITS header as well as a section of Helioviewer-specific metadata. Request Parameters: Parameter Required Type Example Description id Required number 7654321 Unique JP2 image identifier. callback Optional str...
def getjp2header(Id): ''' GET /api/v1/getJP2Header/ Get the XML header embedded in a JPEG2000 image. Includes the FITS header as well as a section of Helioviewer-specific metadata. Request Parameters: Parameter Required Type Example Description id Required number 7654321 Unique JP2 image ide...
json loader objecthook :param load_module: Module that contains the various types :param pairs: key/value tuples (In our case, they are str/str) :return:
def loads_loader(load_module: types.ModuleType, pairs: Dict[str, str]) -> Optional[JSGValidateable]: """json loader objecthook :param load_module: Module that contains the various types :param pairs: key/value tuples (In our case, they are str/str) :return: """ cntxt = load_module._CONTEXT ...
Convert a JSON string into a JSGObject :param s: string representation of JSON document :param load_module: module that contains declarations for types :param kwargs: arguments see: json.load for details :return: JSGObject representing the json string
def loads(s: str, load_module: types.ModuleType, **kwargs): """ Convert a JSON string into a JSGObject :param s: string representation of JSON document :param load_module: module that contains declarations for types :param kwargs: arguments see: json.load for details :return: JSGObject representing...
Convert a file name or file-like object containing stringified JSON into a JSGObject :param fp: file-like object to deserialize :param load_module: module that contains declarations for types :param kwargs: arguments see: json.load for details :return: JSGObject representing the json string
def load(fp: Union[TextIO, str], load_module: types.ModuleType, **kwargs): """ Convert a file name or file-like object containing stringified JSON into a JSGObject :param fp: file-like object to deserialize :param load_module: module that contains declarations for types :param kwargs: arguments see: js...
native isinstance_ with the test for typing.Union overridden
def isinstance_(x, A_tuple): """ native isinstance_ with the test for typing.Union overridden """ if is_union(A_tuple): return any(isinstance_(x, t) for t in A_tuple.__args__) elif getattr(A_tuple, '__origin__', None) is not None: return isinstance(x, A_tuple.__origin__) else: re...
Determine whether obj is valid :param obj: Object to validate :param log: Logger to record validation failures. If absent, no information is recorded
def is_valid(obj: JSGValidateable, log: Optional[Union[TextIO, Logger]] = None) -> bool: """ Determine whether obj is valid :param obj: Object to validate :param log: Logger to record validation failures. If absent, no information is recorded """ return obj._is_valid(log)
`out` is an output stream `ott` is an OTT instance used for translating labels `ott_id2children` is a dict mapping an OTT ID to the IDs of its children `root_ott_id` is the root of the subtree to write. `label_style` is a facet of OTULabelStyleEnum `prune_flags` is a set strings (flags) or OTTFlagUn...
def write_newick_ott(out, ott, ott_id2children, root_ott_id, label_style, prune_flags, create_log_dict=False): """`out` is an output stream `ott` is an OTT instance used for translating ...
returns a pair of trees: the first is that is a pruned version of tree_proxy created by pruning any leaf that has no ott_id and every internal that does not have any descendant with an ott_id. Nodes of out-degree 1 are suppressed as part of the TreeWithPathsInEdges-style. ...
def create_pruned_and_taxonomy_for_tip_ott_ids(tree_proxy, ott, create_monotypic_nodes=False): """returns a pair of trees: the first is that is a pruned version of tree_proxy created by pruning any leaf that has no ott_id and every internal that does not have any descendant with an o...
fstrs = ['{k:d}: {v}'.format(k=k, v=v) for k, v in o.flag_set_id_to_flag_set.items()] print('flag_set_id_to_flag_set =\n {}'.format('\n '.join(fstrs))) for ott_id, info in o.ott_id_to_sources.items(): if 'ncbi' in info: print('OTT {o:d} => NCBI {n:d}'.format(o=ott_id, n=info['ncbi'])) ...
def main(): import sys cout = codecs.getwriter('utf-8')(sys.stdout) o = OTT() # print('taxonomic sources = "{}"'.format('", "'.join([iii for iii in o.taxonomic_sources]))) # print(o.ncbi(1115784)) o.write_newick(cout, label_style=OTULabelStyleEnum.CURRENT_LABEL_OTT_ID, prune_flags=_TREEMACHINE_P...
preorder2tuple maps a preorder number to a node definition. ottID2preorder maps every OTT ID in taxonomy.tsv to a preorder # 'ottID2preorder' 'ottID2preorder' 'preorder2ottID' 'ottID2uniq' 'uniq2ottID' 'name2ottID' 'ottID2names' 'ottID2ranks' ...
def _create_pickle_files(self, out_dir=None): # pylint: disable=R0914,R0915 """ preorder2tuple maps a preorder number to a node definition. ottID2preorder maps every OTT ID in taxonomy.tsv to a preorder # 'ottID2preorder' 'ottID2preorder' 'preorder2ottID' 'ottID2un...
returns: - a list of recognized ott_ids. - a list of unrecognized ott_ids - a list of ott_ids that forward to unrecognized ott_ids - a list of ott_ids that do not appear in the tree because they are flagged to be pruned. - a list of ott_ids that do not appear in the tre...
def map_ott_ids(self, ott_id_list, to_prune_fsi_set, root_ott_id): """returns: - a list of recognized ott_ids. - a list of unrecognized ott_ids - a list of ott_ids that forward to unrecognized ott_ids - a list of ott_ids that do not appear in the tree because they are fla...
Given a set of argument tuples, set their value in a data dictionary if not blank
def arg_tup_to_dict(argument_tuples): """Given a set of argument tuples, set their value in a data dictionary if not blank""" data = dict() for arg_name, arg_val in argument_tuples: if arg_val is not None: if arg_val is True: arg_val = 'true' elif arg_val is F...
Raise appropriate exceptions if necessary.
def handle_error(response): """Raise appropriate exceptions if necessary.""" status_code = response.status_code if status_code not in A_OK_HTTP_CODES: error_explanation = A_ERROR_HTTP_CODES.get(status_code) raise_error = "{}: {}".format(status_code, error_explanation) raise Exceptio...
Takes an `annotation` dictionary which is expected to have a string as the value of annotation['author']['name'] This function will remove all annotations from obj that: 1. have the same author/name, and 2. have no messages that are flagged as messages to be preserved (values for...
def add_or_replace_annotation(self, # pylint: disable=R0201 obj, annotation, agent, add_agent_only=False): """Takes an `annotation` dictionary which is expected to hav...
Either: * Returns a list, or * Generates a MissingExpectedListWarning and returns None (if the value is not a dict or list)
def _get_list_key(self, obj, key, vc, obj_nex_id=None): """Either: * Returns a list, or * Generates a MissingExpectedListWarning and returns None (if the value is not a dict or list) """ k = obj.get(key) if k is None: return None ...
Creates: errors if `obj` does not contain keys in the schema.ALLOWED_KEY_SET, warnings if `obj` lacks keys listed in schema.EXPECETED_KEY_SET, or if `obj` contains keys not listed in schema.ALLOWED_KEY_SET.
def _validate_obj_by_schema(self, obj, obj_nex_id, vc): """Creates: errors if `obj` does not contain keys in the schema.ALLOWED_KEY_SET, warnings if `obj` lacks keys listed in schema.EXPECETED_KEY_SET, or if `obj` contains keys not listed in schema.ALLOWED_KEY_SET. ...
Adds several attributes to `container`: _using_hbf_meta - boolean. True for HoneyBadgerFish v1-style meta elements ('^prop': value rather than 'meta': {'$':value}) and the following _SchemaFragment instances: _NexmlEl_Schema
def add_schema_attributes(container, nexson_version): """Adds several attributes to `container`: _using_hbf_meta - boolean. True for HoneyBadgerFish v1-style meta elements ('^prop': value rather than 'meta': {'$':value}) and the following _SchemaFragment instances: _NexmlEl_Schema "...
Context manager entry; open wallet. For use when keeping agent open across multiple calls. :return: current object
async def open(self) -> '_BaseAgent': """ Context manager entry; open wallet. For use when keeping agent open across multiple calls. :return: current object """ LOGGER.debug('_BaseAgent.open >>>') # Do not open pool independently: let relying party decide when ...
Get json cryptonym (including current verification key) for input (agent) DID from ledger. Raise BadLedgerTxn on failure. :param did: DID of cryptonym to fetch :return: cryptonym json
async def get_nym(self, did: str) -> str: """ Get json cryptonym (including current verification key) for input (agent) DID from ledger. Raise BadLedgerTxn on failure. :param did: DID of cryptonym to fetch :return: cryptonym json """ LOGGER.debug('_BaseAgent.ge...
Get revocation registry definition from ledger by its identifier. Raise AbsentRevReg for no such revocation registry, logging any error condition and raising BadLedgerTxn on bad request. Retrieve the revocation registry definition from the agent's revocation cache if it has it; cache it...
async def _get_rev_reg_def(self, rr_id: str) -> str: """ Get revocation registry definition from ledger by its identifier. Raise AbsentRevReg for no such revocation registry, logging any error condition and raising BadLedgerTxn on bad request. Retrieve the revocation registry de...
Get credential definition from ledger by its identifier. Raise AbsentCredDef for no such credential definition, logging any error condition and raising BadLedgerTxn on bad request. Raise ClosedPool if cred def not in cache and pool is closed. Retrieve the credential definition from the agent's...
async def get_cred_def(self, cd_id: str) -> str: """ Get credential definition from ledger by its identifier. Raise AbsentCredDef for no such credential definition, logging any error condition and raising BadLedgerTxn on bad request. Raise ClosedPool if cred def not in cache and pool is...
Get schema from ledger by SchemaKey namedtuple (origin DID, name, version), sequence number, or schema identifier. Raise AbsentSchema for no such schema, logging any error condition and raising BadLedgerTxn on bad request. Retrieve the schema from the agent's schema cache if it has it;...
async def get_schema(self, index: Union[SchemaKey, int, str]) -> str: """ Get schema from ledger by SchemaKey namedtuple (origin DID, name, version), sequence number, or schema identifier. Raise AbsentSchema for no such schema, logging any error condition and raising BadLedgerTx...
Find a transaction on the distributed ledger by its sequence number. :param txn: transaction number :return: json sequence number of transaction, null for no match
async def get_txn(self, txn: int) -> str: """ Find a transaction on the distributed ledger by its sequence number. :param txn: transaction number :return: json sequence number of transaction, null for no match """ LOGGER.debug('_BaseAgent.get_txn >>> txn: %s', txn) ...
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._evaluate(namespace, namespace) if type(etype) is ForwardRef else etype
Determine whether etype is a Union
def is_union(etype) -> bool: """ Determine whether etype is a Union """ return getattr(etype, '__origin__', None) is not None and \ getattr(etype.__origin__, '_name', None) and\ etype.__origin__._name == 'Union'
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...
Unset the TypedFields on the input `entity`. Args: entity: A mixbox.Entity object. *types: A variable-length list of TypedField subclasses. If not provided, defaults to TypedField.
def unset(entity, *types): """Unset the TypedFields on the input `entity`. Args: entity: A mixbox.Entity object. *types: A variable-length list of TypedField subclasses. If not provided, defaults to TypedField. """ if not types: types = (TypedField,) fields = li...
Return True if the input TypedField `field` contains instance attributes that match the input parameters. Args: field: A TypedField instance. params: A dictionary of TypedField instance attribute-to-value mappings. Returns: True if the input TypedField matches the input parameters.
def _matches(field, params): """Return True if the input TypedField `field` contains instance attributes that match the input parameters. Args: field: A TypedField instance. params: A dictionary of TypedField instance attribute-to-value mappings. Returns: True if the input Type...
Iterate over the input class members and yield its TypedFields. Args: klass: A class (usually an Entity subclass). Yields: (class attribute name, TypedField instance) tuples.
def iterfields(klass): """Iterate over the input class members and yield its TypedFields. Args: klass: A class (usually an Entity subclass). Yields: (class attribute name, TypedField instance) tuples. """ is_field = lambda x: isinstance(x, TypedField) for name, field in inspec...
Return all TypedFields found on the input `Entity` that were initialized with the input **kwargs. Example: >>> find(myentity, multiple=True, type_=Foo) Note: TypedFields.__init__() can accept a string or a class as a type_ argument, but this method expects a class. Args: ...
def find(entity, **kwargs): """Return all TypedFields found on the input `Entity` that were initialized with the input **kwargs. Example: >>> find(myentity, multiple=True, type_=Foo) Note: TypedFields.__init__() can accept a string or a class as a type_ argument, but this metho...
Validate and clean a candidate value for this field.
def _clean(self, value): """Validate and clean a candidate value for this field.""" if value is None: return None elif self.type_ is None: return value elif self.check_type(value): return value elif self.is_type_castable: # noqa re...
Return the class for this field that transforms non-Entity objects (e.g., dicts or binding objects) into Entity instances. Any non-None value returned from this method should implement a from_obj() and from_dict() method. Returns: None if no type_ or factory is defined by t...
def transformer(self): """Return the class for this field that transforms non-Entity objects (e.g., dicts or binding objects) into Entity instances. Any non-None value returned from this method should implement a from_obj() and from_dict() method. Returns: None if n...
creates a logger obj
def bowshock_logger(): '''creates a logger obj''' FORMAT = '%(asctime)-15s %(message)s' logging.basicConfig(format=FORMAT, level=logging.INFO) logger = logging.getLogger('bowshock_logger') return logger
Remove a collection Given a collection_id, branch and optionally an author, remove a collection on the given branch and attribute the commit to author. Returns the SHA of the commit on branch.
def remove_collection(self, first_arg, sec_arg, third_arg, fourth_arg=None, commit_msg=None): """Remove a collection Given a collection_id, branch and optionally an author, remove a collection on the given branch and attribute the commit to author. Returns the SHA of the commit o...
Given a collection_id, temporary filename of content, branch and auth_info Deprecated but needed until we merge api local-dep to master...
def write_collection(self, collection_id, file_content, branch, author): """Given a collection_id, temporary filename of content, branch and auth_info Deprecated but needed until we merge api local-dep to master... """ gh_user = branch.split('_collection_')[0] msg = "Update Col...
Given a collection_id, temporary filename of content, branch and auth_info
def write_collection_from_tmpfile(self, collection_id, tmpfi, parent_sha, auth_info, commit_msg=''): """Given a collection_id, temporary filename of content, branch and auth_info """ return self.write_doc_from_tmpfile(collection_id, tmpfi, ...
Load caches and archive enough to go offline and be able to verify proof on content marked of interest in configuration. Return timestamp (epoch seconds) of cache load event, also used as subdirectory for cache archives. :param archive: whether to archive caches to disk :return...
async def load_cache(self, archive: bool = False) -> int: """ Load caches and archive enough to go offline and be able to verify proof on content marked of interest in configuration. Return timestamp (epoch seconds) of cache load event, also used as subdirectory for cache archiv...
Explicit entry. Perform ancestor opening operations, then parse cache from archive if so configured, and synchronize revocation registry to tails tree content. :return: current object
async def open(self) -> 'HolderProver': """ Explicit entry. Perform ancestor opening operations, then parse cache from archive if so configured, and synchronize revocation registry to tails tree content. :return: current object """ LOGGER.debug('Verifier.open >>...
Explicit exit. If so configured, populate cache to prove for any creds on schemata, cred defs, and rev regs marked of interest in configuration at initialization, archive cache, and purge prior cache archives. :return: current object
async def close(self) -> None: """ Explicit exit. If so configured, populate cache to prove for any creds on schemata, cred defs, and rev regs marked of interest in configuration at initialization, archive cache, and purge prior cache archives. :return: current object ""...
Verify proof as Verifier. Raise AbsentRevReg if a proof cites a revocation registry that does not exist on the distributed ledger. :param proof_req: proof request as Verifier creates, as per proof_req_json above :param proof: proof as HolderProver creates :return: json encoded True if p...
async def verify_proof(self, proof_req: dict, proof: dict) -> str: """ Verify proof as Verifier. Raise AbsentRevReg if a proof cites a revocation registry that does not exist on the distributed ledger. :param proof_req: proof request as Verifier creates, as per proof_req_json above ...
Grant permission if owner or admin.
def can(self): """Grant permission if owner or admin.""" return str(current_user.get_id()) == str(self.community.id_user) or \ DynamicPermission(ActionNeed('admin-access')).can()
Creates an html representation of tabular data, either from a tabarray or an externa file (`including ``.hsv``, ``.csv``, ``.tsv``). If no data is directly provided by passing a tabarray to `X`, then a tabarray is constructed using :func:`tabular.tabarray.tabarray.__new__`. **Parameters** ...
def tabular2html(fname=None, X=None, fin=None, title=None, printheader=False, split=True, usecss=None, writecss=None, SERVERNAME=None, SERVER_FROM_CURDIR='../', ROWS_PER_PAGE=1000, returnstring = False, **kwargs): """ Creates an html representation of tabula...
lat & lon expect decimal latitude and longitude values. (Required) elevation assumes meters. (Optional) limit assumes an integer. Default is 5. (Optional) date expects an ISO 8601 formatted date. (Optional)
def space_events(lon=None, lat=None, limit=None, date=None): ''' lat & lon expect decimal latitude and longitude values. (Required) elevation assumes meters. (Optional) limit assumes an integer. Default is 5. (Optional) date expects an ISO 8601 formatted date. (Optional) ''' base_url =...
Take the union of a list of lists. Take a Python list of Python lists:: [[l11,l12, ...], [l21,l22, ...], ... , [ln1, ln2, ...]] and return the aggregated list:: [l11,l12, ..., l21, l22 , ...] For a list of two lists, e.g. `[a, b]`, this is like:: a.extend(b) **...
def listunion(ListOfLists): """ Take the union of a list of lists. Take a Python list of Python lists:: [[l11,l12, ...], [l21,l22, ...], ... , [ln1, ln2, ...]] and return the aggregated list:: [l11,l12, ..., l21, l22 , ...] For a list of two lists, e.g. `[a, b]`, this is...
Fast inverse of a (numpy) permutation. **Paramters** **s** : sequence Sequence of indices giving a permutation. **Returns** **inv** : numpy array Sequence of indices giving the inverse of permutation `s`.
def perminverse(s): ''' Fast inverse of a (numpy) permutation. **Paramters** **s** : sequence Sequence of indices giving a permutation. **Returns** **inv** : numpy array Sequence of indices giving the inverse of permutation `s`. ...
Tranposes the simple array presentation of a list of lists (of equal length). Argument: L = [row1, row2, ...., rowN] where the rowi are python lists of equal length. Returns: LT, a list of python lists such that LT[j][i] = L[i][j].
def listarraytranspose(L): ''' Tranposes the simple array presentation of a list of lists (of equal length). Argument: L = [row1, row2, ...., rowN] where the rowi are python lists of equal length. Returns: LT, a list of python lists such that LT[j][i] = L[i][j]. ''' retur...
Infer the data type (int, float, str) of a list of strings. Take a list of strings, and attempts to infer a numeric data type that fits them all. If the strings are all integers, returns a NumPy array of integers. If the strings are all floats, returns a NumPy array of floats. Otherwise, returns...
def DEFAULT_TYPEINFERER(column): """ Infer the data type (int, float, str) of a list of strings. Take a list of strings, and attempts to infer a numeric data type that fits them all. If the strings are all integers, returns a NumPy array of integers. If the strings are all floats, returns a N...
Returns a null value for each of various kinds of test values. **Parameters** **test** : bool, int, float or string Value to test. **Returns** **null** : element in `[False, 0, 0.0, '']` Null value corresponding to the given test value: ...
def DEFAULT_NULLVALUE(test): """ Returns a null value for each of various kinds of test values. **Parameters** **test** : bool, int, float or string Value to test. **Returns** **null** : element in `[False, 0, 0.0, '']` Null value c...
Return the python representation of the class represented by this object
def as_python(self, name: str) -> str: """ Return the python representation of the class represented by this object """ if self._map_valuetype: return self.map_as_python(name) else: return self.obj_as_python(name)
Return an ordered list of elements for the _members section :param all_are_optional: True means we're in a choice situation so everything is optional :return:
def members_entries(self, all_are_optional: bool=False) -> List[Tuple[str, str]]: """ Return an ordered list of elements for the _members section :param all_are_optional: True means we're in a choice situation so everything is optional :return: """ rval = [] if self._mem...
objectExpr: OBRACE membersDef? CBRACE OBRACE (LEXER_ID_REF | ANY)? MAPSTO valueType ebnfSuffix? CBRACE
def visitObjectExpr(self, ctx: jsgParser.ObjectExprContext): """ objectExpr: OBRACE membersDef? CBRACE OBRACE (LEXER_ID_REF | ANY)? MAPSTO valueType ebnfSuffix? CBRACE """ if not self._name: self._name = self._context.anon_id() if ctx.membersDef(): ...
membersDef: COMMA | member+ (BAR altMemberDef)* (BAR lastComma)? ; altMemberDef: member* ; member: pairDef COMMA? lastComma: COMMA ;
def visitMembersDef(self, ctx: jsgParser.MembersDefContext): """ membersDef: COMMA | member+ (BAR altMemberDef)* (BAR lastComma)? ; altMemberDef: member* ; member: pairDef COMMA? lastComma: COMMA ; """ if not self._name: self._name = self._context....
member: pairDef COMMA?
def visitMember(self, ctx: jsgParser.MemberContext): """ member: pairDef COMMA? """ self._strict = ctx.COMMA() is None self.visitChildren(ctx)
Optionally filters out aliases from standard doc-id list
def _get_filtered_study_ids(shard, include_aliases=False): """Optionally filters out aliases from standard doc-id list""" from peyotl.phylesystem.helper import DIGIT_PATTERN k = shard.get_doc_ids() if shard.has_aliases and (not include_aliases): x = [] for i in k: if DIGIT_PA...
Optimistic test for Nexson version in a shard (tests first study found)
def diagnose_repo_nexml2json(shard): """Optimistic test for Nexson version in a shard (tests first study found)""" with shard._index_lock: fp = next(iter(shard.study_index.values()))[2] with codecs.open(fp, mode='r', encoding='utf-8') as fo: fj = json.load(fo) from peyotl.nexson_synt...
Return the numeric part of the newest study_id Checks out master branch as a side effect!
def _determine_next_study_id(self): """Return the numeric part of the newest study_id Checks out master branch as a side effect! """ if self._doc_counter_lock is None: self._doc_counter_lock = Lock() prefix = self._new_study_prefix lp = len(prefix) n ...
ASSUMES the caller holds the _doc_counter_lock ! Returns the current numeric part of the next study ID, advances the counter to the next value, and stores that value in the file in case the server is restarted.
def _advance_new_study_id(self): """ ASSUMES the caller holds the _doc_counter_lock ! Returns the current numeric part of the next study ID, advances the counter to the next value, and stores that value in the file in case the server is restarted. """ c = self._next_study...
Returns a set of all of the prefixes seen in the main document dir
def _diagnose_prefixes(self): """Returns a set of all of the prefixes seen in the main document dir """ from peyotl.phylesystem import STUDY_ID_PATTERN p = set() for name in os.listdir(self.doc_dir): if STUDY_ID_PATTERN.match(name): p.add(name[:3]) ...
Checks out master branch as a side effect
def _mint_new_study_id(self): """Checks out master branch as a side effect""" # studies created by the OpenTree API start with ot_, # so they don't conflict with new study id's from other sources with self._doc_counter_lock: c = self._advance_new_study_id() # @TODO. T...
Checks out master branch as a side effect
def create_git_action_for_new_study(self, new_study_id=None): """Checks out master branch as a side effect""" ga = self.create_git_action() if new_study_id is None: new_study_id = self._mint_new_study_id() self.register_doc_id(ga, new_study_id) return ga, new_study_id
Return a list of all non-list items in l :param l: list to be flattened :return:
def flatten(l: Iterable) -> List: """Return a list of all non-list items in l :param l: list to be flattened :return: """ rval = [] for e in l: if not isinstance(e, str) and isinstance(e, Iterable): if len(list(e)): rval += flatten(e) else: ...
Return a list of UNIQUE non-list items in l
def flatten_unique(l: Iterable) -> List: """ Return a list of UNIQUE non-list items in l """ rval = OrderedDict() for e in l: if not isinstance(e, str) and isinstance(e, Iterable): for ev in flatten_unique(e): rval[ev] = None else: rval[e] = None r...
Extract the token for an identifier from the context. Tokens can be: * ID - The name of a JSG definition * idref -- A reference to an existing JSG definition * LEXER_ID - The name of a match pattern definition * LEXER_ID_REF - A reference to an existing match pattern definition *...
def get_terminal(ctx: ParserRuleContext) -> str: """ Extract the token for an identifier from the context. Tokens can be: * ID - The name of a JSG definition * idref -- A reference to an existing JSG definition * LEXER_ID - The name of a match pattern definition * LEXER_ID_REF - A re...
Return a stringified list of identifiers in ctx :param ctx: JSG parser item with a set of identifiers :return:
def as_tokens(ctx: List[ParserRuleContext]) -> List[str]: """Return a stringified list of identifiers in ctx :param ctx: JSG parser item with a set of identifiers :return: """ return [as_token(e) for e in ctx]
Determine whether tkn is a valid python identifier :param tkn: :return:
def is_valid_python(tkn: str) -> bool: """Determine whether tkn is a valid python identifier :param tkn: :return: """ try: root = ast.parse(tkn) except SyntaxError: return False return len(root.body) == 1 and isinstance(root.body[0], ast.Expr) and isinstance(root.body[0].val...
Remove a study Given a study_id, branch and optionally an author, remove a study on the given branch and attribute the commit to author. Returns the SHA of the commit on branch.
def remove_study(self, first_arg, sec_arg, third_arg, fourth_arg=None, commit_msg=None): """Remove a study Given a study_id, branch and optionally an author, remove a study on the given branch and attribute the commit to author. Returns the SHA of the commit on branch. ""...
Given a study_id, temporary filename of content, branch and auth_info Deprecated but needed until we merge api local-dep to master...
def write_study(self, study_id, file_content, branch, author): """Given a study_id, temporary filename of content, branch and auth_info Deprecated but needed until we merge api local-dep to master... """ gh_user = branch.split('_study_')[0] msg = "Update Study #%s via OpenTree ...
Given a study_id, temporary filename of content, branch and auth_info
def write_study_from_tmpfile(self, study_id, tmpfi, parent_sha, auth_info, commit_msg=''): """Given a study_id, temporary filename of content, branch and auth_info """ return self.write_doc_from_tmpfile(study_id, tmpfi, ...
Initialize the communities file storage.
def init(): """Initialize the communities file storage.""" try: initialize_communities_bucket() click.secho('Community init successful.', fg='green') except FilesException as e: click.secho(e.message, fg='red')
Add logo to the community.
def addlogo(community_id, logo): """Add logo to the community.""" # Create the bucket c = Community.get(community_id) if not c: click.secho('Community {0} does not exist.'.format(community_id), fg='red') return ext = save_and_validate_logo(logo, logo.name, c.id) ...
Request a record acceptance to a community.
def request(community_id, record_id, accept): """Request a record acceptance to a community.""" c = Community.get(community_id) assert c is not None record = Record.get_record(record_id) if accept: c.add_record(record) record.commit() else: InclusionRequest.create(communi...
Remove a record from community.
def remove(community_id, record_id): """Remove a record from community.""" c = Community.get(community_id) assert c is not None c.remove_record(record_id) db.session.commit() RecordIndexer().index_by_id(record_id)
treats the 2 sets are sets of taxon IDs on the same (unstated) universe of taxon ids. Returns True clades implied by each are compatible and False otherwise
def sets_are_rooted_compat(one_set, other): """treats the 2 sets are sets of taxon IDs on the same (unstated) universe of taxon ids. Returns True clades implied by each are compatible and False otherwise """ if one_set.issubset(other) or other.issubset(one_set): return True return not in...
Takes a NexSON object and returns a dict of otu_id -> otu_obj
def gen_otu_dict(nex_obj, nexson_version=None): """Takes a NexSON object and returns a dict of otu_id -> otu_obj """ if nexson_version is None: nexson_version = detect_nexson_version(nex_obj) if _is_by_id_hbf(nexson_version): otus = nex_obj['nexml']['otusById'] if len(otus) >...
Explicit entry. Opens pool as configured, for later closure via close(). For use when keeping pool open across multiple calls. Raise any IndyError causing failure to create ledger configuration. :return: current object
async def open(self) -> 'NodePool': """ Explicit entry. Opens pool as configured, for later closure via close(). For use when keeping pool open across multiple calls. Raise any IndyError causing failure to create ledger configuration. :return: current object """ ...
Adapts LockError to HTTP. If an exception is not thrown, the git_action has the lock (and must release it!)
def acquire_lock_raise(git_action, fail_msg=''): """Adapts LockError to HTTP. If an exception is not thrown, the git_action has the lock (and must release it!) """ try: git_action.acquire_lock() except LockError as e: msg = '{o} Details: {d}'.format(o=fail_msg, d=e.message) _LOG....
merge from master into the WIP for this document/author this is needed to allow a worker's future saves to be merged seamlessly into master
def merge_from_master(git_action, doc_id, auth_info, parent_sha, doctype_display_name="document"): """merge from master into the WIP for this document/author this is needed to allow a worker's future saves to be merged seamlessly into master """ gh_user = get_user_author(auth_info)[0] acquire_lo...
Actually make a local Git commit and push it to our remote
def generic_commit_and_try_merge2master_wf(git_action, file_content, doc_id, auth_info, parent_sha, commi...
Sets the chosen country in the session or cookie. If `next' query param is present, it redirects to a given url.
def set_country(request): """ Sets the chosen country in the session or cookie. If `next' query param is present, it redirects to a given url. """ if request.method == 'POST': next = request.POST.get('next', request.GET.get('next')) if is_safe_url(url=next, host=request.get_host()):...
Return the element that tkn represents
def reference(self, tkn: str): """ Return the element that tkn represents""" return self.grammarelts[tkn] if tkn in self.grammarelts else UndefinedElement(tkn)
Return a list all of the grammarelts that depend on tkn :param tkn: :return:
def dependency_list(self, tkn: str) -> List[str]: """Return a list all of the grammarelts that depend on tkn :param tkn: :return: """ if tkn not in self.dependency_map: self.dependency_map[tkn] = [tkn] # Force a circular reference self.dependency_...
Return all the items that tkn depends on as a set :param tkn: :return:
def dependencies(self, tkn: str) -> Set[str]: """Return all the items that tkn depends on as a set :param tkn: :return: """ return set(self.dependency_list(tkn))
Return the set of tokens that are referenced but not defined.
def undefined_entries(self) -> Set[str]: """ Return the set of tokens that are referenced but not defined. """ return as_set([[d for d in self.dependencies(k) if d not in self.grammarelts] for k in self.grammarelts.keys()])
Determine the transitive closure of tkn's dependencies :param tkn: root token :param seen: list of tokens already visited in closure process :return: dependents, dependents of dependents, etc.
def dependency_closure(self, tkn: str, seen: Optional[Set[str]]=None) -> Set[str]: """ Determine the transitive closure of tkn's dependencies :param tkn: root token :param seen: list of tokens already visited in closure process :return: dependents, dependents of dependents, etc. ...
Return the set of recursive (circular) references :return:
def circular_references(self) -> Set[str]: """ Return the set of recursive (circular) references :return: """ rval = set() for k in self.grammarelts.keys(): if k in self.dependency_closure(k): rval.add(k) return rval