INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Normalize treebase - specific metadata into the locations where open tree of life software that expects it. | 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 | 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 | 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 | 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. | 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. | 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. | 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. | 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 a credential definition as Issuer store it in its wallet and send it to the ledger. | async def send_cred_def(self, s_id: str, revocation: bool = True, rr_size: int = None) -> str:
"""
Create a credential definition as Issuer, store it in its wallet, and send it to the ledger.
Raise CorruptWallet for wallet not pertaining to current ledger, BadLedgerTxn on failure
to sen... |
Create credential offer as Issuer for given schema. | 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. | 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. | 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. | 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. | 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. | 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. | 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 a default. The given namespace must al... | 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: ... |
Adds a new namespace to this set optionally with a prefix and schema location URI. | 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... |
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 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. | 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. | 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. | 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. | 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 situation if no prefixes are registered an ex... | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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 tree_id = tree3 ) see: | 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 | 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. | 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... |
Attempts to parse value into an instance of datetime. date. If value is None this function will return None. | def parse_date(value):
"""Attempts to parse `value` into an instance of ``datetime.date``. If
`value` is ``None``, this function will return ``None``.
Args:
value: A timestamp. This can be a string, datetime.date, or
datetime.datetime value.
"""
if not value:
return Non... |
Attempts to convert value into an xs: date string. If value is None None will be returned. | def serialize_date(value):
"""Attempts to convert `value` into an ``xs:date`` string. If `value` is
``None``, ``None`` will be returned.
Args:
value: A date value. This can be a string, datetime.date, or
datetime.datetime object.
Returns:
An ``xs:date`` formatted timestamp ... |
Finds all valid one and two letter corrections for word_string returning the word with the highest relative probability as type str. | def correct_word(word_string):
'''
Finds all valid one and two letter corrections for word_string, returning the word
with the highest relative probability as type str.
'''
if word_string is None:
return ""
elif isinstance(word_string, str):
return max(find_candidates(word_string... |
Finds all potential words word_string could have intended to mean. If a word is not incorrectly spelled it will return this word first else if will look for one letter edits that are correct. If there are no valid one letter edits it will perform a two letter edit search. | def find_candidates(word_string):
'''
Finds all potential words word_string could have intended to mean. If a word is not incorrectly
spelled, it will return this word first, else if will look for one letter edits that are correct.
If there are no valid one letter edits, it will perform a two letter edi... |
Finds all possible one letter edits of word_string: - Splitting word_string into two words at all character locations - Deleting one letter at all character locations - Switching neighbouring characters - Replacing a character with every alphabetical letter - Inserting all possible alphabetical characters between each ... | def find_one_letter_edits(word_string):
'''
Finds all possible one letter edits of word_string:
- Splitting word_string into two words at all character locations
- Deleting one letter at all character locations
- Switching neighbouring characters
- Replacing a character with every alphabetical l... |
Finds all possible two letter edits of word_string: - Splitting word_string into two words at all character locations - Deleting one letter at all character locations - Switching neighbouring characters - Replacing a character with every alphabetical letter - Inserting all possible alphabetical characters between each ... | def find_two_letter_edits(word_string):
'''
Finds all possible two letter edits of word_string:
- Splitting word_string into two words at all character locations
- Deleting one letter at all character locations
- Switching neighbouring characters
- Replacing a character with every alphabetical l... |
Finds the relative probability of the word appearing given context of a base corpus. Returns this probability value as a float instance. | def find_word_prob(word_string, word_total=sum(WORD_DISTRIBUTION.values())):
'''
Finds the relative probability of the word appearing given context of a base corpus.
Returns this probability value as a float instance.
'''
if word_string is None:
return 0
elif isinstance(word_string, str)... |
Checks for each edited word in word_list if that word is a valid english word. abs Returns all validated words as a set instance. | def validate_words(word_list):
'''
Checks for each edited word in word_list if that word is a valid english word.abs
Returns all validated words as a set instance.
'''
if word_list is None:
return {}
elif isinstance(word_list, list):
if not word_list:
return {}
... |
It is also possible to query the stars by label here is an example of querying for the star labeled as Sun. | def search_star(star):
'''
It is also possible to query the stars by label, here is an example of querying for the star labeled as Sun.
http://star-api.herokuapp.com/api/v1/stars/Sun
'''
base_url = "http://star-api.herokuapp.com/api/v1/stars/"
if not isinstance(star, str):
raise Value... |
It is also possible to query the exoplanets by label here is an example of querying for the exoplanet labeled as 11 Com | def search_exoplanet(exoplanet):
'''
It is also possible to query the exoplanets by label, here is an example of querying for the exoplanet labeled as 11 Com
http://star-api.herokuapp.com/api/v1/exo_planets/11 Com
'''
base_url = "http://star-api.herokuapp.com/api/v1/exo_planets/"
if not isins... |
It is also possible to query the local galaxies by label here is an example of querying for the local galaxy labeled IC 10 | def search_local_galaxies(galaxy):
'''
It is also possible to query the local galaxies by label, here is an example of querying for the local galaxy labeled IC 10
http://star-api.herokuapp.com/api/v1/local_groups/IC 10
'''
base_url = "http://star-api.herokuapp.com/api/v1/local_groups/"
if no... |
It is also possible to query the star clusters by label here is an example of querying for the star cluster labeled Berkeley 59 | def search_star_cluster(cluster):
'''
It is also possible to query the star clusters by label, here is an example of querying for the star cluster labeled Berkeley 59
http://star-api.herokuapp.com/api/v1/open_cluster/Berkeley 59
'''
base_url = "http://star-api.herokuapp.com/api/v1/open_cluster/"
... |
Syntactic sugar around to make it easier to get fine - grained access to the parts of a file without composing a PhyloSchema object. Possible invocations include: w. get ( pg_10 ) w. get ( pg_10 trees ) w. get ( pg_10 trees format = nexus ) w. get ( pg_10 tree_id = tree3 ) see: | def get(self, amendment_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.ge... |
Return the python representation | def as_python(self, name: str) -> str:
""" Return the python representation """
if self._ruleTokens:
pattern = "jsg.JSGPattern(r'{}'.format({}))".\
format(self._rulePattern, ', '.join(['{v}={v}.pattern'.format(v=v) for v in sorted(self._ruleTokens)]))
else:
... |
lexerAltList: lexerAlt ( LBAR lexerAlt ) * | def visitLexerAltList(self, ctx: jsgParser.LexerAltListContext):
""" lexerAltList: lexerAlt (LBAR lexerAlt)* """
altlist = ctx.lexerAlt()
self.visit(altlist[0])
for alt in altlist[1:]:
self._rulePattern += '|'
self.visit(alt) |
lexerElement: lexerAtom ebnfSuffix? | lexerBlock ebnfSuffix? | def visitLexerElement(self, ctx: jsgParser.LexerElementContext):
""" lexerElement: lexerAtom ebnfSuffix? | lexerBlock ebnfSuffix? """
self.visitChildren(ctx)
if ctx.ebnfSuffix():
self._rulePattern += ctx.ebnfSuffix().getText() |
lexerBlock: OPREN lexeraltList CPREN | def visitLexerBlock(self, ctx: jsgParser.LexerBlockContext):
""" lexerBlock: OPREN lexeraltList CPREN """
self._rulePattern += '('
self.visitChildren(ctx)
self._rulePattern += ')' |
lexerAtom: lexerTerminal | LEXER_CHAR_SET | ANY | def visitLexerAtom(self, ctx: jsgParser.LexerAtomContext):
""" lexerAtom : lexerTerminal | LEXER_CHAR_SET | ANY """
if ctx.LEXER_CHAR_SET() or ctx.ANY():
self._rulePattern += str(ctx.getText())
else:
self.visitChildren(ctx) |
terminal: LEXER_ID | STRING | def visitLexerTerminal(self, ctx: jsgParser.LexerTerminalContext):
""" terminal: LEXER_ID | STRING """
if ctx.LEXER_ID():
# Substitute LEXER_ID with its string equivalent - "{LEXER_ID}".format(LEXER_ID=LEXER_ID.pattern)
idtoken = as_token(ctx)
self._rulePattern += '(... |
Convert any string to a slug a simplified form suitable for filename and URL part. EXAMPLE: Trees about bees = > trees - about - bees EXAMPLE: My favorites! = > my - favorites N. B. that its behavior should match this client - side slugify function so we can accurately preview slugs in the browser: https:// github. com... | def slugify(s):
"""Convert any string to a "slug", a simplified form suitable for filename and URL part.
EXAMPLE: "Trees about bees" => 'trees-about-bees'
EXAMPLE: "My favorites!" => 'my-favorites'
N.B. that its behavior should match this client-side slugify function, so
we can accurately "preview... |
Generate next slug for a series. | def increment_slug(s):
"""Generate next slug for a series.
Some docstore types will use slugs (see above) as document ids. To
support unique ids, we'll serialize them as follows:
TestUserA/my-test
TestUserA/my-test-2
TestUserA/my-test-3
...
"""
slug_parts =... |
converts ott_id to ottId. | def underscored2camel_case(v):
"""converts ott_id to ottId."""
vlist = v.split('_')
c = []
for n, el in enumerate(vlist):
if el:
if n == 0:
c.append(el)
else:
c.extend([el[0].upper(), el[1:]])
return ''.join(c) |
Return true if the pair name should be ignored | def unvalidated_parm(self, parm: str) -> bool:
"""Return true if the pair name should be ignored
:param parm: string part of pair string:value
:return: True if it should be accepted
"""
return parm.startswith("_") or parm == self.TYPE or parm in self.IGNORE or \
(sel... |
Takes a request and dispatches its data to a jsonrpc method. | def dispatch(self, request):
"""Takes a request and dispatches its data to a jsonrpc method.
:param request: a werkzeug request with json data
:type request: werkzeug.wrappers.Request
:return: json output of the corresponding method
:rtype: str
.. versionadded:: 0.1.0
... |
Registers a method with a given name and signature. | def register(self, name, method, method_signature=None):
"""Registers a method with a given name and signature.
:param name: The name used to register the method
:type name: str
:param method: The method to register
:type method: function
:param method_signature: The met... |
Syntactic sugar for registering a method | def method(self, returns, **parameter_types):
"""Syntactic sugar for registering a method
Example:
>>> registry = Registry()
>>> @registry.method(returns=int, x=int, y=int)
... def add(x, y):
... return x + y
:param returns: The method's ret... |
Creates a dictionary mapping parameters names to their values in the method call. | def _collect_parameters(parameter_names, args, kwargs, defaults):
"""Creates a dictionary mapping parameters names to their values in the method call.
:param parameter_names: The method's parameter names
:type parameter_names: list[string]
:param args: *args passed into the method
... |
Parses the request as a json message. | def _get_request_messages(self, request):
"""Parses the request as a json message.
:param request: a werkzeug request with json data
:type request: werkzeug.wrappers.Request
:return: The parsed json object
:rtype: dict[str, object]
"""
data = request.get_data(as_... |
Checks that the request json is well - formed. | def _check_request(self, msg):
"""Checks that the request json is well-formed.
:param msg: The request's json data
:type msg: dict[str, object]
"""
if "jsonrpc" not in msg:
raise InvalidRequestError("'\"jsonrpc\": \"2.0\"' must be included.")
if msg["jsonrpc"... |
This returns a collection of JSON objects for every weather report available for October 2012: | def maas_archive(begin, end):
'''
This returns a collection of JSON objects for every weather report available for October 2012:
{
"count": 29,
"next": "http://marsweather.ingenology.com/v1/archive/?terrestrial_date_end=2012-10-31&terrestrial_date_start=2012-10-01&page=2",
"previous": null,
... |
Render a template from the template folder with the given context. | def render_template_to_string(input, _from_string=False, **context):
"""Render a template from the template folder with the given context.
Code based on
`<https://github.com/mitsuhiko/flask/blob/master/flask/templating.py>`_
:param input: the string template, or name of the template to be
... |
Validate if communities logo is in limit size and save it. | def save_and_validate_logo(logo_stream, logo_filename, community_id):
"""Validate if communities logo is in limit size and save it."""
cfg = current_app.config
logos_bucket_id = cfg['COMMUNITIES_BUCKET_UUID']
logo_max_size = cfg['COMMUNITIES_LOGO_MAX_SIZE']
logos_bucket = Bucket.query.get(logos_buc... |
Initialize the communities file bucket. | def initialize_communities_bucket():
"""Initialize the communities file bucket.
:raises: `invenio_files_rest.errors.FilesException`
"""
bucket_id = UUID(current_app.config['COMMUNITIES_BUCKET_UUID'])
if Bucket.query.get(bucket_id):
raise FilesException("Bucket with UUID {} already exists."... |
Format the email message element for inclusion request notification. | def format_request_email_templ(increq, template, **ctx):
"""Format the email message element for inclusion request notification.
Formats the message according to the provided template file, using
some default fields from 'increq' object as default context.
Arbitrary context can be provided as keywords ... |
Format the email message title for inclusion request notification. | def format_request_email_title(increq, **ctx):
"""Format the email message title for inclusion request notification.
:param increq: Inclusion request object for which the request is made.
:type increq: `invenio_communities.models.InclusionRequest`
:param ctx: Optional extra context parameters passed to... |
Format the email message body for inclusion request notification. | def format_request_email_body(increq, **ctx):
"""Format the email message body for inclusion request notification.
:param increq: Inclusion request object for which the request is made.
:type increq: `invenio_communities.models.InclusionRequest`
:param ctx: Optional extra context parameters passed to f... |
Signal for sending emails after community inclusion request. | def send_community_request_email(increq):
"""Signal for sending emails after community inclusion request."""
from flask_mail import Message
from invenio_mail.tasks import send_email
msg_body = format_request_email_body(increq)
msg_title = format_request_email_title(increq)
sender = current_app... |
Convenience function for writing documentation. | def modifydocs(a, b, desc=''):
"""
Convenience function for writing documentation.
For a class method `a` that is essentially a wrapper for an outside
function `b`, rope in the docstring from `b` and append to that of `a`.
Also modify the docstring of `a` to get the indentation right.
W... |
Horizontal stacking of tabarrays e. g. adding columns. | def tab_colstack(ListOfTabArrays, mode='abort'):
"""
"Horizontal stacking" of tabarrays, e.g. adding columns.
Wrapper for :func:`tabular.spreadsheet.colstack` that deals with the
coloring and returns the result as a tabarray.
Method calls::
data = tabular.spreadsheet.colstack(ListOfTabAr... |
Vertical stacking of tabarrays e. g. adding rows. | def tab_rowstack(ListOfTabArrays, mode='nulls'):
"""
"Vertical stacking" of tabarrays, e.g. adding rows.
Wrapper for :func:`tabular.spreadsheet.rowstack` that deals with the
coloring and returns the result as a tabarray.
Method calls::
data = tabular.spreadsheet.rowstack(ListOfTabArrays,... |
Database - join for tabular arrays. | def tab_join(ToMerge, keycols=None, nullvals=None, renamer=None,
returnrenaming=False, Names=None):
'''
Database-join for tabular arrays.
Wrapper for :func:`tabular.spreadsheet.join` that deals with the coloring
and returns the result as a tabarray.
Method calls::
data ... |
Creates a copy of this tabarray in the form of a numpy ndarray. | def extract(self):
"""
Creates a copy of this tabarray in the form of a numpy ndarray.
Useful if you want to do math on array elements, e.g. if you have a
subset of the columns that are all numerical, you can construct a
numerical matrix and do matrix operations.
"""
... |
Append one or more records to the end of the array. | def addrecords(self, new):
"""
Append one or more records to the end of the array.
Method wraps::
tabular.spreadsheet.addrecords(self, new)
"""
data = spreadsheet.addrecords(self,new)
data = data.view(tabarray)
data.coloring = self.coloring
... |
Add one or more new columns. | def addcols(self, cols, names=None):
"""
Add one or more new columns.
Method wraps::
tabular.spreadsheet.addcols(self, cols, names)
"""
data = spreadsheet.addcols(self, cols, names)
data = data.view(tabarray)
data.coloring = self.coloring
... |
Delete columns and/ or colors. | def deletecols(self, cols):
"""
Delete columns and/or colors.
Method wraps::
tabular.spreadsheet.deletecols(self, cols)
"""
if isinstance(cols, str):
cols = cols.split(',')
deletenames = utils.uniqify(utils.listunion([[c] if c in
self.... |
Rename column or color in - place. | def renamecol(self, old, new):
"""
Rename column or color in-place.
Method wraps::
tabular.spreadsheet.renamecol(self, old, new)
"""
spreadsheet.renamecol(self,old,new)
for x in self.coloring.keys():
if old in self.coloring[x]:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.