_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q55500
GitActionBase._remove_document
train
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...
python
{ "resource": "" }
q55501
GitActionBase.write_document
train
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...
python
{ "resource": "" }
q55502
GitActionBase.write_doc_from_tmpfile
train
def write_doc_from_tmpfile(self, doc_id, tmpfi, parent_sha, auth_info, commit_msg='', doctype_display_name="document"): """Giv...
python
{ "resource": "" }
q55503
TaxonomicAmendmentsGitAction.remove_amendment
train
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 ...
python
{ "resource": "" }
q55504
InclusionRequest.create
train
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 ...
python
{ "resource": "" }
q55505
InclusionRequest.get
train
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()
python
{ "resource": "" }
q55506
Community.filter_communities
train
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...
python
{ "resource": "" }
q55507
Community.add_record
train
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...
python
{ "resource": "" }
q55508
Community.remove_record
train
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...
python
{ "resource": "" }
q55509
Community.accept_record
train
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...
python
{ "resource": "" }
q55510
Community.reject_record
train
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...
python
{ "resource": "" }
q55511
Community.delete
train
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) ...
python
{ "resource": "" }
q55512
Community.logo_url
train
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}'....
python
{ "resource": "" }
q55513
Community.oaiset
train
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....
python
{ "resource": "" }
q55514
Community.oaiset_url
train
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...
python
{ "resource": "" }
q55515
Community.version_id
train
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()
python
{ "resource": "" }
q55516
FeaturedCommunity.get_featured_or_none
train
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...
python
{ "resource": "" }
q55517
connector.getConnectorVersion
train
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: ...
python
{ "resource": "" }
q55518
connector.setHandler
train
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...
python
{ "resource": "" }
q55519
JSGDocParser.as_python
train
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...
python
{ "resource": "" }
q55520
__getDummyDateList
train
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
python
{ "resource": "" }
q55521
mkIntDate
train
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
python
{ "resource": "" }
q55522
IDGenerator.create_id
train
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_...
python
{ "resource": "" }
q55523
grayspec
train
def grayspec(k): """ List of gray-scale colors in HSV space as web hex triplets. For integer argument k, returns list of `k` gray-scale colors, increasingly light, linearly in the HSV color space, as web hex triplets. Technical dependency of :func:`tabular.spreadsheet.aggregate_in`. **Parame...
python
{ "resource": "" }
q55524
addrecords
train
def addrecords(X, new): """ Append one or more records to the end of a numpy recarray or ndarray . Can take a single record, void or tuple, or a list of records, voids or tuples. Implemented by the tabarray method :func:`tabular.tab.tabarray.addrecords`. **Parameters** **X*...
python
{ "resource": "" }
q55525
addcols
train
def addcols(X, cols, names=None): """ Add one or more columns to a numpy ndarray. Technical dependency of :func:`tabular.spreadsheet.aggregate_in`. Implemented by the tabarray method :func:`tabular.tab.tabarray.addcols`. **Parameters** **X** : numpy ndarray with structured dtyp...
python
{ "resource": "" }
q55526
deletecols
train
def deletecols(X, cols): """ Delete columns from a numpy ndarry or recarray. Can take a string giving a column name or comma-separated list of column names, or a list of string column names. Implemented by the tabarray method :func:`tabular.tab.tabarray.deletecols`. **Parameters** ...
python
{ "resource": "" }
q55527
renamecol
train
def renamecol(X, old, new): """ Rename column of a numpy ndarray with structured dtype, in-place. Implemented by the tabarray method :func:`tabular.tab.tabarray.renamecol`. **Parameters** **X** : numpy ndarray with structured dtype The numpy array for which a co...
python
{ "resource": "" }
q55528
replace
train
def replace(X, old, new, strict=True, cols=None, rows=None): """ Replace value `old` with `new` everywhere it appears in-place. Implemented by the tabarray method :func:`tabular.tab.tabarray.replace`. **Parameters** **X** : numpy ndarray with structured dtype Nu...
python
{ "resource": "" }
q55529
rowstack
train
def rowstack(seq, mode='nulls', nullvals=None): ''' Vertically stack a sequence of numpy ndarrays with structured dtype Analog of numpy.vstack Implemented by the tabarray method :func:`tabular.tab.tabarray.rowstack` which uses :func:`tabular.tabarray.tab_rowstack`. **Parameters** ...
python
{ "resource": "" }
q55530
colstack
train
def colstack(seq, mode='abort',returnnaming=False): """ Horizontally stack a sequence of numpy ndarrays with structured dtypes Analog of numpy.hstack for recarrays. Implemented by the tabarray method :func:`tabular.tab.tabarray.colstack` which uses :func:`tabular.tabarray.tab_colstack`. ...
python
{ "resource": "" }
q55531
DEFAULT_RENAMER
train
def DEFAULT_RENAMER(L, Names=None): """ Renames overlapping column names of numpy ndarrays with structured dtypes Rename the columns by using a simple convention: * If `L` is a list, it will append the number in the list to the key associated with the array. * If `L` is a dictionary,...
python
{ "resource": "" }
q55532
getjp2image
train
def getjp2image(date, sourceId=None, observatory=None, instrument=None, detector=None, measurement=None): ''' Helioviewer.org and JHelioviewer operate off of JPEG2000 formatted image data generated from science-quality FITS files. U...
python
{ "resource": "" }
q55533
loads_loader
train
def loads_loader(load_module: types.ModuleType, pairs: Dict[str, str]) -> Optional[JSGValidateable]: """json loader objecthook :param load_module: Module that contains the various types :param pairs: key/value tuples (In our case, they are str/str) :return: """ cntxt = load_module._CONTEXT ...
python
{ "resource": "" }
q55534
loads
train
def loads(s: str, load_module: types.ModuleType, **kwargs): """ Convert a JSON string into a JSGObject :param s: string representation of JSON document :param load_module: module that contains declarations for types :param kwargs: arguments see: json.load for details :return: JSGObject representing...
python
{ "resource": "" }
q55535
load
train
def load(fp: Union[TextIO, str], load_module: types.ModuleType, **kwargs): """ Convert a file name or file-like object containing stringified JSON into a JSGObject :param fp: file-like object to deserialize :param load_module: module that contains declarations for types :param kwargs: arguments see: js...
python
{ "resource": "" }
q55536
isinstance_
train
def isinstance_(x, A_tuple): """ native isinstance_ with the test for typing.Union overridden """ if is_union(A_tuple): return any(isinstance_(x, t) for t in A_tuple.__args__) elif getattr(A_tuple, '__origin__', None) is not None: return isinstance(x, A_tuple.__origin__) else: re...
python
{ "resource": "" }
q55537
is_valid
train
def is_valid(obj: JSGValidateable, log: Optional[Union[TextIO, Logger]] = None) -> bool: """ Determine whether obj is valid :param obj: Object to validate :param log: Logger to record validation failures. If absent, no information is recorded """ return obj._is_valid(log)
python
{ "resource": "" }
q55538
arg_tup_to_dict
train
def arg_tup_to_dict(argument_tuples): """Given a set of argument tuples, set their value in a data dictionary if not blank""" data = dict() for arg_name, arg_val in argument_tuples: if arg_val is not None: if arg_val is True: arg_val = 'true' elif arg_val is F...
python
{ "resource": "" }
q55539
handle_error
train
def handle_error(response): """Raise appropriate exceptions if necessary.""" status_code = response.status_code if status_code not in A_OK_HTTP_CODES: error_explanation = A_ERROR_HTTP_CODES.get(status_code) raise_error = "{}: {}".format(status_code, error_explanation) raise Exceptio...
python
{ "resource": "" }
q55540
_BaseAgent.open
train
async def open(self) -> '_BaseAgent': """ Context manager entry; open wallet. For use when keeping agent open across multiple calls. :return: current object """ LOGGER.debug('_BaseAgent.open >>>') # Do not open pool independently: let relying party decide when ...
python
{ "resource": "" }
q55541
_BaseAgent._get_rev_reg_def
train
async def _get_rev_reg_def(self, rr_id: str) -> str: """ Get revocation registry definition from ledger by its identifier. Raise AbsentRevReg for no such revocation registry, logging any error condition and raising BadLedgerTxn on bad request. Retrieve the revocation registry de...
python
{ "resource": "" }
q55542
_BaseAgent.get_cred_def
train
async def get_cred_def(self, cd_id: str) -> str: """ Get credential definition from ledger by its identifier. Raise AbsentCredDef for no such credential definition, logging any error condition and raising BadLedgerTxn on bad request. Raise ClosedPool if cred def not in cache and pool is...
python
{ "resource": "" }
q55543
is_union
train
def is_union(etype) -> bool: """ Determine whether etype is a Union """ return getattr(etype, '__origin__', None) is not None and \ getattr(etype.__origin__, '_name', None) and\ etype.__origin__._name == 'Union'
python
{ "resource": "" }
q55544
unset
train
def unset(entity, *types): """Unset the TypedFields on the input `entity`. Args: entity: A mixbox.Entity object. *types: A variable-length list of TypedField subclasses. If not provided, defaults to TypedField. """ if not types: types = (TypedField,) fields = li...
python
{ "resource": "" }
q55545
_matches
train
def _matches(field, params): """Return True if the input TypedField `field` contains instance attributes that match the input parameters. Args: field: A TypedField instance. params: A dictionary of TypedField instance attribute-to-value mappings. Returns: True if the input Type...
python
{ "resource": "" }
q55546
iterfields
train
def iterfields(klass): """Iterate over the input class members and yield its TypedFields. Args: klass: A class (usually an Entity subclass). Yields: (class attribute name, TypedField instance) tuples. """ is_field = lambda x: isinstance(x, TypedField) for name, field in inspec...
python
{ "resource": "" }
q55547
TypedField._clean
train
def _clean(self, value): """Validate and clean a candidate value for this field.""" if value is None: return None elif self.type_ is None: return value elif self.check_type(value): return value elif self.is_type_castable: # noqa re...
python
{ "resource": "" }
q55548
TreeCollectionsGitAction.remove_collection
train
def remove_collection(self, first_arg, sec_arg, third_arg, fourth_arg=None, commit_msg=None): """Remove a collection Given a collection_id, branch and optionally an author, remove a collection on the given branch and attribute the commit to author. Returns the SHA of the commit o...
python
{ "resource": "" }
q55549
Verifier.load_cache
train
async def load_cache(self, archive: bool = False) -> int: """ Load caches and archive enough to go offline and be able to verify proof on content marked of interest in configuration. Return timestamp (epoch seconds) of cache load event, also used as subdirectory for cache archiv...
python
{ "resource": "" }
q55550
_Permission.can
train
def can(self): """Grant permission if owner or admin.""" return str(current_user.get_id()) == str(self.community.id_user) or \ DynamicPermission(ActionNeed('admin-access')).can()
python
{ "resource": "" }
q55551
listunion
train
def listunion(ListOfLists): """ Take the union of a list of lists. Take a Python list of Python lists:: [[l11,l12, ...], [l21,l22, ...], ... , [ln1, ln2, ...]] and return the aggregated list:: [l11,l12, ..., l21, l22 , ...] For a list of two lists, e.g. `[a, b]`, this is...
python
{ "resource": "" }
q55552
DEFAULT_NULLVALUE
train
def DEFAULT_NULLVALUE(test): """ Returns a null value for each of various kinds of test values. **Parameters** **test** : bool, int, float or string Value to test. **Returns** **null** : element in `[False, 0, 0.0, '']` Null value c...
python
{ "resource": "" }
q55553
JSGObjectExpr.as_python
train
def as_python(self, name: str) -> str: """ Return the python representation of the class represented by this object """ if self._map_valuetype: return self.map_as_python(name) else: return self.obj_as_python(name)
python
{ "resource": "" }
q55554
JSGObjectExpr.members_entries
train
def members_entries(self, all_are_optional: bool=False) -> List[Tuple[str, str]]: """ Return an ordered list of elements for the _members section :param all_are_optional: True means we're in a choice situation so everything is optional :return: """ rval = [] if self._mem...
python
{ "resource": "" }
q55555
_get_filtered_study_ids
train
def _get_filtered_study_ids(shard, include_aliases=False): """Optionally filters out aliases from standard doc-id list""" from peyotl.phylesystem.helper import DIGIT_PATTERN k = shard.get_doc_ids() if shard.has_aliases and (not include_aliases): x = [] for i in k: if DIGIT_PA...
python
{ "resource": "" }
q55556
PhylesystemShard._determine_next_study_id
train
def _determine_next_study_id(self): """Return the numeric part of the newest study_id Checks out master branch as a side effect! """ if self._doc_counter_lock is None: self._doc_counter_lock = Lock() prefix = self._new_study_prefix lp = len(prefix) n ...
python
{ "resource": "" }
q55557
PhylesystemShard._advance_new_study_id
train
def _advance_new_study_id(self): """ ASSUMES the caller holds the _doc_counter_lock ! Returns the current numeric part of the next study ID, advances the counter to the next value, and stores that value in the file in case the server is restarted. """ c = self._next_study...
python
{ "resource": "" }
q55558
flatten
train
def flatten(l: Iterable) -> List: """Return a list of all non-list items in l :param l: list to be flattened :return: """ rval = [] for e in l: if not isinstance(e, str) and isinstance(e, Iterable): if len(list(e)): rval += flatten(e) else: ...
python
{ "resource": "" }
q55559
flatten_unique
train
def flatten_unique(l: Iterable) -> List: """ Return a list of UNIQUE non-list items in l """ rval = OrderedDict() for e in l: if not isinstance(e, str) and isinstance(e, Iterable): for ev in flatten_unique(e): rval[ev] = None else: rval[e] = None r...
python
{ "resource": "" }
q55560
as_tokens
train
def as_tokens(ctx: List[ParserRuleContext]) -> List[str]: """Return a stringified list of identifiers in ctx :param ctx: JSG parser item with a set of identifiers :return: """ return [as_token(e) for e in ctx]
python
{ "resource": "" }
q55561
is_valid_python
train
def is_valid_python(tkn: str) -> bool: """Determine whether tkn is a valid python identifier :param tkn: :return: """ try: root = ast.parse(tkn) except SyntaxError: return False return len(root.body) == 1 and isinstance(root.body[0], ast.Expr) and isinstance(root.body[0].val...
python
{ "resource": "" }
q55562
PhylesystemGitAction.remove_study
train
def remove_study(self, first_arg, sec_arg, third_arg, fourth_arg=None, commit_msg=None): """Remove a study Given a study_id, branch and optionally an author, remove a study on the given branch and attribute the commit to author. Returns the SHA of the commit on branch. ""...
python
{ "resource": "" }
q55563
init
train
def init(): """Initialize the communities file storage.""" try: initialize_communities_bucket() click.secho('Community init successful.', fg='green') except FilesException as e: click.secho(e.message, fg='red')
python
{ "resource": "" }
q55564
addlogo
train
def addlogo(community_id, logo): """Add logo to the community.""" # Create the bucket c = Community.get(community_id) if not c: click.secho('Community {0} does not exist.'.format(community_id), fg='red') return ext = save_and_validate_logo(logo, logo.name, c.id) ...
python
{ "resource": "" }
q55565
request
train
def request(community_id, record_id, accept): """Request a record acceptance to a community.""" c = Community.get(community_id) assert c is not None record = Record.get_record(record_id) if accept: c.add_record(record) record.commit() else: InclusionRequest.create(communi...
python
{ "resource": "" }
q55566
remove
train
def remove(community_id, record_id): """Remove a record from community.""" c = Community.get(community_id) assert c is not None c.remove_record(record_id) db.session.commit() RecordIndexer().index_by_id(record_id)
python
{ "resource": "" }
q55567
gen_otu_dict
train
def gen_otu_dict(nex_obj, nexson_version=None): """Takes a NexSON object and returns a dict of otu_id -> otu_obj """ if nexson_version is None: nexson_version = detect_nexson_version(nex_obj) if _is_by_id_hbf(nexson_version): otus = nex_obj['nexml']['otusById'] if len(otus) >...
python
{ "resource": "" }
q55568
set_country
train
def set_country(request): """ Sets the chosen country in the session or cookie. If `next' query param is present, it redirects to a given url. """ if request.method == 'POST': next = request.POST.get('next', request.GET.get('next')) if is_safe_url(url=next, host=request.get_host()):...
python
{ "resource": "" }
q55569
JSGDocContext.reference
train
def reference(self, tkn: str): """ Return the element that tkn represents""" return self.grammarelts[tkn] if tkn in self.grammarelts else UndefinedElement(tkn)
python
{ "resource": "" }
q55570
JSGDocContext.dependency_list
train
def dependency_list(self, tkn: str) -> List[str]: """Return a list all of the grammarelts that depend on tkn :param tkn: :return: """ if tkn not in self.dependency_map: self.dependency_map[tkn] = [tkn] # Force a circular reference self.dependency_...
python
{ "resource": "" }
q55571
JSGDocContext.dependencies
train
def dependencies(self, tkn: str) -> Set[str]: """Return all the items that tkn depends on as a set :param tkn: :return: """ return set(self.dependency_list(tkn))
python
{ "resource": "" }
q55572
JSGDocContext.undefined_entries
train
def undefined_entries(self) -> Set[str]: """ Return the set of tokens that are referenced but not defined. """ return as_set([[d for d in self.dependencies(k) if d not in self.grammarelts] for k in self.grammarelts.keys()])
python
{ "resource": "" }
q55573
new_request
train
def new_request(sender, request=None, notify=True, **kwargs): """New request for inclusion.""" if current_app.config['COMMUNITIES_MAIL_ENABLED'] and notify: send_community_request_email(request)
python
{ "resource": "" }
q55574
inject_provisional_community
train
def inject_provisional_community(sender, json=None, record=None, index=None, **kwargs): """Inject 'provisional_communities' key to ES index.""" if index and not index.startswith( current_app.config['COMMUNITIES_INDEX_PREFIX']): return json['provisional_c...
python
{ "resource": "" }
q55575
_OTIWrapper.find_nodes
train
def find_nodes(self, query_dict=None, exact=False, verbose=False, **kwargs): """Query on node properties. See documentation for _OTIWrapper class.""" assert self.use_v1 return self._do_query('{p}/singlePropertySearchForTreeNodes'.format(p=self.query_prefix), query_d...
python
{ "resource": "" }
q55576
_OTIWrapper.find_trees
train
def find_trees(self, query_dict=None, exact=False, verbose=False, wrap_response=False, **kwargs): """Query on tree properties. See documentation for _OTIWrapper class.""" if self.use_v1: uri = '{p}/singlePropertySearchForTrees'.format(p=self.query_prefix) else: uri = '{p}...
python
{ "resource": "" }
q55577
_OTIWrapper.find_studies
train
def find_studies(self, query_dict=None, exact=False, verbose=False, **kwargs): """Query on study properties. See documentation for _OTIWrapper class.""" if self.use_v1: uri = '{p}/singlePropertySearchForStudies'.format(p=self.query_prefix) else: uri = '{p}/find_studies'.f...
python
{ "resource": "" }
q55578
get_requirements
train
def get_requirements(): '''returns requirements array for package''' packages = [] with open("requirements.txt", "r") as req_doc: for package in req_doc: packages.append(package.replace("\n", "")) return packages
python
{ "resource": "" }
q55579
TaxonomicAmendmentStore
train
def TaxonomicAmendmentStore(repos_dict=None, repos_par=None, with_caching=True, assumed_doc_version=None, git_ssh=None, pkey=None, git_action_class=Taxo...
python
{ "resource": "" }
q55580
delete_marked_communities
train
def delete_marked_communities(): """Delete communities after holdout time.""" # TODO: Delete the community ID from all records metadata first raise NotImplementedError() Community.query.filter_by( Community.delete_time > datetime.utcnow()).delete() db.session.commit()
python
{ "resource": "" }
q55581
delete_expired_requests
train
def delete_expired_requests(): """Delete expired inclusion requests.""" InclusionRequest.query.filter_by( InclusionRequest.expiry_date > datetime.utcnow()).delete() db.session.commit()
python
{ "resource": "" }
q55582
create_content_spec
train
def create_content_spec(**kwargs): """Sugar. factory for a PhyloSchema object. Repackages the kwargs to kwargs for PhyloSchema so that our PhyloSchema.__init__ does not have to be soo rich """ format_str = kwargs.get('format', 'nexson') nexson_version = kwargs.get('nexson_version', 'native') ...
python
{ "resource": "" }
q55583
convert_nexson_format
train
def convert_nexson_format(blob, out_nexson_format, current_format=None, remove_old_structs=True, pristine_if_invalid=False, sort_arbitrary=False): """Take a dict form of NexSON and conve...
python
{ "resource": "" }
q55584
_inplace_sort_by_id
train
def _inplace_sort_by_id(unsorted_list): """Takes a list of dicts each of which has an '@id' key, sorts the elements in the list by the value of the @id key. Assumes that @id is unique or the dicts have a meaningul < operator """ if not isinstance(unsorted_list, list): return sorted_list ...
python
{ "resource": "" }
q55585
cull_nonmatching_trees
train
def cull_nonmatching_trees(nexson, tree_id, curr_version=None): """Modifies `nexson` and returns it in version 1.2.1 with any tree that does not match the ID removed. Note that this does not search through the NexSON for every node, edge, tree that was deleted. So the resulting NexSON may have brok...
python
{ "resource": "" }
q55586
PhyloSchema.phylesystem_api_url
train
def phylesystem_api_url(self, base_url, study_id): """Returns URL and param dict for a GET call to phylesystem_api """ p = self._phylesystem_api_params() e = self._phylesystem_api_ext() if self.content == 'study': return '{d}/study/{i}{e}'.format(d=base_url, i=study_i...
python
{ "resource": "" }
q55587
JSGArray._is_valid
train
def _is_valid(self, log: Optional[Logger] = None) -> bool: """ Determine whether the current contents are valid """ return self._validate(self, log)[0]
python
{ "resource": "" }
q55588
JSGArray._validate
train
def _validate(self, val: list, log: Optional[Logger] = None) -> Tuple[bool, List[str]]: """ Determine whether val is a valid instance of this array :returns: Success indicator and error list """ errors = [] if not isinstance(val, list): errors.append(f"{self._variable_name}:...
python
{ "resource": "" }
q55589
tree_iter_nexson_proxy
train
def tree_iter_nexson_proxy(nexson_proxy): """Iterates over NexsonTreeProxy objects in order determined by the nexson blob""" nexml_el = nexson_proxy._nexml_el tg_order = nexml_el['^ot:treesElementOrder'] tgd = nexml_el['treesById'] for tg_id in tg_order: tg = tgd[tg_id] tree_order = ...
python
{ "resource": "" }
q55590
main
train
def main(): """Get status from APC NIS and print output on stdout.""" # No need to use "proper" names on such simple code. # pylint: disable=invalid-name p = argparse.ArgumentParser() p.add_argument("--host", default="localhost") p.add_argument("--port", type=int, default=3551) p.add_argumen...
python
{ "resource": "" }
q55591
Server.wsgi_app
train
def wsgi_app(self, environ, start_response): """A basic WSGI app""" @_LOCAL_MANAGER.middleware def _wrapped_app(environ, start_response): request = Request(environ) setattr(_local, _CURRENT_REQUEST_KEY, request) response = self._dispatch_request(request) ...
python
{ "resource": "" }
q55592
Server.run
train
def run(self, host, port, **options): """For debugging purposes, you can run this as a standalone server. .. WARNING:: **Security vulnerability** This uses :class:`DebuggedJsonRpcApplication` to assist debugging. If you want to use this in production, you should run :class:`Ser...
python
{ "resource": "" }
q55593
Server._try_trigger_before_first_request_funcs
train
def _try_trigger_before_first_request_funcs(self): # pylint: disable=C0103 """Runs each function from ``self.before_first_request_funcs`` once and only once.""" if self._after_first_request_handled: return else: with self._before_first_request_lock: if se...
python
{ "resource": "" }
q55594
DebuggedJsonRpcApplication.debug_application
train
def debug_application(self, environ, start_response): """Run the application and preserve the traceback frames. :param environ: The environment which is passed into the wsgi application :type environ: dict[str, object] :param start_response: The start_response function of the wsgi appli...
python
{ "resource": "" }
q55595
DebuggedJsonRpcApplication.handle_debug
train
def handle_debug(self, environ, start_response, traceback_id): """Handles the debug endpoint for inspecting previous errors. :param environ: The environment which is passed into the wsgi application :type environ: dict[str, object] :param start_response: The start_response function of t...
python
{ "resource": "" }
q55596
InvenioCommunities.register_signals
train
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) ...
python
{ "resource": "" }
q55597
genargs
train
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...
python
{ "resource": "" }
q55598
JSGPython._to_string
train
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: ...
python
{ "resource": "" }
q55599
JSGPython.conforms
train
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...
python
{ "resource": "" }