INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Determine whether element conforms to etype :param element: Element to test for conformance :param etype: Type to test against :param namespace: Namespace to use to resolve forward references :return:
def conforms(element, etype, namespace: Dict[str, Any]) -> bool: """ Determine whether element conforms to etype :param element: Element to test for conformance :param etype: Type to test against :param namespace: Namespace to use to resolve forward references :return: """ etype = proc_forw...
Upgrade database.
def upgrade(): """Upgrade database.""" op.create_table( 'communities_community', sa.Column('created', sa.DateTime(), nullable=False), sa.Column('updated', sa.DateTime(), nullable=False), sa.Column('id', sa.String(length=100), nullable=False), sa.Column('id_user', sa.Integ...
Get a list of all the communities. .. http:get:: /communities/(string:id) Returns a JSON list with all the communities. **Request**: .. sourcecode:: http GET /communities HTTP/1.1 Accept: application/json Content-Type: applicat...
def get(self, query, sort, page, size): """Get a list of all the communities. .. http:get:: /communities/(string:id) Returns a JSON list with all the communities. **Request**: .. sourcecode:: http GET /communities HTTP/1.1 Accept: appl...
Factory function for a _Phylesystem object. A wrapper around the _Phylesystem class instantiation for the most common use case: a singleton _Phylesystem. If you need distinct _Phylesystem objects, you'll need to call that class directly.
def Phylesystem(repos_dict=None, repos_par=None, with_caching=True, repo_nexml2json=None, git_ssh=None, pkey=None, git_action_class=PhylesystemGitAction, mirror_info=None, new_study_prefix=Non...
Type-specific configuration for backward compatibility
def write_configuration(self, out, secret_attrs=False): """Type-specific configuration for backward compatibility""" key_order = ['repo_nexml2json', 'number_of_shards', 'initialization', ] cd = self.get_configuration_dict(secret_attrs=secret_attrs) ...
Type-specific configuration for backward compatibility
def get_configuration_dict(self, secret_attrs=False): """Type-specific configuration for backward compatibility""" cd = {'repo_nexml2json': self.repo_nexml2json, 'number_of_shards': len(self._shards), 'initialization': self._filepath_args, 'shards': [], ...
Converts HTML5 character references within text_string to their corresponding unicode characters and returns converted string as type str. Keyword argument: - text_string: string instance Exceptions raised: - InputError: occurs should a non-string argument be passed
def convert_html_entities(text_string): ''' Converts HTML5 character references within text_string to their corresponding unicode characters and returns converted string as type str. Keyword argument: - text_string: string instance Exceptions raised: - InputError: occurs should a non-str...
Coverts Latin character references within text_string to their corresponding unicode characters and returns converted string as type str. Keyword argument: - text_string: string instance Exceptions raised: - InputError: occurs should a string or NoneType not be passed as an argument
def convert_ligatures(text_string): ''' Coverts Latin character references within text_string to their corresponding unicode characters and returns converted string as type str. Keyword argument: - text_string: string instance Exceptions raised: - InputError: occurs should a string or No...
Splits string and converts words not found within a pre-built dictionary to their most likely actual word based on a relative probability dictionary. Returns edited string as type str. Keyword argument: - text_string: string instance Exceptions raised: - InputError: occurs should a string or...
def correct_spelling(text_string): ''' Splits string and converts words not found within a pre-built dictionary to their most likely actual word based on a relative probability dictionary. Returns edited string as type str. Keyword argument: - text_string: string instance Exceptions raise...
Splits text_string into a list of sentences based on NLTK's english.pickle tokenizer, and returns said list as type list of str. Keyword argument: - text_string: string instance Exceptions raised: - InputError: occurs should a non-string argument be passed
def create_sentence_list(text_string): ''' Splits text_string into a list of sentences based on NLTK's english.pickle tokenizer, and returns said list as type list of str. Keyword argument: - text_string: string instance Exceptions raised: - InputError: occurs should a non-string argumen...
Extracts keywords from text_string using NLTK's list of English stopwords, ignoring words of a length smaller than 3, and returns the new string as type str. Keyword argument: - text_string: string instance Exceptions raised: - InputError: occurs should a non-string argument be passed
def keyword_tokenize(text_string): ''' Extracts keywords from text_string using NLTK's list of English stopwords, ignoring words of a length smaller than 3, and returns the new string as type str. Keyword argument: - text_string: string instance Exceptions raised: - InputError: occurs sh...
Returns base from of text_string using NLTK's WordNetLemmatizer as type str. Keyword argument: - text_string: string instance Exceptions raised: - InputError: occurs should a non-string argument be passed
def lemmatize(text_string): ''' Returns base from of text_string using NLTK's WordNetLemmatizer as type str. Keyword argument: - text_string: string instance Exceptions raised: - InputError: occurs should a non-string argument be passed ''' if text_string is None ...
Converts text_string into lowercase and returns the converted string as type str. Keyword argument: - text_string: string instance Exceptions raised: - InputError: occurs should a non-string argument be passed
def lowercase(text_string): ''' Converts text_string into lowercase and returns the converted string as type str. Keyword argument: - text_string: string instance Exceptions raised: - InputError: occurs should a non-string argument be passed ''' if text_string is None or text_string ...
Removes any escape character within text_string and returns the new string as type str. Keyword argument: - text_string: string instance Exceptions raised: - InputError: occurs should a non-string argument be passed
def remove_esc_chars(text_string): ''' Removes any escape character within text_string and returns the new string as type str. Keyword argument: - text_string: string instance Exceptions raised: - InputError: occurs should a non-string argument be passed ''' if text_string is None or...
Given each function within function_list, applies the order of functions put forward onto text_string, returning the processed string as type str. Keyword argument: - function_list: list of functions available in preprocessing.text - text_string: string instance Exceptions raised: - Func...
def preprocess_text(text_string, function_list): ''' Given each function within function_list, applies the order of functions put forward onto text_string, returning the processed string as type str. Keyword argument: - function_list: list of functions available in preprocessing.text - text_st...
Removes any digit value discovered within text_string and returns the new string as type str. Keyword argument: - text_string: string instance Exceptions raised: - InputError: occurs should a non-string argument be passed
def remove_numbers(text_string): ''' Removes any digit value discovered within text_string and returns the new string as type str. Keyword argument: - text_string: string instance Exceptions raised: - InputError: occurs should a non-string argument be passed ''' if text_string is Non...
Removes any integer represented as a word within text_string and returns the new string as type str. Keyword argument: - text_string: string instance Exceptions raised: - InputError: occurs should a non-string argument be passed
def remove_number_words(text_string): ''' Removes any integer represented as a word within text_string and returns the new string as type str. Keyword argument: - text_string: string instance Exceptions raised: - InputError: occurs should a non-string argument be passed ''' if te...
Removes any word associated to time (day, week, month, etc.) within text_string and returns the new string as type str. Keyword argument: - text_string: string instance Exceptions raised: - InputError: occurs should a non-string argument be passed
def remove_time_words(text_string): ''' Removes any word associated to time (day, week, month, etc.) within text_string and returns the new string as type str. Keyword argument: - text_string: string instance Exceptions raised: - InputError: occurs should a non-string argument be passed ...
Removes all punctuation unattached from a non-whitespace or attached to another punctuation character unexpectedly (e.g. ".;';") within text_string and returns the new string as type str. Keyword argument: - text_string: string instance Exceptions raised: - InputError: occurs should a non-string...
def remove_unbound_punct(text_string): ''' Removes all punctuation unattached from a non-whitespace or attached to another punctuation character unexpectedly (e.g. ".;';") within text_string and returns the new string as type str. Keyword argument: - text_string: string instance Exceptions ra...
Removes all URLs within text_string and returns the new string as type str. Keyword argument: - text_string: string instance Exceptions raised: - InputError: occurs should a non-string argument be passed
def remove_urls(text_string): ''' Removes all URLs within text_string and returns the new string as type str. Keyword argument: - text_string: string instance Exceptions raised: - InputError: occurs should a non-string argument be passed ''' if text_string is None or text_string == "...
Removes all whitespace found within text_string and returns new string as type str. Keyword argument: - text_string: string instance Exceptions raised: - InputError: occurs should a string or NoneType not be passed as an argument
def remove_whitespace(text_string): ''' Removes all whitespace found within text_string and returns new string as type str. Keyword argument: - text_string: string instance Exceptions raised: - InputError: occurs should a string or NoneType not be passed as an argument ''' if text_st...
This is the primary method to override to ensure logging with extra options gets correctly specified.
def log(self, level, message, *args, **kwargs): """ This is the primary method to override to ensure logging with extra options gets correctly specified. """ extra = self.extras.copy() extra.update(kwargs.pop('extra', {})) kwargs['extra'] = extra self.log...
Specialized warnings system. If a warning subclass is passed into the keyword arguments and raise_warnings is True - the warnning will be passed to the warnings module.
def warning(self, message, *args, **kwargs): """ Specialized warnings system. If a warning subclass is passed into the keyword arguments and raise_warnings is True - the warnning will be passed to the warnings module. """ warncls = kwargs.pop('warning', None) if w...
Provide current user as extra context to the logger
def log(self, level, message, *args, **kwargs): """ Provide current user as extra context to the logger """ extra = kwargs.pop('extra', {}) extra.update({ 'user': self.user }) kwargs['extra'] = extra super(ServiceLogger, self).log(level, messa...
Instantiates and returns a ServiceLogger instance
def logger(self): """ Instantiates and returns a ServiceLogger instance """ if not hasattr(self, '_logger') or not self._logger: self._logger = ServiceLogger() return self._logger
Uses a peyotl wrapper around an Open Tree web service to get a list of studies including values `value` for a given property to be searched on `porperty`. The oti_wrapper can be None (in which case the default wrapper from peyotl.sugar will be used. All other arguments correspond to the arguments of the we...
def ot_find_studies(arg_dict, exact=True, verbose=False, oti_wrapper=None): """Uses a peyotl wrapper around an Open Tree web service to get a list of studies 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 peyot...
This function sets up a command-line option parser and then calls print_matching_trees to do all of the real work.
def main(argv): """This function sets up a command-line option parser and then calls print_matching_trees to do all of the real work. """ import argparse description = 'Uses Open Tree of Life web services to try to find a tree with the value property pair specified. ' \ 'setting --...
This function sets up a command-line option parser and then calls to do all of the real work.
def main(argv): """This function sets up a command-line option parser and then calls 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 = '''Takes a series of at least 2 OTT ids...
Searchers for JSON files in this repo and returns a map of collection id ==> (`tag`, dir, collection filepath) where `tag` is typically the shard name
def create_id2collection_info(path, tag): """Searchers for JSON files in this repo and returns a map of collection id ==> (`tag`, dir, collection filepath) where `tag` is typically the shard name """ d = {} for triple in os.walk(path): root, files = triple[0], triple[2] for filen...
Generic configuration, may be overridden by type-specific version
def write_configuration(self, out, secret_attrs=False): """Generic configuration, may be overridden by type-specific version""" key_order = ['name', 'path', 'git_dir', 'doc_dir', 'assumed_doc_version', 'git_ssh', 'pkey', 'has_aliases', 'number of collections'] cd = self.get_...
Overrides superclass method and renames some properties
def get_configuration_dict(self, secret_attrs=False): """Overrides superclass method and renames some properties""" cd = super(TreeCollectionsShard, self).get_configuration_dict(secret_attrs=secret_attrs) # "rename" some keys in the dict provided cd['number of collections'] = cd.pop('num...
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.collections_store import COLLECTION_ID_PATTERN p = set() for owner_dirname in os.listdir(self.doc_dir): example_collection_name = "{n}/xxxxx".format(n=o...
Checks out master branch as a side effect
def create_git_action_for_new_collection(self, new_collection_id=None): """Checks out master branch as a side effect""" ga = self.create_git_action() assert new_collection_id is not None # id should have been sorted out by the caller self.register_doc_id(ga, new_collection_id) ...
Determine if a value is a sequence type. Returns: ``True`` if `value` is a sequence type (e.g., ``list``, or ``tuple``). String types will return ``False``. NOTE: On Python 3, strings have the __iter__ defined, so a simple hasattr check is insufficient.
def is_sequence(value): """Determine if a value is a sequence type. Returns: ``True`` if `value` is a sequence type (e.g., ``list``, or ``tuple``). String types will return ``False``. NOTE: On Python 3, strings have the __iter__ defined, so a simple hasattr check is insufficient. """ ...
Import the class referred to by the fully qualified class path. Args: classpath: A full "foo.bar.MyClass" path to a class definition. Returns: The class referred to by the classpath. Raises: ImportError: If an error occurs while importing the module. AttributeError: IF the...
def import_class(classpath): """Import the class referred to by the fully qualified class path. Args: classpath: A full "foo.bar.MyClass" path to a class definition. Returns: The class referred to by the classpath. Raises: ImportError: If an error occurs while importing the mo...
Attempt to return a Python class for the input class reference. If `classref` is a class or None, return it. If `classref` is a python classpath (e.g., "foo.bar.MyClass") import the class and return it. Args: classref: A fully-qualified Python path to class, or a Python class. Returns: ...
def resolve_class(classref): """Attempt to return a Python class for the input class reference. If `classref` is a class or None, return it. If `classref` is a python classpath (e.g., "foo.bar.MyClass") import the class and return it. Args: classref: A fully-qualified Python path to class,...
Function decorator which checks that the decorated function is called with a set of required kwargs. Args: *argnames: String keyword argument names. Raises: ValueError: If a required kwarg is missing in the decorated function call.
def needkwargs(*argnames): """Function decorator which checks that the decorated function is called with a set of required kwargs. Args: *argnames: String keyword argument names. Raises: ValueError: If a required kwarg is missing in the decorated function call. """ ...
Connect to the APCUPSd NIS and request its status.
def get(host="localhost", port=3551, timeout=30): """ Connect to the APCUPSd NIS and request its status. """ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(timeout) sock.connect((host, port)) sock.send(CMD_STATUS) buffr = "" while not buffr.endswith(EOF): ...
Split the output from get_status() into lines, clean it up and return it as an OrderedDict.
def parse(raw_status, strip_units=False): """ Split the output from get_status() into lines, clean it up and return it as an OrderedDict. """ lines = split(raw_status) if strip_units: lines = strip_units_from_lines(lines) # Split each line on the SEP character, strip extraneous white...
Removes all units from the ends of the lines.
def strip_units_from_lines(lines): """ Removes all units from the ends of the lines. """ for line in lines: for unit in ALL_UNITS: if line.endswith(" %s" % unit): line = line[:-1-len(unit)] yield line
Print the status to stdout in the same format as the original apcaccess.
def print_status(raw_status, strip_units=False): """ Print the status to stdout in the same format as the original apcaccess. """ lines = split(raw_status) if strip_units: lines = strip_units_from_lines(lines) for line in lines: print(line)
Takes a name and optional contextName returns a list of matches. `wrap_response` can be True to return a TNRSResponse object, None to return the "raw" response dict, or a function/class that takes (response, query_data=dict) as its arguments. Each match is a dict with: ...
def TNRS(self, names, context_name=None, id_list=None, fuzzy_matching=False, include_deprecated=False, include_dubious=False, do_approximate_matching=None, wrap_response=None): """Takes a name and optional co...
Takes a name and optional context_name returns a list of matches. Each match is a dict with: 'higher' boolean DEF??? 'exact' boolean for exact match 'ottId' int 'name' name (or uniqname???) for the taxon in OTT 'nodeId' int ID of not in the taxomachine db....
def autocomplete(self, name, context_name=None, include_dubious=False): """Takes a name and optional context_name returns a list of matches. Each match is a dict with: 'higher' boolean DEF??? 'exact' boolean for exact match 'ottId' int 'name' name (or uniqnam...
delegates a call to TNRS (same arguments as that function). Returns a list of (non-dubious) OTT IDs in the same order as the original names. Raises a ValueError if each name does not have exactly one perfect, non-dubious (score = 1.0) match in the TNRS results.
def names_to_ott_ids_perfect(self, names, **kwargs): """delegates a call to TNRS (same arguments as that function). Returns a list of (non-dubious) OTT IDs in the same order as the original names. Raises a ValueError if each name does not have exactly one perfect, non-dubious (score = 1...
If the taxa are being cached, this call will create a the lineage "spike" for taxon child_taxon Expecting child_taxon to have a non-empty _taxonomic_lineage with response dicts that can create an ancestral TaxonWrapper.
def get_cached_parent_for_taxon(self, child_taxon): """If the taxa are being cached, this call will create a the lineage "spike" for taxon child_taxon Expecting child_taxon to have a non-empty _taxonomic_lineage with response dicts that can create an ancestral TaxonWrapper. """ ...
Return credential definition identifier for input issuer DID and schema sequence number. :param issuer_did: DID of credential definition issuer :param schema_seq_no: schema sequence number :return: credential definition identifier
def cred_def_id(issuer_did: str, schema_seq_no: int) -> str: """ Return credential definition identifier for input issuer DID and schema sequence number. :param issuer_did: DID of credential definition issuer :param schema_seq_no: schema sequence number :return: credential definition identifier ...
Given a credential definition identifier and a tag, return the corresponding revocation registry identifier, repeating the issuer DID from the input identifier. :param cd_id: credential definition identifier :param tag: tag to use :return: revocation registry identifier
def rev_reg_id(cd_id: str, tag: str) -> str: """ Given a credential definition identifier and a tag, return the corresponding revocation registry identifier, repeating the issuer DID from the input identifier. :param cd_id: credential definition identifier :param tag: tag to use :return: re...
Given a revocation registry identifier, return its corresponding credential definition identifier and (stringified int) tag. :param rr_id: revocation registry identifier :return: credential definition identifier and tag
def rev_reg_id2cred_def_id__tag(rr_id: str) -> (str, str): """ Given a revocation registry identifier, return its corresponding credential definition identifier and (stringified int) tag. :param rr_id: revocation registry identifier :return: credential definition identifier and tag """ ret...
Given a credentials structure and an optional list of credential identifiers (aka wallet cred-ids, referents; specify None to include all), return dict mapping each credential identifier to a box ids structure (i.e., a dict specifying its corresponding schema identifier, credential definition identifier, an...
def box_ids(creds: dict, cred_ids: list = None) -> dict: """ Given a credentials structure and an optional list of credential identifiers (aka wallet cred-ids, referents; specify None to include all), return dict mapping each credential identifier to a box ids structure (i.e., a dict specifying its corr...
Find indy-sdk creds matching input filter from within input creds structure, json-loaded as returned via HolderProver.get_creds(), and return human-legible summary. :param creds: creds structure returned by HolderProver.get_creds(); e.g., :: { "attrs": { "attr0_uuid": ...
def creds_display(creds: dict, filt: dict = None, filt_dflt_incl: bool = False) -> dict: """ Find indy-sdk creds matching input filter from within input creds structure, json-loaded as returned via HolderProver.get_creds(), and return human-legible summary. :param creds: creds structure returned by Hol...
Given a creds structure, return a dict mapping pairs (revocation registry identifier, credential revocation identifier) to (decoded) attribute name:value dicts. If the caller includes a filter of attribute:value pairs, retain only matching attributes. :param creds: creds structure returned by HolderPr...
def revoc_info(creds: dict, filt: dict = None) -> dict: """ Given a creds structure, return a dict mapping pairs (revocation registry identifier, credential revocation identifier) to (decoded) attribute name:value dicts. If the caller includes a filter of attribute:value pairs, retain only matching...
Fetch revealed attributes from input proof and return dict mapping credential definition identifiers to dicts, each dict mapping attribute names to (decoded) values, for processing in further creds downstream. :param: indy-sdk proof as dict :return: dict mapping cred-ids to dicts, each mapping revealed att...
def revealed_attrs(proof: dict) -> dict: """ Fetch revealed attributes from input proof and return dict mapping credential definition identifiers to dicts, each dict mapping attribute names to (decoded) values, for processing in further creds downstream. :param: indy-sdk proof as dict :return: dict...
Analyzes the request to find which country the user wants the system to recognize. It checks the following sources in the given order: * session, * cookie, * HTTP_ACCEPT_LANGUAGE HTTP header, and * IP address if USE_GEOIP is True. It returns country code in ISO 3166-1 alpha-2 format.
def get_country_from_request(request): """ Analyzes the request to find which country the user wants the system to recognize. It checks the following sources in the given order: * session, * cookie, * HTTP_ACCEPT_LANGUAGE HTTP header, and * IP address if USE_GEOIP is True. It return...
Updates the field of info about an OTU that might not be filled in by a match_names or taxon call.
def update_empty_fields(self, **kwargs): """Updates the field of info about an OTU that might not be filled in by a match_names or taxon call.""" if self._is_deprecated is None: self._is_deprecated = kwargs.get('is_deprecated') if self._is_dubious is None: self._is_dubiou...
Verifyies that `ebt` is the inverse of the `edgeBySourceId` data member of `tree`
def _check_rev_dict(tree, ebt): """Verifyies that `ebt` is the inverse of the `edgeBySourceId` data member of `tree`""" ebs = defaultdict(dict) for edge in ebt.values(): source_id = edge['@source'] edge_id = edge['@id'] ebs[source_id][edge_id] = edge assert ebs == tree['edgeBySou...
creates a edge_by_target dict with the same edge objects as the edge_by_source. Also adds an '@id' field to each edge.
def _create_edge_by_target(self): """creates a edge_by_target dict with the same edge objects as the edge_by_source. Also adds an '@id' field to each edge.""" ebt = {} for edge_dict in self._edge_by_source.values(): for edge_id, edge in edge_dict.items(): targ...
Remove nodes and edges from tree if they are not the ingroup or a descendant of it.
def prune_to_ingroup(self): """Remove nodes and edges from tree if they are not the ingroup or a descendant of it.""" # Prune to just the ingroup if not self._ingroup_node_id: _LOG.debug('No ingroup node was specified.') self._ingroup_node_id = self.root_node_id e...
Prune `node_id` and the edges and nodes that are tipward of it. Caller must delete the edge to node_id.
def prune_clade(self, node_id): """Prune `node_id` and the edges and nodes that are tipward of it. Caller must delete the edge to node_id.""" to_del_nodes = [node_id] while bool(to_del_nodes): node_id = to_del_nodes.pop(0) self._flag_node_as_del_and_del_in_by_targ...
Flags a node as deleted, and removes it from the _edge_by_target (and parent's edge_by_source), if it is still found there. Does NOT remove the node's entries from self._edge_by_source.
def _flag_node_as_del_and_del_in_by_target(self, node_id): """Flags a node as deleted, and removes it from the _edge_by_target (and parent's edge_by_source), if it is still found there. Does NOT remove the node's entries from self._edge_by_source.""" self.nodes_deleted.append(node_id) et...
Assumes that there is no entry in edge_by_source[node_id] to clean up.
def _del_tip(self, node_id): """Assumes that there is no entry in edge_by_source[node_id] to clean up.""" self.nodes_deleted.append(node_id) etp = self._edge_by_target.get(node_id) assert etp is not None source_id, target_id = self._del_edge(etp) assert target_id == node_...
returns a dict mapping ott_id to list of elements referring to leafs mapped to that ott_id. They keys will be ott_ids and None (for unmapped tips). The values are lists of tuples. Each tuple represents a different leaf and contains: (integer_for_of_is_examplar: -1 if the node is flagged by ^...
def group_and_sort_leaves_by_ott_id(self): """returns a dict mapping ott_id to list of elements referring to leafs mapped to that ott_id. They keys will be ott_ids and None (for unmapped tips). The values are lists of tuples. Each tuple represents a different leaf and contains: (inte...
Deletes to_par_edge and nd_id. To be used when nd_id is an out-degree= 1 node
def suppress_deg_one_node(self, to_par_edge, nd_id, to_child_edge): """Deletes to_par_edge and nd_id. To be used when nd_id is an out-degree= 1 node""" # circumvent the node with nd_id to_child_edge_id = to_child_edge['@id'] par = to_par_edge['@source'] self._edge_by_source[par][...
`to_prune_fsi_set` is a set of flag indices to be pruned.
def prune_tree_for_supertree(self, ott, to_prune_fsi_set, root_ott_id, taxonomy_treefile=None, id_to_other_prune_reason=None): """ `to_prun...
Describes the method. :return: Description :rtype: dict[str, object]
def describe(self): """Describes the method. :return: Description :rtype: dict[str, object] """ return { "name": self.name, "params": self.params, "returns": self.returns, "description": self.description, }
The parameters for this method in a JSON-compatible format :rtype: list[dict[str, str]]
def params(self): """The parameters for this method in a JSON-compatible format :rtype: list[dict[str, str]] """ return [{"name": p_name, "type": p_type.__name__} for (p_name, p_type) in self.signature.parameter_types]
The return type for this method in a JSON-compatible format. This handles the special case of ``None`` which allows ``type(None)`` also. :rtype: str | None
def returns(self): """The return type for this method in a JSON-compatible format. This handles the special case of ``None`` which allows ``type(None)`` also. :rtype: str | None """ return_type = self.signature.return_type none_type = type(None) if return_type i...
Returns a signature object ensuring order of parameter names and types. :param parameter_names: A list of ordered parameter names :type parameter_names: list[str] :param parameter_types: A dictionary of parameter names to types :type parameter_types: dict[str, type] :param retur...
def create(parameter_names, parameter_types, return_type): """Returns a signature object ensuring order of parameter names and types. :param parameter_names: A list of ordered parameter names :type parameter_names: list[str] :param parameter_types: A dictionary of parameter names to typ...
Returns a pair of the "child" content of minidom_node: the first element of the pair is a concatenation of the text content the second element is a list of non-text nodes. The string concatenation strips leading and trailing whitespace from each bit of text found and joins the fragments (with n...
def _extract_text_and_child_element_list(minidom_node): """Returns a pair of the "child" content of minidom_node: the first element of the pair is a concatenation of the text content the second element is a list of non-text nodes. The string concatenation strips leading and trailing whitespace ...
Builds a dictionary from the DOM element x The function Uses as hacky splitting of attribute or tag names using {} to remove namespaces. returns a pair of: the tag of `x` and the honeybadgerfish representation of the subelements of x Indirect recursion through _hb...
def _gen_hbf_el(self, x): """ Builds a dictionary from the DOM element x The function Uses as hacky splitting of attribute or tag names using {} to remove namespaces. returns a pair of: the tag of `x` and the honeybadgerfish representation of the subelemen...
Indirect recursion through _gen_hbf_el
def _hbf_handle_child_elements(self, obj, ntl): """ Indirect recursion through _gen_hbf_el """ # accumulate a list of the children names in ko, and # the a dictionary of tag to xml elements. # repetition of a tag means that it will map to a list of # xml eleme...
Checks if the minidom_meta_element can be represented as a key/value pair in a object. Returns (key, value) ready for JSON serialization, OR `None, None` if the element can not be treated as simple pair. If `None` is returned, then more literal translation of the ...
def _transform_meta_key_value(self, minidom_meta_element): """Checks if the minidom_meta_element can be represented as a key/value pair in a object. Returns (key, value) ready for JSON serialization, OR `None, None` if the element can not be treated as simple pair. I...
Returns an ``etree.ETCompatXMLParser`` instance.
def get_xml_parser(encoding=None): """Returns an ``etree.ETCompatXMLParser`` instance.""" parser = etree.ETCompatXMLParser( huge_tree=True, remove_comments=True, strip_cdata=False, remove_blank_text=True, resolve_entities=False, encoding=encoding ) return...
Returns an instance of lxml.etree._Element for the given `doc` input. Args: doc: The input XML document. Can be an instance of ``lxml.etree._Element``, ``lxml.etree._ElementTree``, a file-like object, or a string filename. encoding: The character encoding of `doc`. If ``None...
def get_etree_root(doc, encoding=None): """Returns an instance of lxml.etree._Element for the given `doc` input. Args: doc: The input XML document. Can be an instance of ``lxml.etree._Element``, ``lxml.etree._ElementTree``, a file-like object, or a string filename. encod...
Parses the xsi:schemaLocation attribute on `node`. Returns: A list of (ns, schemaLocation) tuples for the node. Raises: KeyError: If `node` does not have an xsi:schemaLocation attribute.
def get_schemaloc_pairs(node): """Parses the xsi:schemaLocation attribute on `node`. Returns: A list of (ns, schemaLocation) tuples for the node. Raises: KeyError: If `node` does not have an xsi:schemaLocation attribute. """ schemalocs = node.attrib[TAG_SCHEMALOCATION] l = sch...
Removes all CDATA blocks from `text` if it contains them. Note: If the function contains escaped XML characters outside of a CDATA block, they will be unescaped. Args: A string containing one or more CDATA blocks. Returns: An XML unescaped string with CDATA block qualifier...
def strip_cdata(text): """Removes all CDATA blocks from `text` if it contains them. Note: If the function contains escaped XML characters outside of a CDATA block, they will be unescaped. Args: A string containing one or more CDATA blocks. Returns: An XML unescaped str...
Wraps the input `text` in a ``<![CDATA[ ]]>`` block. If the text contains CDATA sections already, they are stripped and replaced by the application of an outer-most CDATA block. Args: text: A string to wrap in a CDATA block. Returns: The `text` value wrapped in ``<![CDATA[]]>``
def cdata(text): """Wraps the input `text` in a ``<![CDATA[ ]]>`` block. If the text contains CDATA sections already, they are stripped and replaced by the application of an outer-most CDATA block. Args: text: A string to wrap in a CDATA block. Returns: The `text` value wrapped in...
Return True if the input value is valid for insertion into the inner list. Args: value: An object about to be inserted.
def _is_valid(self, value): """Return True if the input value is valid for insertion into the inner list. Args: value: An object about to be inserted. """ # Entities have an istypeof method that can perform more sophisticated # type checking. if hasa...
Attempt to coerce value into the correct type. Subclasses can override this function.
def _fix_value(self, value): """Attempt to coerce value into the correct type. Subclasses can override this function. """ try: return self._castfunc(value) except: error = "Can't put '{0}' ({1}) into a {2}. Expected a {3} object." error = erro...
valueType: idref | nonRefValueType
def visitValueType(self, ctx: jsgParser.ValueTypeContext): """ valueType: idref | nonRefValueType """ if ctx.idref(): self._typeid = as_token(ctx) else: self.visitChildren(ctx)
nonRefValueType: LEXER_ID_REF | STRING | builtinValueType | objectExpr | arrayExpr | OPREN typeAlternatives CPREN | ANY
def visitNonRefValueType(self, ctx: jsgParser.NonRefValueTypeContext): """ nonRefValueType: LEXER_ID_REF | STRING | builtinValueType | objectExpr | arrayExpr | OPREN typeAlternatives CPREN | ANY """ if ctx.LEXER_ID_REF(): # Reference to a lexer token ...
Relay literal text entry from user to Roku until <Enter> or <Esc> pressed.
def text_entry(self): """ Relay literal text entry from user to Roku until <Enter> or <Esc> pressed. """ allowed_sequences = set(['KEY_ENTER', 'KEY_ESCAPE', 'KEY_DELETE']) sys.stdout.write('Enter text (<Esc> to abort) : ') sys.stdout.flush() # Track start column to ens...
Return (tree_id, tree) or None (if the tree has no edges).
def convert_tree(self, tree): """Return (tree_id, tree) or None (if the tree has no edges). """ nodeById = {} root_node = None node_list = _index_list_of_values(tree, 'node') for node in node_list: nodeById[node['@id']] = node r = node.get('@root')...
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...
Generate a list quoted raw name, signature type entries for this pairdef, recursively traversing reference types :param all_are_optional: If true, all types are forced optional :return: raw name/ signature type for all elements in this pair
def members_entries(self, all_are_optional: Optional[bool] = False) -> List[Tuple[str, str]]: """ Generate a list quoted raw name, signature type entries for this pairdef, recursively traversing reference types :param all_are_optional: If true, all types are forced optional :return: raw...
Return the __init__ signature element(s) (var: type = default value). Note that signatures are not generated for non-python names, although we do take the liberty of suffixing a '_' for reserved words (e.g. class: @int generates "class_: int = None" :param all_are_optional: If True, all items...
def signatures(self, all_are_optional: Optional[bool] = False) -> List[str]: """ Return the __init__ signature element(s) (var: type = default value). Note that signatures are not generated for non-python names, although we do take the liberty of suffixing a '_' for reserved words (e.g. class: ...
Create an initializer entry for the entry :param raw_name: name unadjusted for python compatibility. :param cooked_name: name that may or may not be python compatible :param prefix: owner of the element - used when objects passed as arguments :return: Initialization statements
def _initializer_for(self, raw_name: str, cooked_name: str, prefix: Optional[str]) -> List[str]: """Create an initializer entry for the entry :param raw_name: name unadjusted for python compatibility. :param cooked_name: name that may or may not be python compatible :param prefix: owne...
Return the __init__ initializer assignment block
def initializers(self, prefix: Optional[str] = None) -> List[str]: """ Return the __init__ initializer assignment block """ if self._type_reference: # This assumes that references are to things that have initializers # TODO: Remove this check once we are certian things are good ...
pairDef: name COLON valueType ebnfSuffix? | idref ebnfSuffix? | OPREN name (BAR? name)+ CPREN COLON valueType ebnfSuffix?
def visitPairDef(self, ctx: jsgParser.PairDefContext): """ pairDef: name COLON valueType ebnfSuffix? | idref ebnfSuffix? | OPREN name (BAR? name)+ CPREN COLON valueType ebnfSuffix? """ if ctx.name(): # Options 1 or 3 self.visitChild...
name: ID | STRING
def visitName(self, ctx: jsgParser.NameContext): """ name: ID | STRING """ rtkn = get_terminal(ctx) tkn = esc_kw(rtkn) self._names[rtkn] = tkn
Raise AbsentLinkSecret if link secret is not set. :param action: action requiring link secret
def _assert_link_secret(self, action: str): """ Raise AbsentLinkSecret if link secret is not set. :param action: action requiring link secret """ if self._link_secret is None: LOGGER.debug('HolderProver._assert_link_secret: action %s requires link secret but it is n...
Set configuration dict :param value: configuration dict
def cfg(self, value: dict) -> None: """ Set configuration dict :param value: configuration dict """ self._cfg = value or {} validate_config('holder-prover', self._cfg)
Pick up tails file reader handle for input revocation registry identifier. If no symbolic link is present, get the revocation registry definition to retrieve its tails file hash, then find the tails file and link it. Raise AbsentTails for missing corresponding tails file. :param rr_id...
async def _sync_revoc(self, rr_id: str) -> None: """ Pick up tails file reader handle for input revocation registry identifier. If no symbolic link is present, get the revocation registry definition to retrieve its tails file hash, then find the tails file and link it. Raise Ab...
Build rev reg delta json, potentially starting from existing (earlier) delta. Return delta json and its timestamp on the distributed ledger. Raise AbsentRevReg for no such revocation registry, or BadRevStateTime for a requested delta to a time preceding revocation registry creation. :...
async def _build_rr_delta_json(self, rr_id: str, to: int, fro: int = None, fro_delta: dict = None) -> (str, int): """ Build rev reg delta json, potentially starting from existing (earlier) delta. Return delta json and its timestamp on the distributed ledger. Raise AbsentRevReg for no s...
Build and return indy-sdk proof request for input attributes and timestamps by cred def id. Raise AbsentInterval if caller specifies cache_only and default non-revocation intervals, but revocation cache does not have delta frames for any revocation registries on a specified cred def. :param cd...
async def build_proof_req_json(self, cd_id2spec: dict, cache_only: bool = False) -> str: """ Build and return indy-sdk proof request for input attributes and timestamps by cred def id. Raise AbsentInterval if caller specifies cache_only and default non-revocation intervals, but revocati...
Build and return indy-sdk requested credentials json from input indy-sdk creds structure through specified filter. :param creds: indy-sdk creds structure :param filt: filter mapping cred def ids to: - (optionally) 'attr-match': dict mapping attributes to values (omit, empty dict, o...
async def build_req_creds_json(self, creds: dict, filt: dict = None, filt_dflt_incl: bool = False) -> str: """ Build and return indy-sdk requested credentials json from input indy-sdk creds structure through specified filter. :param creds: indy-sdk creds structure :param filt: f...
Return path to the correct directory for the tails file on input revocation registry identifier. :param rr_id: revocation registry identifier of interest :return: path to tails dir for input revocation registry identifier
def dir_tails(self, rr_id: str) -> str: """ Return path to the correct directory for the tails file on input revocation registry identifier. :param rr_id: revocation registry identifier of interest :return: path to tails dir for input revocation registry identifier """ ...
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('HolderProver.ope...
Explicit exit. If so configured, populate cache to prove all creds in wallet offline if need be, archive cache, and purge prior cache archives. :return: current object
async def close(self) -> None: """ Explicit exit. If so configured, populate cache to prove all creds in wallet offline if need be, archive cache, and purge prior cache archives. :return: current object """ LOGGER.debug('HolderProver.close >>>') if self.cfg.get...
Return list of revocation registry identifiers for which HolderProver has tails files. :return: list of revocation registry identifiers for which HolderProver has tails files
def rev_regs(self) -> list: """ Return list of revocation registry identifiers for which HolderProver has tails files. :return: list of revocation registry identifiers for which HolderProver has tails files """ LOGGER.debug('HolderProver.rev_regs >>>') rv = [basename(f...
Create link secret (a.k.a. master secret) used in proofs by HolderProver. Raise any IndyError causing failure to set link secret in wallet. :param link_secret: label for link secret; indy-sdk uses label to generate link secret
async def create_link_secret(self, link_secret: str) -> None: """ Create link secret (a.k.a. master secret) used in proofs by HolderProver. Raise any IndyError causing failure to set link secret in wallet. :param link_secret: label for link secret; indy-sdk uses label to generate link ...