INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Create forward references for all circular references :return:
def resolve_circular_references(self) -> None: """ Create forward references for all circular references :return: """ circulars = self.circular_references() for c in circulars: fwdref = JSGForwardRef(c) self.grammarelts[fwdref.label] = fwdref ...
Generator that returns items in ther order needed for the actual python 1) All forward references 2) All lexer items 3) Object / Array definitions in order of increasing dependency depth Within each category, items are returned alphabetically
def ordered_elements(self) -> str: """ Generator that returns items in ther order needed for the actual python 1) All forward references 2) All lexer items 3) Object / Array definitions in order of increasing dependency depth Within each category, items are retur...
New request for inclusion.
def new_request(sender, request=None, notify=True, **kwargs): """New request for inclusion.""" if current_app.config['COMMUNITIES_MAIL_ENABLED'] and notify: send_community_request_email(request)
Inject 'provisional_communities' key to ES index.
def inject_provisional_community(sender, json=None, record=None, index=None, **kwargs): """Inject 'provisional_communities' key to ES index.""" if index and not index.startswith( current_app.config['COMMUNITIES_INDEX_PREFIX']): return json['provisional_c...
Signal for creating OAI-PMH sets during community creation.
def create_oaipmh_set(mapper, connection, community): """Signal for creating OAI-PMH sets during community creation.""" from invenio_oaiserver.models import OAISet with db.session.begin_nested(): obj = OAISet(spec=community.oaiset_spec, name=community.title, ...
Signal for creating OAI-PMH sets during community creation.
def destroy_oaipmh_set(mapper, connection, community): """Signal for creating OAI-PMH sets during community creation.""" from invenio_oaiserver.models import OAISet with db.session.begin_nested(): oaiset = OAISet.query.filter_by( spec=community.oaiset_spec).one_or_none() if oaise...
Query on node properties. See documentation for _OTIWrapper class.
def find_nodes(self, query_dict=None, exact=False, verbose=False, **kwargs): """Query on node properties. See documentation for _OTIWrapper class.""" assert self.use_v1 return self._do_query('{p}/singlePropertySearchForTreeNodes'.format(p=self.query_prefix), query_d...
Query on tree properties. See documentation for _OTIWrapper class.
def find_trees(self, query_dict=None, exact=False, verbose=False, wrap_response=False, **kwargs): """Query on tree properties. See documentation for _OTIWrapper class.""" if self.use_v1: uri = '{p}/singlePropertySearchForTrees'.format(p=self.query_prefix) else: uri = '{p}...
Query on study properties. See documentation for _OTIWrapper class.
def find_studies(self, query_dict=None, exact=False, verbose=False, **kwargs): """Query on study properties. See documentation for _OTIWrapper class.""" if self.use_v1: uri = '{p}/singlePropertySearchForStudies'.format(p=self.query_prefix) else: uri = '{p}/find_studies'.f...
Returns a list of dicts for the entire set of studies indexed by oti. If verbose and include_trees are False, each dict will just have the ot:studyId If verbose is True, then the keys could also include: ot:curatorName ot:dataDeposit ot:focalClade ot:foca...
def find_all_studies(self, include_trees=False, verbose=False): """Returns a list of dicts for the entire set of studies indexed by oti. If verbose and include_trees are False, each dict will just have the ot:studyId If verbose is True, then the keys could also include: ot:curatorNa...
returns requirements array for package
def get_requirements(): '''returns requirements array for package''' packages = [] with open("requirements.txt", "r") as req_doc: for package in req_doc: packages.append(package.replace("\n", "")) return packages
Factory function for a _TaxonomicAmendmentStore object. A wrapper around the _TaxonomicAmendmentStore class instantiation for the most common use case: a singleton _TaxonomicAmendmentStore. If you need distinct _TaxonomicAmendmentStore objects, you'll need to call that class directly.
def TaxonomicAmendmentStore(repos_dict=None, repos_par=None, with_caching=True, assumed_doc_version=None, git_ssh=None, pkey=None, git_action_class=Taxo...
Validate and save this JSON. Ensure (and return) a unique amendment id
def add_new_amendment(self, json_repr, auth_info, commit_msg=''): """Validate and save this JSON. Ensure (and return) a unique amendment id""" amendment = self._coerce_json_to_amendment(json_repr) if amendment is None:...
Parse the JSON, return a slug in the form '{subtype}-{first ottid}-{last-ottid}'.
def _build_amendment_id(self, json_repr): """Parse the JSON, return a slug in the form '{subtype}-{first ottid}-{last-ottid}'.""" amendment = self._coerce_json_to_amendment(json_repr) if amendment is None: return None amendment_subtype = 'additions' # TODO: Look more ...
Validate and save this JSON. Ensure (and return) a unique amendment id
def update_existing_amendment(self, amendment_id=None, json_repr=None, auth_info=None, parent_sha=None, merged_sha=None, ...
Call the primary validator for a quick test
def _is_valid_amendment_json(self, json_repr): """Call the primary validator for a quick test""" amendment = self._coerce_json_to_amendment(json_repr) if amendment is None: # invalid JSON, definitely broken return False aa = validate_amendment(amendment) e...
Use to ensure that a JSON string (if found) is parsed to the equivalent dict in python. If the incoming value is already parsed, do nothing. If a string fails to parse, return None.
def _coerce_json_to_amendment(self, json_repr): """Use to ensure that a JSON string (if found) is parsed to the equivalent dict in python. If the incoming value is already parsed, do nothing. If a string fails to parse, return None.""" if isinstance(json_repr, dict): amendment = json...
Delete communities after holdout time.
def delete_marked_communities(): """Delete communities after holdout time.""" # TODO: Delete the community ID from all records metadata first raise NotImplementedError() Community.query.filter_by( Community.delete_time > datetime.utcnow()).delete() db.session.commit()
Delete expired inclusion requests.
def delete_expired_requests(): """Delete expired inclusion requests.""" InclusionRequest.query.filter_by( InclusionRequest.expiry_date > datetime.utcnow()).delete() db.session.commit()
Sugar. factory for a PhyloSchema object. Repackages the kwargs to kwargs for PhyloSchema so that our PhyloSchema.__init__ does not have to be soo rich
def create_content_spec(**kwargs): """Sugar. factory for a PhyloSchema object. Repackages the kwargs to kwargs for PhyloSchema so that our PhyloSchema.__init__ does not have to be soo rich """ format_str = kwargs.get('format', 'nexson') nexson_version = kwargs.get('nexson_version', 'native') ...
Converts an XML doc to JSON using the honeybadgerfish convention (see to_honeybadgerfish_dict) and then prunes elements not used by open tree of life study curartion. If nexml_content is provided, it is interpreted as the contents of an NeXML file in utf-8 encoding. If nexml_content is None, then the ...
def get_ot_study_info_from_nexml(src=None, nexml_content=None, encoding=u'utf8', nexson_syntax_version=DEFAULT_NEXSON_VERSION): """Converts an XML doc to JSON using the honeybadgerfish convention (see to_honeybadgerfi...
Take a dict form of NexSON and converts its datastructures to those needed to serialize as out_nexson_format. If current_format is not specified, it will be inferred. If `remove_old_structs` is False and different honeybadgerfish varieties are selected, the `blob` will be 'fat" containing both types...
def convert_nexson_format(blob, out_nexson_format, current_format=None, remove_old_structs=True, pristine_if_invalid=False, sort_arbitrary=False): """Take a dict form of NexSON and conve...
For v0.0 (which has meta values in a list), this function recursively walks through the object and sorts each meta by @property or @rel values.
def sort_meta_elements(blob): """For v0.0 (which has meta values in a list), this function recursively walks through the object and sorts each meta by @property or @rel values. """ v = detect_nexson_version(blob) if _is_badgerfish_version(v): _recursive_sort_meta(blob, '') return blo...
Takes a list of dicts each of which has an '@id' key, sorts the elements in the list by the value of the @id key. Assumes that @id is unique or the dicts have a meaningul < operator
def _inplace_sort_by_id(unsorted_list): """Takes a list of dicts each of which has an '@id' key, sorts the elements in the list by the value of the @id key. Assumes that @id is unique or the dicts have a meaningul < operator """ if not isinstance(unsorted_list, list): return sorted_list ...
Primarily used for testing (getting nice diffs). Calls sort_meta_elements and then sorts otu, node and edge list by id
def sort_arbitrarily_ordered_nexson(blob): """Primarily used for testing (getting nice diffs). Calls sort_meta_elements and then sorts otu, node and edge list by id """ # otu, node and edge elements have no necessary orger in v0.0 or v1.0 v = detect_nexson_version(blob) nex = get_nexml_el(blob) ...
`label_key` is a string (a key in the otu object) or a callable that takes two arguments: the node, and the otu If `leaf_labels` is not None, it shoulr be a (list, dict) pair which will be filled. The list will hold the order encountered, and the dict will map name to index in the list
def _write_newick_leaf_label(out, node_id, node, otu_group, label_key, leaf_labels, unlabeled_counter, needs_quotes_pattern): """ `label_key` is a string (a key in the otu object) or a callable that takes two arguments: the node, and the otu If `leaf_labels` is not None, it shoulr be a (list, dict) pair whi...
`label_key` is a string (a key in the otu object) or a callable that takes two arguments: the node, and the otu (which may be None for an internal node) If `leaf_labels` is not None, it shoulr be a (list, dict) pair which will be filled. The list will hold the order encountered, and the dict...
def _write_newick_internal_label(out, node_id, node, otu_group, label_key, needs_quotes_pattern): """`label_key` is a string (a key in the otu object) or a callable that takes two arguments: the node, and the otu (which may be None for an internal node) If `leaf_labels` is not None, it shoulr be a (list...
`label_key` is a string (a key in the otu object) or a callable that takes two arguments: the node, and the otu (which may be None for an internal node) If `leaf_labels` is not None, it shoulr be a (list, dict) pair which will be filled. The list will hold the order encountered, and the dict...
def convert_tree_to_newick(tree, otu_group, label_key, leaf_labels, needs_quotes_pattern=NEWICK_NEEDING_QUOTING, subtree_id=None, bracket_ingroup=False): ...
`label_key` is a string (a key in the otu object) or a callable that takes two arguments: the node, and the otu (which may be None for an internal node) If `leaf_labels` is not None, it shoulr be a (list, dict) pair which will be filled. The list will hold the order encountered, and the dict...
def nexson_frag_write_newick(out, edges, nodes, otu_group, label_key, leaf_labels, root_id, needs_quotes_pattern=NEWI...
Modifies `nexson` and returns it in version 1.2.1 with any tree that does not match the ID removed. Note that this does not search through the NexSON for every node, edge, tree that was deleted. So the resulting NexSON may have broken references !
def cull_nonmatching_trees(nexson, tree_id, curr_version=None): """Modifies `nexson` and returns it in version 1.2.1 with any tree that does not match the ID removed. Note that this does not search through the NexSON for every node, edge, tree that was deleted. So the resulting NexSON may have brok...
Returns a list of (id, tree, otus_group) tuples for the specified tree_id (all trees if tree_id is None)
def extract_tree_nexson(nexson, tree_id, curr_version=None): """Returns a list of (id, tree, otus_group) tuples for the specified tree_id (all trees if tree_id is None) """ if curr_version is None: curr_version = detect_nexson_version(nexson) if not _is_by_id_hbf(curr_version): nexso...
Returns URL and param dict for a GET call to phylesystem_api
def phylesystem_api_url(self, base_url, study_id): """Returns URL and param dict for a GET call to phylesystem_api """ p = self._phylesystem_api_params() e = self._phylesystem_api_ext() if self.content == 'study': return '{d}/study/{i}{e}'.format(d=base_url, i=study_i...
Determine whether the current contents are valid
def _is_valid(self, log: Optional[Logger] = None) -> bool: """ Determine whether the current contents are valid """ return self._validate(self, log)[0]
Determine whether val is a valid instance of this array :returns: Success indicator and error list
def _validate(self, val: list, log: Optional[Logger] = None) -> Tuple[bool, List[str]]: """ Determine whether val is a valid instance of this array :returns: Success indicator and error list """ errors = [] if not isinstance(val, list): errors.append(f"{self._variable_name}:...
Takes a dict corresponding to the honeybadgerfish JSON blob of the 1.0.* type and converts it to BY_ID_HONEY_BADGERFISH version. The object is modified in place and returned.
def convert(self, obj): """Takes a dict corresponding to the honeybadgerfish JSON blob of the 1.0.* type and converts it to BY_ID_HONEY_BADGERFISH version. The object is modified in place and returned. """ if self.pristine_if_invalid: raise NotImplementedError('pristi...
Takes a dict corresponding to the honeybadgerfish JSON blob of the 1.2.* type and converts it to DIRECT_HONEY_BADGERFISH version. The object is modified in place and returned.
def convert(self, obj): """Takes a dict corresponding to the honeybadgerfish JSON blob of the 1.2.* type and converts it to DIRECT_HONEY_BADGERFISH version. The object is modified in place and returned. """ if self.pristine_if_invalid: raise NotImplementedError('prist...
t, trace=0 -> (t1, t2, shift). Split a table to save space. t is a sequence of ints. This function can be useful to save space if many of the ints are the same. t1 and t2 are lists of ints, and shift is an int, chosen to minimize the combined size of t1 and t2 (in C code), and where for each i in ra...
def splitbins(t, trace=0): """t, trace=0 -> (t1, t2, shift). Split a table to save space. t is a sequence of ints. This function can be useful to save space if many of the ints are the same. t1 and t2 are lists of ints, and shift is an int, chosen to minimize the combined size of t1 and t2 (in C ...
otu_sort can be None (not sorted or stable), True (sorted by ID lexigraphically) or a key function for a sort function on list of otuIDs Note that if there are multiple OTU groups, the NexSON specifies the order of sorting of the groups (so the sort argument here only refers to the sorting of OTUs with...
def otu_iter_nexson_proxy(nexson_proxy, otu_sort=None): """otu_sort can be None (not sorted or stable), True (sorted by ID lexigraphically) or a key function for a sort function on list of otuIDs Note that if there are multiple OTU groups, the NexSON specifies the order of sorting of the groups (so...
Iterates over NexsonTreeProxy objects in order determined by the nexson blob
def tree_iter_nexson_proxy(nexson_proxy): """Iterates over NexsonTreeProxy objects in order determined by the nexson blob""" nexml_el = nexson_proxy._nexml_el tg_order = nexml_el['^ot:treesElementOrder'] tgd = nexml_el['treesById'] for tg_id in tg_order: tg = tgd[tg_id] tree_order = ...
Takes a tree in "By ID" NexSON (v1.2). provides and iterator over: NexsonNodeProxy object where the edge of the object is the edge connectin the node to the parent. The first node will be the root and will have None as it's edge
def nexson_tree_preorder_iter(tree_proxy, node_id=None, node=None, edge_id=None, edge=None): """Takes a tree in "By ID" NexSON (v1.2). provides and iterator over: NexsonNodeProxy object where the edge of the object is the edge connectin the node to the parent. The first node will be the root and wi...
Returns a reference to the dict of target node id to (edge_id, edge)
def edge_by_target(self): """Returns a reference to the dict of target node id to (edge_id, edge)""" if self._edge_by_target is None: self._edge_by_target = reverse_edge_by_source_dict(self._edge_by_source_id, self._nexson_tree['...
Get status from APC NIS and print output on stdout.
def main(): """Get status from APC NIS and print output on stdout.""" # No need to use "proper" names on such simple code. # pylint: disable=invalid-name p = argparse.ArgumentParser() p.add_argument("--host", default="localhost") p.add_argument("--port", type=int, default=3551) p.add_argumen...
A basic WSGI app
def wsgi_app(self, environ, start_response): """A basic WSGI app""" @_LOCAL_MANAGER.middleware def _wrapped_app(environ, start_response): request = Request(environ) setattr(_local, _CURRENT_REQUEST_KEY, request) response = self._dispatch_request(request) ...
For debugging purposes, you can run this as a standalone server. .. WARNING:: **Security vulnerability** This uses :class:`DebuggedJsonRpcApplication` to assist debugging. If you want to use this in production, you should run :class:`Server` as a standard WSGI app with `uWS...
def run(self, host, port, **options): """For debugging purposes, you can run this as a standalone server. .. WARNING:: **Security vulnerability** This uses :class:`DebuggedJsonRpcApplication` to assist debugging. If you want to use this in production, you should run :class:`Ser...
Runs each function from ``self.before_first_request_funcs`` once and only once.
def _try_trigger_before_first_request_funcs(self): # pylint: disable=C0103 """Runs each function from ``self.before_first_request_funcs`` once and only once.""" if self._after_first_request_handled: return else: with self._before_first_request_lock: if se...
Run the application and preserve the traceback frames. :param environ: The environment which is passed into the wsgi application :type environ: dict[str, object] :param start_response: The start_response function of the wsgi application :type start_response: (str, list[(str, str)]) -> N...
def debug_application(self, environ, start_response): """Run the application and preserve the traceback frames. :param environ: The environment which is passed into the wsgi application :type environ: dict[str, object] :param start_response: The start_response function of the wsgi appli...
Handles the debug endpoint for inspecting previous errors. :param environ: The environment which is passed into the wsgi application :type environ: dict[str, object] :param start_response: The start_response function of the wsgi application :type start_response: (str, list[(str, str)]) ...
def handle_debug(self, environ, start_response, traceback_id): """Handles the debug endpoint for inspecting previous errors. :param environ: The environment which is passed into the wsgi application :type environ: dict[str, object] :param start_response: The start_response function of t...
Normalize treebase-specific metadata into the locations where open tree of life software that expects it. See get_ot_study_info_from_nexml for the explanation of the src, nexml_content, encoding, and nexson_syntax_version arguments If merge_blocks is True then peyotl.manip.merge_otus_and_trees Act...
def get_ot_study_info_from_treebase_nexml(src=None, nexml_content=None, encoding=u'utf8', nexson_syntax_version=DEFAULT_NEXSON_VERSION, merge_blocks=Tru...
Flask application initialization.
def init_app(self, app): """Flask application initialization.""" self.init_config(app) app.cli.add_command(cmd) app.extensions['invenio-communities'] = self # Register the jinja do extension app.jinja_env.add_extension('jinja2.ext.do') self.register_signals(app)
Register the signals.
def register_signals(self, app): """Register the signals.""" before_record_index.connect(inject_provisional_community) if app.config['COMMUNITIES_OAI_ENABLED']: listen(Community, 'after_insert', create_oaipmh_set) listen(Community, 'after_delete', destroy_oaipmh_set) ...
Create a command line parser :return: parser
def genargs() -> ArgumentParser: """ Create a command line parser :return: parser """ parser = ArgumentParser() parser.add_argument("spec", help="JSG specification - can be file name, URI or string") parser.add_argument("-o", "--outfile", help="Output python file - if omitted, python is not...
Convert a URL or file name to a string
def _to_string(inp: str) -> str: """ Convert a URL or file name to a string """ if '://' in inp: req = requests.get(inp) if not req.ok: raise ValueError(f"Unable to read {inp}") return req.text else: with open(inp) as infile: ...
Determine whether json conforms with the JSG specification :param json: JSON string, URI to JSON or file name with JSON :param name: Test name for ValidationResult -- printed in dx if present :param verbose: True means print the response :return: pass/fail + fail reason
def conforms(self, json: str, name: str = "", verbose: bool=False) -> ValidationResult: """ Determine whether json conforms with the JSG specification :param json: JSON string, URI to JSON or file name with JSON :param name: Test name for ValidationResult -- printed in dx if present :pa...
#WARNING not thread safe just a easy of debugging routine!
def _write_to_next_free(tag, blob): """#WARNING not thread safe just a easy of debugging routine!""" ind = 0 pref = '/tmp/peyotl-' + tag + str(ind) while os.path.exists(pref): ind += 1 pref = '/tmp/peyotl-' + tag + str(ind) write_as_json(blob, pref)
Runs the nexson validator and returns a converted 4 object: nexson, annotation, validation_log, nexson_adaptor `nexson` is the nexson dict. `output_version` is the version of nexson syntax to be used after validation. if `allow_invalid` is False, and the nexson validation has errors, then a...
def validate_and_convert_nexson(nexson, output_version, allow_invalid, **kwargs): """Runs the nexson validator and returns a converted 4 object: nexson, annotation, validation_log, nexson_adaptor `nexson` is the nexson dict. `output_version` is the version of nexson syntax to be used after validati...
Actually make a local Git commit and push it to our remote
def commit_and_try_merge2master(git_action, file_content, study_id, auth_info, parent_sha, commit_msg='', merged_sha=None): ...
merge from master into the WIP for this study/author this is needed to allow a worker's future saves to be merged seamlessly into master
def merge_from_master(git_action, study_id, auth_info, parent_sha): """merge from master into the WIP for this study/author this is needed to allow a worker's future saves to be merged seamlessly into master """ return _merge_from_master(git_action, doc_id=study_id, ...
Explicit entry. Perform ancestor opening operations, then synchronize revocation registry to tails tree content. :return: current object
async def open(self) -> 'Issuer': """ Explicit entry. Perform ancestor opening operations, then synchronize revocation registry to tails tree content. :return: current object """ LOGGER.debug('Issuer.open >>>') await super().open() for path_rr_id in Tai...
Create revocation registry and new tails file (and association to corresponding revocation registry definition via symbolic link) for input revocation registry identifier. :param rr_id: revocation registry identifier :param rr_size: revocation registry size (defaults to 256)
async def _create_rev_reg(self, rr_id: str, rr_size: int = None) -> None: """ Create revocation registry and new tails file (and association to corresponding revocation registry definition via symbolic link) for input revocation registry identifier. :param rr_id: revocation regi...
Create revoc registry if need be for input revocation registry identifier; open and cache tails file reader. :param rr_id: revocation registry identifier :param rr_size: if new revocation registry necessary, its size (default as per _create_rev_reg())
async def _sync_revoc(self, rr_id: str, rr_size: int = None) -> None: """ Create revoc registry if need be for input revocation registry identifier; open and cache tails file reader. :param rr_id: revocation registry identifier :param rr_size: if new revocation registry necessar...
Return path to tails file for input revocation registry identifier. :param rr_id: revocation registry identifier of interest :return: path to tails file for input revocation registry identifier
def path_tails(self, rr_id: str) -> str: """ Return path to tails file for input revocation registry identifier. :param rr_id: revocation registry identifier of interest :return: path to tails file for input revocation registry identifier """ return Tails.linked(self._d...
Create credential offer as Issuer for given schema. Raise CorruptWallet if the wallet has no private key for the corresponding credential definition. :param schema_seq_no: schema sequence number :return: credential offer json for use in storing credentials at HolderProver.
async def create_cred_offer(self, schema_seq_no: int) -> str: """ Create credential offer as Issuer for given schema. Raise CorruptWallet if the wallet has no private key for the corresponding credential definition. :param schema_seq_no: schema sequence number :return: credenti...
Create credential as Issuer out of credential request and dict of key:value (raw, unencoded) entries for attributes. Return credential json, and if cred def supports revocation, credential revocation identifier and revocation registry delta ledger timestamp (epoch seconds). If the cred...
async def create_cred( self, cred_offer_json, cred_req_json: str, cred_attrs: dict, rr_size: int = None) -> (str, str, int): """ Create credential as Issuer out of credential request and dict of key:value (raw, unencoded) entries for at...
Revoke credential that input revocation registry identifier and credential revocation identifier specify. Return (epoch seconds) time of revocation. Raise AbsentTails if no tails file is available for input revocation registry identifier. Raise BadRevocation if issuer cannot re...
async def revoke_cred(self, rr_id: str, cr_id) -> int: """ Revoke credential that input revocation registry identifier and credential revocation identifier specify. Return (epoch seconds) time of revocation. Raise AbsentTails if no tails file is available for input revo...
Return json object on lists of all unique box identifiers (schema identifiers, credential definition identifiers, and revocation registry identifiers) for all credential definitions and credentials issued; e.g., :: { "schema_id": [ "R17v42T4pk...:2:tombstone...
async def get_box_ids_json(self) -> str: """ Return json object on lists of all unique box identifiers (schema identifiers, credential definition identifiers, and revocation registry identifiers) for all credential definitions and credentials issued; e.g., :: { ...
Format a value for display as an XML text node. Returns: Unicode string (str on Python 3, unicode on Python 2)
def quote_xml(text): """Format a value for display as an XML text node. Returns: Unicode string (str on Python 3, unicode on Python 2) """ text = _coerce_unicode(text) # If it's a CDATA block, return the text as is. if text.startswith(CDATA_START): return text # If it's no...
Initialize this instance from a namespace URI, and optional prefix and schema location URI.
def __construct_from_components(self, ns_uri, prefix=None, schema_location=None): """Initialize this instance from a namespace URI, and optional prefix and schema location URI.""" assert ns_uri # other fields are optional self.uri = ns_uri self.schema_location = schema_locatio...
Internal method to directly add a _NamespaceInfo object to this set. No sanity checks are done (e.g. checking for prefix conflicts), so be sure to do it yourself before calling this.
def __add_namespaceinfo(self, ni): """Internal method to directly add a _NamespaceInfo object to this set. No sanity checks are done (e.g. checking for prefix conflicts), so be sure to do it yourself before calling this.""" self.__ns_uri_map[ni.uri] = ni for prefix in ni.prefixe...
If existing_ni_or_ns_uri is a _NamespaceInfo object (which must be in this set), then caller wants to map incoming_prefix to that namespace. This function verifies that the prefix isn't already mapped to a different namespace URI. If it is, an exception is raised. Otherwise, existing_...
def __check_prefix_conflict(self, existing_ni_or_ns_uri, incoming_prefix): """If existing_ni_or_ns_uri is a _NamespaceInfo object (which must be in this set), then caller wants to map incoming_prefix to that namespace. This function verifies that the prefix isn't already mapped to a dif...
Get the namespace the given prefix maps to. Args: prefix (str): The prefix Returns: str: The namespace, or None if the prefix isn't mapped to anything in this set.
def namespace_for_prefix(self, prefix): """Get the namespace the given prefix maps to. Args: prefix (str): The prefix Returns: str: The namespace, or None if the prefix isn't mapped to anything in this set. """ try: ni = self....
Sets the preferred prefix for ns_uri. If add_if_not_exist is True, the prefix is added if it's not already registered. Otherwise, setting an unknown prefix as preferred is an error. The default is False. Setting to None always works, and indicates a preference to use the namespace as...
def set_preferred_prefix_for_namespace(self, ns_uri, prefix, add_if_not_exist=False): """Sets the preferred prefix for ns_uri. If add_if_not_exist is True, the prefix is added if it's not already registered. Otherwise, setting an unknown prefix as preferred is an error. The default is...
Merge incoming_schemaloc into the given `_NamespaceInfo`, ni. If we don't have one yet and the incoming value is non-None, update ours with theirs. This modifies ni.
def __merge_schema_locations(self, ni, incoming_schemaloc): """Merge incoming_schemaloc into the given `_NamespaceInfo`, ni. If we don't have one yet and the incoming value is non-None, update ours with theirs. This modifies ni. """ if ni.schema_location == incoming_schemaloc: ...
Removes the indicated namespace from this set.
def remove_namespace(self, ns_uri): """Removes the indicated namespace from this set.""" if not self.contains_namespace(ns_uri): return ni = self.__ns_uri_map.pop(ns_uri) for prefix in ni.prefixes: del self.__prefix_map[prefix]
Adds a new namespace to this set, optionally with a prefix and schema location URI. If the namespace already exists, the given prefix and schema location are merged with the existing entry: * If non-None, ``prefix`` is added to the set. The preferred prefix is not m...
def add_namespace_uri(self, ns_uri, prefix=None, schema_location=None): """Adds a new namespace to this set, optionally with a prefix and schema location URI. If the namespace already exists, the given prefix and schema location are merged with the existing entry: * If non-N...
Adds prefix for the given namespace URI. The namespace must already exist in this set. If set_as_preferred is True, also set this namespace as the preferred one. ``prefix`` must be non-None; a default preference can't be set this way. See :meth:`set_preferred_prefix_for_namespace` for...
def add_prefix(self, ns_uri, prefix, set_as_preferred=False): """Adds prefix for the given namespace URI. The namespace must already exist in this set. If set_as_preferred is True, also set this namespace as the preferred one. ``prefix`` must be non-None; a default preference can't be...
Gets (a copy of) the prefix set for the given namespace.
def get_prefixes(self, ns_uri): """Gets (a copy of) the prefix set for the given namespace.""" ni = self.__lookup_uri(ns_uri) return ni.prefixes.copy()
Gets an iterator over the prefixes for the given namespace.
def prefix_iter(self, ns_uri): """Gets an iterator over the prefixes for the given namespace.""" ni = self.__lookup_uri(ns_uri) return iter(ni.prefixes)
Removes prefix from this set. This is a no-op if the prefix doesn't exist in it.
def remove_prefix(self, prefix): """Removes prefix from this set. This is a no-op if the prefix doesn't exist in it. """ if prefix not in self.__prefix_map: return ni = self.__lookup_prefix(prefix) ni.prefixes.discard(prefix) del self.__prefix_map[pr...
Sets the schema location of the given namespace. If ``replace`` is ``True``, then any existing schema location is replaced. Otherwise, if the schema location is already set to a different value, an exception is raised. If the schema location is set to None, it is effectively erased fr...
def set_schema_location(self, ns_uri, schema_location, replace=False): """Sets the schema location of the given namespace. If ``replace`` is ``True``, then any existing schema location is replaced. Otherwise, if the schema location is already set to a different value, an exception is r...
Generates XML namespace declarations for namespaces in this set. It must be suitable for use in an actual XML document, so an exception is raised if this can't be done, e.g. if it would have more than one default namespace declaration. If ``preferred_prefixes_only`` is ``True`` and a n...
def get_xmlns_string(self, ns_uris=None, sort=False, preferred_prefixes_only=True, delim="\n"): """Generates XML namespace declarations for namespaces in this set. It must be suitable for use in an actual XML document, so an exception is raised if this can't be done, e....
Constructs and returns a schemalocation attribute. If no namespaces in this set have any schema locations defined, returns an empty string. Args: ns_uris (iterable): The namespaces to include in the constructed attribute value. If None, all are included. ...
def get_schemaloc_string(self, ns_uris=None, sort=False, delim="\n"): """Constructs and returns a schemalocation attribute. If no namespaces in this set have any schema locations defined, returns an empty string. Args: ns_uris (iterable): The namespaces to include in the co...
Constructs and returns a map from namespace URI to prefix, representing all namespaces in this set. The prefix chosen for each namespace is its preferred prefix if it's not None. If the preferred prefix is None, one is chosen from the set of registered prefixes. In the latter situatio...
def get_uri_prefix_map(self): """Constructs and returns a map from namespace URI to prefix, representing all namespaces in this set. The prefix chosen for each namespace is its preferred prefix if it's not None. If the preferred prefix is None, one is chosen from the set of registered ...
Constructs and returns a map from namespace URI to schema location URI. Namespaces without schema locations are excluded.
def get_uri_schemaloc_map(self): """Constructs and returns a map from namespace URI to schema location URI. Namespaces without schema locations are excluded.""" mapping = {} for ni in six.itervalues(self.__ns_uri_map): if ni.schema_location: mapping[ni.uri] ...
Return a subset of this NamespaceSet containing only data for the given namespaces. Args: ns_uris (iterable): An iterable of namespace URIs which select the namespaces for the subset. Returns: The subset Raises: NamespaceNotFoundErro...
def subset(self, ns_uris): """Return a subset of this NamespaceSet containing only data for the given namespaces. Args: ns_uris (iterable): An iterable of namespace URIs which select the namespaces for the subset. Returns: The subset Rai...
Imports namespaces into this set, from other_ns. Args: other_ns (NamespaceSet): The set to import from replace (bool): If a namespace exists in both sets, do we replace our data with other_ns's data? We could get fancy and define some merge strategies, b...
def import_from(self, other_ns, replace=False): """Imports namespaces into this set, from other_ns. Args: other_ns (NamespaceSet): The set to import from replace (bool): If a namespace exists in both sets, do we replace our data with other_ns's data? We could ge...
For debugging; does some sanity checks on this set. Raises InvalidNamespaceSetError if this namespace set is invalid. Otherwise, raises/returns nothing.
def assert_valid(self): """For debugging; does some sanity checks on this set. Raises InvalidNamespaceSetError if this namespace set is invalid. Otherwise, raises/returns nothing.""" for ns_uri, ni in six.iteritems(self.__ns_uri_map): if not ni.uri: raise I...
Return the version of the root element passed in. Args: root (etree.Element) Returns: distutils.StrictVersion Raises: UnknownVersionError
def _get_version(self, root): """Return the version of the root element passed in. Args: root (etree.Element) Returns: distutils.StrictVersion Raises: UnknownVersionError """ # Note: STIX and MAEC use a "version" attribute. To suppor...
Ensure the root element is a supported version. Args: root (etree.Element) Raises: UnsupportedVersionError
def _check_version(self, root): """Ensure the root element is a supported version. Args: root (etree.Element) Raises: UnsupportedVersionError """ version = self._get_version(root) supported = [StrictVersion(x) for x in self.s...
Check that the XML element tree has a supported root element. Args: root (etree.Element) Raises: UnsupportedRootElementError
def _check_root_tag(self, root): """Check that the XML element tree has a supported root element. Args: root (etree.Element) Raises: UnsupportedRootElementError """ supported = self.supported_tags() if root.tag in supported: return ...
Creates a STIX binding object from the supplied xml file. Args: xml_file: A filename/path or a file-like object representing a STIX instance document check_version: Inspect the version before parsing. check_root: Inspect the root element before parsing. ...
def parse_xml_to_obj(self, xml_file, check_version=True, check_root=True, encoding=None): """Creates a STIX binding object from the supplied xml file. Args: xml_file: A filename/path or a file-like object representing a STIX instance document ...
Creates a python-stix STIXPackage object from the supplied xml_file. Args: xml_file: A filename/path or a file-like object representing a STIX instance document check_version: Inspect the version before parsing. check_root: Inspect the root element before par...
def parse_xml(self, xml_file, check_version=True, check_root=True, encoding=None): """Creates a python-stix STIXPackage object from the supplied xml_file. Args: xml_file: A filename/path or a file-like object representing a STIX instance document ...
Syntactic sugar around to make it easier to get fine-grained access to the parts of a file without composing a PhyloSchema object. Possible invocations include: w.get('pg_10') w.get('pg_10', 'trees') w.get('pg_10', 'trees', format='nexus') w.get('pg_10', t...
def get(self, collection_id, content=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') w.g...
HTTP REQUEST GET https://api.nasa.gov/patents QUERY PARAMETERS Parameter Type Default Description query string None Search text to filter results concept_tags bool False Return an ordered dictionary of concepts from the patent abstract limit int all number of patents to return api_key str...
def patents(query=None, concept_tags=None, limit=None): ''' HTTP REQUEST GET https://api.nasa.gov/patents QUERY PARAMETERS Parameter Type Default Description query string None Search text to filter results concept_tags bool False Return an ordered dictionary of concepts from the patent ab...
Factory for record links generation.
def default_links_item_factory(community): """Factory for record links generation.""" return dict( self=url_for( '.communities_item', community_id=community['id'], _external=True), html=current_app.config.get( 'COMMUNITIES_URL_COMMUNITY_VIEW', '{protocol}://{h...
Factory for record links generation.
def default_links_pagination_factory(page, urlkwargs): """Factory for record links generation.""" endpoint = '.communities_list' links = { 'self': url_for(endpoint, page=page.page, _external=True, **urlkwargs), } if page.has_prev: links['prev'] = url_for(endpoint, page=page.prev_nu...
Takes a dict corresponding to the honeybadgerfish JSON blob of the 1.0.* type and converts it to BY_ID_HONEY_BADGERFISH version. The object is modified in place and returned.
def convert(self, obj): """Takes a dict corresponding to the honeybadgerfish JSON blob of the 1.0.* type and converts it to BY_ID_HONEY_BADGERFISH version. The object is modified in place and returned. """ if self.pristine_if_invalid: raise NotImplementedError('pristi...
Get the community logo URL.
def get_logo_url(self, obj): """Get the community logo URL.""" if current_app and obj.logo_url: return u'{site_url}{path}'.format( site_url=current_app.config.get('THEME_SITEURL'), path=obj.logo_url, )
Add the links for each community.
def item_links_addition(self, data): """Add the links for each community.""" links_item_factory = self.context.get('links_item_factory', default_links_item_factory) data['links'] = links_item_factory(data) return data
Wrap result in envelope.
def envelope(self, data, many): """Wrap result in envelope.""" if not many: return data result = dict( hits=dict( hits=data, total=self.context.get('total', len(data)) ) ) page = self.context.get('page') ...
Attempts to parse `value` into an instance of ``datetime.datetime``. If `value` is ``None``, this function will return ``None``. Args: value: A timestamp. This can be a string or datetime.datetime value.
def parse_datetime(value): """Attempts to parse `value` into an instance of ``datetime.datetime``. If `value` is ``None``, this function will return ``None``. Args: value: A timestamp. This can be a string or datetime.datetime value. """ if not value: return None elif isinstanc...