INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
An attribute with type None is equivalent to an absent attribute.
:param d: Object with attributes
:return: Object dictionary w/ Nones and underscores removed | def _strip_nones(d: Dict[str, Any])-> Dict[str, Any]:
"""
An attribute with type None is equivalent to an absent attribute.
:param d: Object with attributes
:return: Object dictionary w/ Nones and underscores removed
"""
return OrderedDict({k: None if isinstance(v, JSGNul... |
Return a serializable version of obj. Overrides JsonObj _default method
:param obj: Object to be serialized
:return: Serialized version of obj | def _default(self, obj: object):
""" Return a serializable version of obj. Overrides JsonObj _default method
:param obj: Object to be serialized
:return: Serialized version of obj
"""
return None if obj is JSGNull else obj.val if type(obj) is AnyType else \
JSGObject.... |
Returns a GitHub URL for the doc in question (study, collection, ...) | def get_public_url(self, doc_id, branch='master'):
"""Returns a GitHub URL for the doc in question (study, collection, ...)
"""
name, path_frag = self.get_repo_and_path_fragment(doc_id)
return 'https://raw.githubusercontent.com/OpenTreeOfLife/' + name + '/' + branch + '/' + path_frag |
For `doc_id` returns a list of:
[0] the repo name and,
[1] the path from the repo to the doc file.
This is useful because
(if you know the remote), it lets you construct the full path. | def get_repo_and_path_fragment(self, doc_id):
"""For `doc_id` returns a list of:
[0] the repo name and,
[1] the path from the repo to the doc file.
This is useful because
(if you know the remote), it lets you construct the full path.
"""
shard = self.get_s... |
Validates that the given parameters are exactly the method's declared parameters.
:param method: The method to be called
:type method: function
:param parameters: The parameters to use in the call
:type parameters: dict[str, object] | list[object] | def validate_params_match(method, parameters):
"""Validates that the given parameters are exactly the method's declared parameters.
:param method: The method to be called
:type method: function
:param parameters: The parameters to use in the call
:type parameters: dict[str, object] | list[object]
... |
Checks that the given parameters have the correct types.
:param parameters: List of (name, value) pairs of the given parameters
:type parameters: dict[str, object]
:param parameter_types: Parameter type by name.
:type parameter_types: dict[str, type]
:param strict_floats: If False, treat integers a... | def check_types(parameters, parameter_types, strict_floats):
"""Checks that the given parameters have the correct types.
:param parameters: List of (name, value) pairs of the given parameters
:type parameters: dict[str, object]
:param parameter_types: Parameter type by name.
:type parameter_types: ... |
Checks that exactly the given parameter names have declared types.
:param parameter_names: The names of the parameters in the method declaration
:type parameter_names: list[str]
:param parameter_types: Parameter type by name
:type parameter_types: dict[str, type] | def check_type_declaration(parameter_names, parameter_types):
"""Checks that exactly the given parameter names have declared types.
:param parameter_names: The names of the parameters in the method declaration
:type parameter_names: list[str]
:param parameter_types: Parameter type by name
:type par... |
Checks that the given return value has the correct type.
:param value: Value returned by the method
:type value: object
:param expected_type: Expected return type
:type expected_type: type
:param strict_floats: If False, treat integers as floats
:type strict_floats: bool | def check_return_type(value, expected_type, strict_floats):
"""Checks that the given return value has the correct type.
:param value: Value returned by the method
:type value: object
:param expected_type: Expected return type
:type expected_type: type
:param strict_floats: If False, treat integ... |
Returns a dictionary of name -> filepath
`name` is the repo name based on the dir name (not the get repo). It is not
terribly useful, but it is nice to have so that any mirrored repo directory can
use the same naming convention.
`filepath` will be the full path to the repo directory (it will end... | def get_repos(par_list=None, **kwargs):
"""Returns a dictionary of name -> filepath
`name` is the repo name based on the dir name (not the get repo). It is not
terribly useful, but it is nice to have so that any mirrored repo directory can
use the same naming convention.
`filepath` will be t... |
Searchers for *.json files in this repo and returns
a map of study id ==> (`tag`, dir, study filepath)
where `tag` is typically the shard name | def create_id2study_info(path, tag):
"""Searchers for *.json files in this repo and returns
a map of study id ==> (`tag`, dir, study filepath)
where `tag` is typically the shard name
"""
d = {}
for triple in os.walk(path):
root, files = triple[0], triple[2]
for filename in files:... |
Only intended to be called by the Phylesystem singleton. | def _make_phylesystem_cache_region(**kwargs):
"""Only intended to be called by the Phylesystem singleton.
"""
global _CACHE_REGION_CONFIGURED, _REGION
if _CACHE_REGION_CONFIGURED:
return _REGION
_CACHE_REGION_CONFIGURED = True
try:
# noinspection PyPackageRequirements
fro... |
This function sets up a command-line option parser and then calls match_and_print
to do all of the real work. | def main(argv):
"""This function sets up a command-line option parser and then calls match_and_print
to do all of the real work.
"""
import argparse
description = 'Uses Open Tree of Life web services to find information for each OTT ID.'
parser = argparse.ArgumentParser(prog='ot-taxon-info', des... |
Takes an `obj` that is a NexSON object.
`warning_codes_to_skip` is None or an iterable collection of integers
that correspond to facets of NexsonWarningCodes. Warnings associated
with any code in the list will be suppressed.
`retain_deprecated` if False, then `obj` may be modified to replace
... | def validate_nexson(obj, warning_codes_to_skip=None, retain_deprecated=True, **kwargs):
"""Takes an `obj` that is a NexSON object.
`warning_codes_to_skip` is None or an iterable collection of integers
that correspond to facets of NexsonWarningCodes. Warnings associated
with any code in the list ... |
Returns three objects:
an annotation dict (NexSON formmatted),
the validation_log object created when NexSON validation was performed, and
the object of class NexSON which was created from nexson. This object may
alias parts of the nexson dict that is passed in as an argument.
C... | def ot_validate(nexson, **kwargs):
"""Returns three objects:
an annotation dict (NexSON formmatted),
the validation_log object created when NexSON validation was performed, and
the object of class NexSON which was created from nexson. This object may
alias parts of the nexson dic... |
In order to use this capability, queries can be issued to the system with the following URI
format:
GET /xml-api/id_parameter
Parameter Required? Value Description
id_parameter Yes Type: String
Default: None
The id value of the TechPort record.
TechPort values range from 0-20000.
Not all... | def techport(Id):
'''
In order to use this capability, queries can be issued to the system with the following URI
format:
GET /xml-api/id_parameter
Parameter Required? Value Description
id_parameter Yes Type: String
Default: None
The id value of the TechPort record.
TechPort values r... |
Not locked! | def get_HEAD_SHA1(git_dir):
"""Not locked!
"""
head_file = os.path.join(git_dir, 'HEAD')
with open(head_file, 'r') as hf:
head_contents = hf.read().strip()
assert head_contents.startswith('ref: ')
ref_filename = head_contents[5:] # strip off "ref: "
real_ref = os.path.join(git_dir, ... |
Returns doc_dir and doc_filepath for doc_id. | def path_for_doc(self, doc_id):
"""Returns doc_dir and doc_filepath for doc_id.
"""
full_path = self.path_for_doc_fn(self.repo, doc_id)
# _LOG.debug('>>>>>>>>>> GitActionBase.path_for_doc_fn: {}'.format(self.path_for_doc_fn))
# _LOG.debug('>>>>>>>>>> GitActionBase.path_for_doc re... |
Return the current branch name | def current_branch(self):
"""Return the current branch name"""
branch_name = git(self.gitdir, self.gitwd, "symbolic-ref", "HEAD")
return branch_name.replace('refs/heads/', '').strip() |
Returns true or false depending on if a branch exists | def branch_exists(self, branch):
"""Returns true or false depending on if a branch exists"""
try:
git(self.gitdir, self.gitwd, "rev-parse", branch)
except sh.ErrorReturnCode:
return False
return True |
fetch from a remote | def fetch(self, remote='origin'):
"""fetch from a remote"""
git(self.gitdir, "fetch", remote, _env=self.env()) |
Return a dict representation of this file's commit history
This uses specially formatted git-log output for easy parsing, as described here:
http://blog.lost-theory.org/post/how-to-parse-git-log-output/
For a full list of available fields, see:
http://linux.die.net/man/1/git-log | def get_version_history_for_file(self, filepath):
""" Return a dict representation of this file's commit history
This uses specially formatted git-log output for easy parsing, as described here:
http://blog.lost-theory.org/post/how-to-parse-git-log-output/
For a full list of availab... |
Low level function used internally when you have an absolute filepath to add and commit | def _add_and_commit(self, doc_filepath, author, commit_msg):
"""Low level function used internally when you have an absolute filepath to add and commit"""
try:
git(self.gitdir, self.gitwd, "add", doc_filepath)
git(self.gitdir, self.gitwd, "commit", author=author, message=commit_m... |
Merge the the given WIP branch to master (or destination, if specified)
If the merge fails, the merge will be aborted
and then a MergeException will be thrown. The
message of the MergeException will be the
"git status" output, so details about merge
conflicts can be determined. | def merge(self, branch, destination="master"):
"""
Merge the the given WIP branch to master (or destination, if specified)
If the merge fails, the merge will be aborted
and then a MergeException will be thrown. The
message of the MergeException will be the
"git status" o... |
Return the
blob[0] contents of the given doc_id,
blob[1] the SHA1 of the HEAD of branch (or `commit_sha`)
blob[2] dictionary of WIPs for this doc.
If the doc_id does not exist, it returns the empty string.
If `commit_sha` is provided, that will be checked out and retu... | def return_document(self, doc_id, branch='master', commit_sha=None, return_WIP_map=False):
"""Return the
blob[0] contents of the given doc_id,
blob[1] the SHA1 of the HEAD of branch (or `commit_sha`)
blob[2] dictionary of WIPs for this doc.
If the doc_id does not exis... |
Returns the set of documents that have changed on the master since
commit `ancestral_commit_sha` or `False` (on an error)
'doc_id_from_repo_path' is a required function
if `doc_ids_to_check` is passed in, it should be an iterable list of
IDs. Only IDs in this list will be returned. | def _get_changed_docs(self,
ancestral_commit_sha,
doc_id_from_repo_path,
doc_ids_to_check=None):
"""Returns the set of documents that have changed on the master since
commit `ancestral_commit_sha` or `False` (on an error)
... |
Remove a document
Remove a document on the given branch and attribute the commit to author.
Returns the SHA of the commit on branch. | def _remove_document(self, gh_user, doc_id, parent_sha, author, commit_msg=None):
"""Remove a document
Remove a document on the given branch and attribute the commit to author.
Returns the SHA of the commit on branch.
"""
# _LOG.debug("@@@@@@@@ GitActionBase._remove_document, doc... |
Given a document id, temporary filename of content, branch and auth_info
Deprecated but needed until we merge api local-dep to master... | def write_document(self, gh_user, doc_id, file_content, branch, author, commit_msg=None):
"""Given a document id, temporary filename of content, branch and auth_info
Deprecated but needed until we merge api local-dep to master...
"""
parent_sha = None
fc = tempfile.NamedTempora... |
Given a doc_id, temporary filename of content, branch and auth_info | def write_doc_from_tmpfile(self,
doc_id,
tmpfi,
parent_sha,
auth_info,
commit_msg='',
doctype_display_name="document"):
"""Giv... |
Inefficient comparison of src and dest dicts.
Recurses through dict and lists.
returns None if there is no difference and a
DictDiffObject of there are differences
**kwargs can contain:
wrap_dict_in_list default False. If True and one
value is present as a lis... | def create(src, dest, **kwargs):
"""Inefficient comparison of src and dest dicts.
Recurses through dict and lists.
returns None if there is no difference and a
DictDiffObject of there are differences
**kwargs can contain:
wrap_dict_in_list default False. If True and o... |
Inefficient comparison of src and dest dicts.
Recurses through dict and lists.
returns (is_identical, modifications, additions, deletions)
where each
is_identical is a boolean True if the dicts have
contents that compare equal.
and the other three are dicts:
... | def create(src, dest, **kwargs):
"""Inefficient comparison of src and dest dicts.
Recurses through dict and lists.
returns (is_identical, modifications, additions, deletions)
where each
is_identical is a boolean True if the dicts have
contents that compare equ... |
performs taxonomic name resolution.
See https://github.com/OpenTreeOfLife/opentree/wiki/Open-Tree-of-Life-APIs#match_names
with the exception that "ids" in the API call is referred has the name "id_list" in this function.
The most commonly used kwargs are:
- context_name=<name> (see ... | def match_names(self, *valist, **kwargs):
"""performs taxonomic name resolution.
See https://github.com/OpenTreeOfLife/opentree/wiki/Open-Tree-of-Life-APIs#match_names
with the exception that "ids" in the API call is referred has the name "id_list" in this function.
The most commonly use... |
Remove an amendment
Given a amendment_id, branch and optionally an
author, remove an amendment on the given branch
and attribute the commit to author.
Returns the SHA of the commit on branch. | def remove_amendment(self, first_arg, sec_arg, third_arg, fourth_arg=None, commit_msg=None):
"""Remove an amendment
Given a amendment_id, branch and optionally an
author, remove an amendment on the given branch
and attribute the commit to author.
Returns the SHA of the commit on ... |
Given an amendment_id, temporary filename of content, branch and auth_info
Deprecated but needed until we merge api local-dep to master... | def write_amendment(self, amendment_id, file_content, branch, author):
"""Given an amendment_id, temporary filename of content, branch and auth_info
Deprecated but needed until we merge api local-dep to master...
"""
gh_user = branch.split('_amendment_')[0]
msg = "Update Amendm... |
Given an amendment_id, temporary filename of content, branch and auth_info | def write_amendment_from_tmpfile(self, amendment_id, tmpfi, parent_sha, auth_info, commit_msg=''):
"""Given an amendment_id, temporary filename of content, branch and auth_info
"""
return self.write_doc_from_tmpfile(amendment_id,
tmpfi,
... |
arrayExpr: OBRACKET valueType (BAR valueType)* ebnfSuffix? CBRACKET; | def visitArrayExpr(self, ctx: jsgParser.ArrayExprContext):
""" arrayExpr: OBRACKET valueType (BAR valueType)* ebnfSuffix? CBRACKET; """
from pyjsg.parser_impl.jsg_ebnf_parser import JSGEbnf
from pyjsg.parser_impl.jsg_valuetype_parser import JSGValueType
self._types = [JSGValueType(self.... |
For `doc_id` returns the path from the
repo to the doc file. This is useful because
(if you know the remote), it lets you construct the full path. | def get_rel_path_fragment(self, doc_id):
"""For `doc_id` returns the path from the
repo to the doc file. This is useful because
(if you know the remote), it lets you construct the full path.
"""
with self._index_lock:
r = self._doc_index[doc_id]
fp = r[-1]
... |
Returns a pair: (doc_id, absolute filepath of document file)
for each document in this repository.
Order is arbitrary. | def iter_doc_filepaths(self, **kwargs): # pylint: disable=W0613
"""Returns a pair: (doc_id, absolute filepath of document file)
for each document in this repository.
Order is arbitrary.
"""
with self._index_lock:
for doc_id, info in self._doc_index.items():
... |
Returns a pair: (doc_id, nexson_blob)
for each document in this repository.
Order is arbitrary. | def iter_doc_objs(self, **kwargs):
"""Returns a pair: (doc_id, nexson_blob)
for each document in this repository.
Order is arbitrary.
"""
_LOG = get_logger('TypeAwareGitShard')
try:
for doc_id, fp in self.iter_doc_filepaths(**kwargs):
if not se... |
Generic configuration, may be overridden by type-specific version | def get_configuration_dict(self, secret_attrs=False):
"""Generic configuration, may be overridden by type-specific version"""
rd = {'name': self.name,
'path': self.path,
'git_dir': self.git_dir,
'assumed_doc_version': self.assumed_doc_version,
'doc... |
This will force the current branch to master! | def _read_master_branch_resource(self, fn, is_json=False):
"""This will force the current branch to master! """
with self._master_branch_repo_lock:
ga = self._create_git_action_for_global_resource()
with ga.lock():
ga.checkout_master()
if os.path.e... |
This will force the current branch to master! | def _write_master_branch_resource(self, content, fn, commit_msg, is_json=False):
"""This will force the current branch to master! """
# TODO: we might want this to push, but currently it is only called in contexts in which
# we are about to push anyway (document creation)
with self._mast... |
Create a record inclusion request to a community.
:param community: Community object.
:param record: Record API object.
:param expires_at: Time after which the request expires and shouldn't
be resolved anymore. | def create(cls, community, record, user=None, expires_at=None,
notify=True):
"""Create a record inclusion request to a community.
:param community: Community object.
:param record: Record API object.
:param expires_at: Time after which the request expires and shouldn't
... |
Get an inclusion request. | def get(cls, community_id, record_uuid):
"""Get an inclusion request."""
return cls.query.filter_by(
id_record=record_uuid, id_community=community_id
).one_or_none() |
Get a community. | def create(cls, community_id, user_id, **data):
"""Get a community."""
with db.session.begin_nested():
obj = cls(id=community_id, id_user=user_id, **data)
db.session.add(obj)
return obj |
Get a community. | def save_logo(self, stream, filename):
"""Get a community."""
logo_ext = save_and_validate_logo(stream, filename, self.id)
if logo_ext:
self.logo_ext = logo_ext
return True
return False |
Get a community. | def get(cls, community_id, with_deleted=False):
"""Get a community."""
q = cls.query.filter_by(id=community_id)
if not with_deleted:
q = q.filter(cls.deleted_at.is_(None))
return q.one_or_none() |
Get a community. | def get_by_user(cls, user_id, with_deleted=False):
"""Get a community."""
query = cls.query.filter_by(
id_user=user_id
)
if not with_deleted:
query = query.filter(cls.deleted_at.is_(None))
return query.order_by(db.asc(Community.title)) |
Search for communities.
Helper function which takes from database only those communities which
match search criteria. Uses parameter 'so' to set communities in the
correct order.
Parameter 'page' is introduced to restrict results and return only
slice of them for the current pa... | def filter_communities(cls, p, so, with_deleted=False):
"""Search for communities.
Helper function which takes from database only those communities which
match search criteria. Uses parameter 'so' to set communities in the
correct order.
Parameter 'page' is introduced to restri... |
Add a record to the community.
:param record: Record object.
:type record: `invenio_records.api.Record` | def add_record(self, record):
"""Add a record to the community.
:param record: Record object.
:type record: `invenio_records.api.Record`
"""
key = current_app.config['COMMUNITIES_RECORD_KEY']
record.setdefault(key, [])
if self.has_record(record):
cur... |
Remove an already accepted record from the community.
:param record: Record object.
:type record: `invenio_records.api.Record` | def remove_record(self, record):
"""Remove an already accepted record from the community.
:param record: Record object.
:type record: `invenio_records.api.Record`
"""
if not self.has_record(record):
current_app.logger.warning(
'Community removal: reco... |
Accept a record for inclusion in the community.
:param record: Record object. | def accept_record(self, record):
"""Accept a record for inclusion in the community.
:param record: Record object.
"""
with db.session.begin_nested():
req = InclusionRequest.get(self.id, record.id)
if req is None:
raise InclusionRequestMissingError... |
Reject a record for inclusion in the community.
:param record: Record object. | def reject_record(self, record):
"""Reject a record for inclusion in the community.
:param record: Record object.
"""
with db.session.begin_nested():
req = InclusionRequest.get(self.id, record.id)
if req is None:
raise InclusionRequestMissingError... |
Mark the community for deletion.
:param delete_time: DateTime after which to delete the community.
:type delete_time: datetime.datetime
:raises: CommunitiesError | def delete(self):
"""Mark the community for deletion.
:param delete_time: DateTime after which to delete the community.
:type delete_time: datetime.datetime
:raises: CommunitiesError
"""
if self.deleted_at is not None:
raise CommunitiesError(community=self)
... |
Get URL to collection logo.
:returns: Path to community logo.
:rtype: str | def logo_url(self):
"""Get URL to collection logo.
:returns: Path to community logo.
:rtype: str
"""
if self.logo_ext:
return '/api/files/{bucket}/{key}'.format(
bucket=current_app.config['COMMUNITIES_BUCKET_UUID'],
key='{0}/logo.{1}'.... |
Return the corresponding OAISet for given community.
If OAIServer is not installed this property will return None.
:returns: returns OAISet object corresponding to this community.
:rtype: `invenio_oaiserver.models.OAISet` or None | def oaiset(self):
"""Return the corresponding OAISet for given community.
If OAIServer is not installed this property will return None.
:returns: returns OAISet object corresponding to this community.
:rtype: `invenio_oaiserver.models.OAISet` or None
"""
if current_app.... |
Return the OAISet URL for given community.
:returns: URL of corresponding OAISet.
:rtype: str | def oaiset_url(self):
"""Return the OAISet URL for given community.
:returns: URL of corresponding OAISet.
:rtype: str
"""
return url_for(
'invenio_oaiserver.response',
verb='ListRecords',
metadataPrefix='oai_dc', set=self.oaiset_spec, _extern... |
Return the version of the community.
:returns: hash which encodes the community id and its las update.
:rtype: str | def version_id(self):
"""Return the version of the community.
:returns: hash which encodes the community id and its las update.
:rtype: str
"""
return hashlib.sha1('{0}__{1}'.format(
self.id, self.updated).encode('utf-8')).hexdigest() |
Get the latest featured community.
:param start_date: Date after which the featuring starts
:returns: Community object or None
:rtype: `invenio_communities.models.Community` or None | def get_featured_or_none(cls, start_date=None):
"""Get the latest featured community.
:param start_date: Date after which the featuring starts
:returns: Community object or None
:rtype: `invenio_communities.models.Community` or None
"""
start_date = start_date or datetim... |
GET the current Connector version.
:returns: asyncResult object, populates error and result fields
:rtype: asyncResult | def getConnectorVersion(self):
"""
GET the current Connector version.
:returns: asyncResult object, populates error and result fields
:rtype: asyncResult
"""
result = asyncResult()
data = self._getURL("/",versioned=False)
result.fill(data)
if data.status_code == 200:
result.error = False
else:
... |
Get list of all endpoints on the domain.
:param str typeOfEndpoint: Optional filter endpoints returned by type
:return: list of all endpoints
:rtype: asyncResult | def getEndpoints(self,typeOfEndpoint=""):
"""
Get list of all endpoints on the domain.
:param str typeOfEndpoint: Optional filter endpoints returned by type
:return: list of all endpoints
:rtype: asyncResult
"""
q = {}
result = asyncResult()
if typeOfEndpoint:
q['type'] = typeOfEndpoint
resul... |
Get list of resources on an endpoint.
:param str ep: Endpoint to get the resources of
:param bool noResp: Optional - specify no response necessary from endpoint
:param bool cacheOnly: Optional - get results from cache on connector, do not wake up endpoint
:return: list of resources
:rtype: asyncResult | def getResources(self,ep,noResp=False,cacheOnly=False):
"""
Get list of resources on an endpoint.
:param str ep: Endpoint to get the resources of
:param bool noResp: Optional - specify no response necessary from endpoint
:param bool cacheOnly: Optional - get results from cache on connector, do not wake up ... |
Get value of a specific resource on a specific endpoint.
:param str ep: name of endpoint
:param str res: name of resource
:param fnptr cbfn: Optional - callback function to be called on completion
:param bool noResp: Optional - specify no response necessary from endpoint
:param bool cacheOnly: Optional - g... | def getResourceValue(self,ep,res,cbfn="",noResp=False,cacheOnly=False):
"""
Get value of a specific resource on a specific endpoint.
:param str ep: name of endpoint
:param str res: name of resource
:param fnptr cbfn: Optional - callback function to be called on completion
:param bool noResp: Optional - s... |
Put a value to a resource on an endpoint
:param str ep: name of endpoint
:param str res: name of resource
:param str data: data to send via PUT
:param fnptr cbfn: Optional - callback funtion to call when operation is completed
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rty... | def putResourceValue(self,ep,res,data,cbfn=""):
"""
Put a value to a resource on an endpoint
:param str ep: name of endpoint
:param str res: name of resource
:param str data: data to send via PUT
:param fnptr cbfn: Optional - callback funtion to call when operation is completed
:return: successful ``.s... |
Send DELETE message to an endpoint.
:param str ep: name of endpoint
:param fnptr cbfn: Optional - callback funtion to call when operation is completed
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult | def deleteEndpoint(self,ep,cbfn=""):
'''
Send DELETE message to an endpoint.
:param str ep: name of endpoint
:param fnptr cbfn: Optional - callback funtion to call when operation is completed
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = as... |
Delete all subscriptions on specified endpoint ``ep``
:param str ep: name of endpoint
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult | def deleteEndpointSubscriptions(self,ep):
'''
Delete all subscriptions on specified endpoint ``ep``
:param str ep: name of endpoint
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
result.endpoint = ep
data = self._deleteURL("... |
Delete all subscriptions on the domain (all endpoints, all resources)
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult | def deleteAllSubscriptions(self):
'''
Delete all subscriptions on the domain (all endpoints, all resources)
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
data = self._deleteURL("/subscriptions/")
if data.status_code == 204: #i... |
Get list of all subscriptions on a given endpoint ``ep``
:param str ep: name of endpoint
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult | def getEndpointSubscriptions(self,ep):
'''
Get list of all subscriptions on a given endpoint ``ep``
:param str ep: name of endpoint
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
result.endpoint = ep
data = self._getURL("/sub... |
Get list of all subscriptions for a resource ``res`` on an endpoint ``ep``
:param str ep: name of endpoint
:param str res: name of resource
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult | def getResourceSubscription(self,ep,res):
'''
Get list of all subscriptions for a resource ``res`` on an endpoint ``ep``
:param str ep: name of endpoint
:param str res: name of resource
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncRes... |
Set pre-subscription rules for all endpoints / resources on the domain.
This can be useful for all current and future endpoints/resources.
:param json JSONdata: data to use as pre-subscription data. Wildcards are permitted
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyn... | def putPreSubscription(self,JSONdata):
'''
Set pre-subscription rules for all endpoints / resources on the domain.
This can be useful for all current and future endpoints/resources.
:param json JSONdata: data to use as pre-subscription data. Wildcards are permitted
:return: successful ``.status_code`` / ``... |
Get the current pre-subscription data from connector
:return: JSON that represents the pre-subscription data in the ``.result`` field
:rtype: asyncResult | def getPreSubscription(self):
'''
Get the current pre-subscription data from connector
:return: JSON that represents the pre-subscription data in the ``.result`` field
:rtype: asyncResult
'''
result = asyncResult()
data = self._getURL("/subscriptions")
if data.status_code == 200: #immediate success
... |
Set the callback URL. To be used in place of LongPolling when deploying a webapp.
**note**: make sure you set up a callback URL in your web app
:param str url: complete url, including port, where the callback url is located
:param str headers: Optional - Headers to have Connector send back with all calls
... | def putCallback(self,url,headers=""):
'''
Set the callback URL. To be used in place of LongPolling when deploying a webapp.
**note**: make sure you set up a callback URL in your web app
:param str url: complete url, including port, where the callback url is located
:param str headers: Optional - Headers... |
Register a handler for a particular notification type.
These are the types of notifications that are acceptable.
| 'async-responses'
| 'registrations-expired'
| 'de-registrations'
| 'reg-updates'
| 'registrations'
| 'notifications'
:param str handler: name of the notification type
:param fnptr cb... | def setHandler(self,handler,cbfn):
'''
Register a handler for a particular notification type.
These are the types of notifications that are acceptable.
| 'async-responses'
| 'registrations-expired'
| 'de-registrations'
| 'reg-updates'
| 'registrations'
| 'notifications'
:param str handler: name... |
Start LongPolling Connector for notifications.
:param bool noWait: Optional - use the cached values in connector, do not wait for the device to respond
:return: Thread of constantly running LongPoll. To be used to kill the thred if necessary.
:rtype: pythonThread | def startLongPolling(self, noWait=False):
'''
Start LongPolling Connector for notifications.
:param bool noWait: Optional - use the cached values in connector, do not wait for the device to respond
:return: Thread of constantly running LongPoll. To be used to kill the thred if necessary.
:rtype: pythonThre... |
Stop LongPolling thread
:return: none | def stopLongPolling(self):
'''
Stop LongPolling thread
:return: none
'''
if(self.longPollThread.isAlive()):
self._stopLongPolling.set()
self.log.debug("set stop longpolling flag")
else:
self.log.warn("LongPolling thread already stopped")
return |
Function to handle notification data as part of Callback URL handler.
:param str data: data posted to Callback URL by connector.
:return: nothing | def handler(self,data):
'''
Function to handle notification data as part of Callback URL handler.
:param str data: data posted to Callback URL by connector.
:return: nothing
'''
if isinstance(data,r.models.Response):
self.log.debug("data is request object = %s", str(data.content))
data = data.con... |
Enable / Disable debugging
:param bool onOff: turn debugging on / off
:return: none | def debug(self,onOff,level='DEBUG'):
'''
Enable / Disable debugging
:param bool onOff: turn debugging on / off
:return: none
'''
if onOff:
if level == 'DEBUG':
self.log.setLevel(logging.DEBUG)
self._ch.setLevel(logging.DEBUG)
self.log.debug("Debugging level DEBUG enabled")
elif level =... |
Add the appropriate python typing to subject (e.g. Optional, List, ...)
:param subject: Subject to be decorated
:param all_are_optional: Force everything to be optional
:return: Typed subject | def python_cardinality(self, subject: str, all_are_optional: bool = False) -> str:
"""Add the appropriate python typing to subject (e.g. Optional, List, ...)
:param subject: Subject to be decorated
:param all_are_optional: Force everything to be optional
:return: Typed subject
"... |
Add the appropriate python typing to subject (e.g. Optional, List, ...)
:param subject: Subject to be decorated
:param all_are_optional: Force everything to be optional
:return: Typed subject | def signature_cardinality(self, subject: str, all_are_optional: bool = False) -> str:
"""Add the appropriate python typing to subject (e.g. Optional, List, ...)
:param subject: Subject to be decorated
:param all_are_optional: Force everything to be optional
:return: Typed subject
... |
ebnfSuffix: QMARK | STAR | PLUS | OBRACE INT (COMMA (INT|STAR)?)? CBRACE | def visitEbnfSuffix(self, ctx: jsgParser.EbnfSuffixContext):
""" ebnfSuffix: QMARK | STAR | PLUS | OBRACE INT (COMMA (INT|STAR)?)? CBRACE """
self._ebnftext = ctx.getText()
if ctx.INT():
self.min = int(ctx.INT(0).getText())
if ctx.COMMA():
if len(ctx.INT()... |
Return the python representation of the document | def as_python(self, infile, include_original_shex: bool=False):
""" Return the python representation of the document """
self._context.resolve_circular_references() # add forwards for any circular entries
body = ''
for k in self._context.ordered_elements():
v = sel... |
directive: '.TYPE' name typeExceptions? SEMI | def visitTypeDirective(self, ctx: jsgParser.TypeDirectiveContext):
""" directive: '.TYPE' name typeExceptions? SEMI """
self._context.directives.append('_CONTEXT.TYPE = "{}"'.format(as_token(ctx.name())))
self._context.has_typeid = True
self.visitChildren(ctx) |
typeExceptions: DASH idref+ | def visitTypeExceptions(self, ctx: jsgParser.TypeExceptionsContext):
""" typeExceptions: DASH idref+ """
for tkn in as_tokens(ctx.idref()):
self._context.directives.append('_CONTEXT.TYPE_EXCEPTIONS.append("{}")'.format(tkn)) |
directive: '.IGNORE' name* SEMI | def visitIgnoreDirective(self, ctx: jsgParser.IgnoreDirectiveContext):
""" directive: '.IGNORE' name* SEMI """
for name in as_tokens(ctx.name()):
self._context.directives.append('_CONTEXT.IGNORE.append("{}")'.format(name)) |
objectDef: ID objectExpr | def visitObjectDef(self, ctx: jsgParser.ObjectDefContext):
""" objectDef: ID objectExpr """
name = as_token(ctx)
self._context.grammarelts[name] = JSGObjectExpr(self._context, ctx.objectExpr(), name) |
arrayDef : ID arrayExpr | def visitArrayDef(self, ctx: jsgParser.ArrayDefContext):
""" arrayDef : ID arrayExpr """
self._context.grammarelts[as_token(ctx)] = JSGArrayExpr(self._context, ctx.arrayExpr()) |
objectMacro : ID EQUALS membersDef SEMI | def visitObjectMacro(self, ctx: jsgParser.ObjectExprContext):
""" objectMacro : ID EQUALS membersDef SEMI """
name = as_token(ctx)
self._context.grammarelts[name] = JSGObjectExpr(self._context, ctx.membersDef(), name) |
valueTypeMacro : ID EQUALS nonRefValueType (BAR nonRefValueType)* SEMI | def visitValueTypeMacro(self, ctx: jsgParser.ValueTypeMacroContext):
""" valueTypeMacro : ID EQUALS nonRefValueType (BAR nonRefValueType)* SEMI """
self._context.grammarelts[as_token(ctx)] = JSGValueType(self._context, ctx) |
lexerRuleSpec: LEXER_ID COLON lexerRuleBlock SEMI | def visitLexerRuleSpec(self, ctx: jsgParser.LexerRuleSpecContext):
""" lexerRuleSpec: LEXER_ID COLON lexerRuleBlock SEMI """
self._context.grammarelts[as_token(ctx)] = JSGLexerRuleBlock(self._context, ctx.lexerRuleBlock()) |
Searches for JSON files in this repo and returns
a map of amendment id ==> (`tag`, dir, amendment filepath)
where `tag` is typically the shard name | def create_id2amendment_info(path, tag):
"""Searches for JSON files in this repo and returns
a map of amendment id ==> (`tag`, dir, amendment filepath)
where `tag` is typically the shard name
"""
d = {}
for triple in os.walk(path):
root, files = triple[0], triple[2]
for filename ... |
Overrides superclass method and renames some properties | def get_configuration_dict(self, secret_attrs=False):
"""Overrides superclass method and renames some properties"""
cd = super(TaxonomicAmendmentsShard, self).get_configuration_dict(secret_attrs=secret_attrs)
# "rename" some keys in the dict provided
cd['number of amendments'] = cd.pop('... |
Read an initial value (int) from our stored counter (file)
Checks out master branch as a side effect! | def _determine_next_ott_id(self):
"""Read an initial value (int) from our stored counter (file)
Checks out master branch as a side effect!
"""
if self._doc_counter_lock is None:
self._doc_counter_lock = Lock()
with self._doc_counter_lock:
_LOG.debug('Read... |
ASSUMES the caller holds the _doc_counter_lock !
Checks the current int value of the next ottid, reserves a block of
{how_many} ids, advances the counter to the next available value,
stores the counter in a file in case the server is restarted.
Checks out master branch as a side effect. | def _mint_new_ott_ids(self, how_many=1):
""" ASSUMES the caller holds the _doc_counter_lock !
Checks the current int value of the next ottid, reserves a block of
{how_many} ids, advances the counter to the next available value,
stores the counter in a file in case the server is restarted... |
Checks out master branch as a side effect | def create_git_action_for_new_amendment(self, new_amendment_id=None):
"""Checks out master branch as a side effect"""
ga = self.create_git_action()
assert new_amendment_id is not None
# id should have been sorted out by the caller
self.register_doc_id(ga, new_amendment_id)
... |
Generate a dummy date list for testing without
hitting the server | def __getDummyDateList():
"""
Generate a dummy date list for testing without
hitting the server
"""
D = []
for y in xrange(2001, 2010):
for d in xrange(1, 365, 1):
D.append('A%04d%03d' % (y, d))
return D |
Convert the webserver formatted dates
to an integer format by stripping the
leading char and casting | def mkIntDate(s):
"""
Convert the webserver formatted dates
to an integer format by stripping the
leading char and casting
"""
n = s.__len__()
d = int(s[-(n - 1):n])
return d |
modisClient: function for building a modisData object | def modisClient(client=None,
product=None,
band=None,
lat=None,
lon=None,
startDate=None,
endDate=None,
chunkSize=8,
kmAboveBelow=0,
kmLeftRight=0):
"""
modisClient: funct... |
Send input agent's cryptonym (including DID, verification key, plus optional alias and role)
to the distributed ledger.
Raise BadLedgerTxn on failure.
:param did: agent DID to send to ledger
:param verkey: agent verification key
:param alias: optional alias
:param role:... | async def send_nym(self, did: str, verkey: str, alias: str = None, role: str = None) -> None:
"""
Send input agent's cryptonym (including DID, verification key, plus optional alias and role)
to the distributed ledger.
Raise BadLedgerTxn on failure.
:param did: agent DID to send... |
Create an ID.
Note that if `prefix` is not provided, it will be `guid`, even if the
`method` is `METHOD_INT`. | def create_id(self, prefix="guid"):
"""Create an ID.
Note that if `prefix` is not provided, it will be `guid`, even if the
`method` is `METHOD_INT`.
"""
if self.method == IDGenerator.METHOD_UUID:
id_ = str(uuid.uuid4())
elif self.method == IDGenerator.METHOD_... |
# ----------QUERY PARAMETERS----------
# Parameter Type Default Description
# lat float n/a Latitude
# lon float n/a Longitude
# dim float 0.025 width and height of image in degrees
# date YYYY-MM-DD today date of image ----if not supplied, then the most recent image (i.e., closest to today) is re... | def imagery(lon=None, lat=None, dim=None, date=None, cloud_score=None):
'''
# ----------QUERY PARAMETERS----------
# Parameter Type Default Description
# lat float n/a Latitude
# lon float n/a Longitude
# dim float 0.025 width and height of image in degrees
# date YYYY-MM-DD today date of ... |
HTTP REQUEST
GET https://api.nasa.gov/planetary/earth/assets
QUERY PARAMETERS
Parameter Type Default Description
lat float n/a Latitude
lon float n/a Longitude
begin YYYY-MM-DD n/a beginning of date range
end YYYY-MM-DD today end of date range
api_key string DEMO_KEY api.nasa.... | def assets(lon=None, lat=None, begin=None, end=None):
'''
HTTP REQUEST
GET https://api.nasa.gov/planetary/earth/assets
QUERY PARAMETERS
Parameter Type Default Description
lat float n/a Latitude
lon float n/a Longitude
begin YYYY-MM-DD n/a beginning of date range
end YYYY-M... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.