text stringlengths 81 112k |
|---|
Format datetime to HTTP Full Date format.
Args:
dt : datetime
- tz-aware: Used in the formatted string.
- tz-naive: Assumed to be in UTC.
Returns:
str
The returned format is a is fixed-length subset of that defined by RFC 1123 and
is
the preferred format fo... |
Parse HTTP Full Date formats and return as datetime.
Args:
http_full_datetime : str
Each of the allowed formats are supported:
- Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
- Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
- Sun Nov 6 08:49:... |
Adjust datetime to UTC.
Apply the timezone offset to the datetime and set the timezone to UTC.
This is a no-op if the datetime is already in UTC.
Args:
dt : datetime
- tz-aware: Used in the formatted string.
- tz-naive: Assumed to be in UTC.
Returns:
datetime
The ... |
If datetime is tz-naive, set it to ``tz``. If datetime is tz-aware, return it
unmodified.
Args:
dt : datetime
tz-naive or tz-aware datetime.
tz : datetime.tzinfo
The timezone to which to adjust tz-naive datetime.
Returns:
datetime
tz-aware datetime.
Warning:... |
Round datetime up or down to nearest divisor.
Round datetime up or down to nearest number of seconds that divides evenly by
the divisor.
Any timezone is preserved but ignored in the rounding.
Args:
dt: datetime
n_round_sec : int or float
Divisor for rounding
Examples:
... |
Run process with SLURM.
For details, see
:meth:`~resolwe.flow.managers.workload_connectors.base.BaseConnector.submit`.
def submit(self, data, runtime_dir, argv):
"""Run process with SLURM.
For details, see
:meth:`~resolwe.flow.managers.workload_connectors.base.BaseConnector.su... |
Get files to purge.
def get_purge_files(root, output, output_schema, descriptor, descriptor_schema):
"""Get files to purge."""
def remove_file(fn, paths):
"""From paths remove fn and dirs before fn in dir tree."""
while fn:
for i in range(len(paths) - 1, -1, -1):
if ... |
Print and conditionally delete files not referenced by meta data.
:param location_id: Id of the
:class:`~resolwe.flow.models.DataLocation` model that data
objects reference to.
:param delete: If ``True``, then delete unreferenced files.
def location_purge(location_id, delete=False, verbosity=0... |
Purge all data locations.
def _location_purge_all(delete=False, verbosity=0):
"""Purge all data locations."""
if DataLocation.objects.exists():
for location in DataLocation.objects.filter(Q(purged=False) | Q(data=None)):
location_purge(location.id, delete, verbosity)
else:
logge... |
Purge unreferenced storages.
def _storage_purge_all(delete=False, verbosity=0):
"""Purge unreferenced storages."""
orphaned_storages = Storage.objects.filter(data=None)
if verbosity >= 1:
if orphaned_storages.exists():
logger.info(__("Unreferenced storages ({}):", orphaned_storages.cou... |
Purge all data locations.
def purge_all(delete=False, verbosity=0):
"""Purge all data locations."""
_location_purge_all(delete, verbosity)
_storage_purge_all(delete, verbosity) |
Convert value from an AST node.
def get_value(self, node):
"""Convert value from an AST node."""
if not isinstance(node, ast.Str):
raise TypeError("must be a string literal")
return node.s |
Convert value from an AST node.
def get_value(self, node):
"""Convert value from an AST node."""
if not isinstance(node, ast.Attribute):
raise TypeError("must be an attribute")
if node.value.id != self.choices.__name__:
raise TypeError("must be an attribute of {}".forma... |
Convert value from an AST node.
def get_value(self, node):
"""Convert value from an AST node."""
if not isinstance(node, ast.Dict):
raise TypeError("must be a dictionary")
evaluator = SafeEvaluator()
try:
value = evaluator.run(node)
except Exception as e... |
Visit a class node containing a list of field definitions.
def visit_field_class(self, item, descriptor=None, fields=None):
"""Visit a class node containing a list of field definitions."""
discovered_fields = collections.OrderedDict()
field_groups = {}
for node in item.body:
... |
Visit top-level classes.
def visit_ClassDef(self, node): # pylint: disable=invalid-name
"""Visit top-level classes."""
# Resolve everything as root scope contains everything from the process module.
for base in node.bases:
# Cover `from resolwe.process import ...`.
if i... |
Parse process.
:return: A list of discovered process descriptors
def parse(self):
"""Parse process.
:return: A list of discovered process descriptors
"""
root = ast.parse(self._source)
visitor = ProcessVisitor(source=self._source)
visitor.visit(root)
r... |
Load and cache permissions class.
If ``permissions_name`` is not given, it defaults to permissions
class set in Django ``FLOW_API['PERMISSIONS']`` setting.
def get_permissions_class(permissions_name=None):
"""Load and cache permissions class.
If ``permissions_name`` is not given, it defaults to permi... |
Save the model.
def save(self, *args, **kwargs):
"""Save the model."""
name_max_len = self._meta.get_field('name').max_length
if len(self.name) > name_max_len:
self.name = self.name[:(name_max_len - 3)] + '...'
for _ in range(MAX_SLUG_RETRIES):
try:
... |
Get set of identifiers that provide revision context for SciObj.
Returns: tuple: PID, SID, OBSOLETES_PID, OBSOLETED_BY_PID
def get_identifiers(sysmeta_pyxb):
"""Get set of identifiers that provide revision context for SciObj.
Returns: tuple: PID, SID, OBSOLETES_PID, OBSOLETED_BY_PID
"""
pid ... |
Sort objects by dependency.
Sort a dict of obsoleting PID to obsoleted PID to a list of PIDs in order of
obsolescence.
Args:
unsorted_dict : dict
Dict that holds obsolescence information. Each ``key/value`` pair establishes
that the PID in ``key`` identifies an object that obsoletes ... |
Args: client: d1_client.cnclient.CoordinatingNodeClient or
d1_client.mnclient.MemberNodeClient.
did : str
SID or a PID of any object in a revision chain.
Returns:
list of str:
All PIDs in the chain. The returned list is in the same order as the chain. The
initial PID is typ... |
Remove unused imports Unsafe!
Only tested on our codebase, which uses simple absolute imports on the form, "import
a.b.c".
def main():
"""Remove unused imports Unsafe!
Only tested on our codebase, which uses simple absolute imports on the form, "import
a.b.c".
"""
parser = argparse.Argum... |
Find all triple-quoted docstrings in module.
def get_docstr_list(red):
"""Find all triple-quoted docstrings in module."""
docstr_list = []
for n in red.find_all("string"):
if n.value.startswith('"""'):
docstr_list.append(n)
return docstr_list |
Group lines of a docstring to blocks.
For now, only groups markdown list sections.
A block designates a list of consequtive lines that all start at the same
indentation level.
The lines of the docstring are iterated top to bottom. Each line is added to
`block_list` until a line is encountered tha... |
Wrap a single line to one or more lines that start at indent_int and end at the
last word that will fit before WRAP_MARGIN_INT.
If there are no word breaks (spaces) before WRAP_MARGIN_INT, force a break at
WRAP_MARGIN_INT.
def wrap(indent_int, unwrap_str):
"""Wrap a single line to one or more lines th... |
Create a simple OAI-ORE Resource Map with one Science Metadata document and any
number of Science Data objects.
This creates a document that establishes an association between a Science Metadata
object and any number of Science Data objects. The Science Metadata object contains
information that is inde... |
Create a simple OAI-ORE Resource Map with one Science Metadata document and any
number of Science Data objects, using a stream of PIDs.
Args:
in_stream:
The first non-blank line is the PID of the resource map itself. Second line is
the science metadata PID and remaining lines are science ... |
Create the basic ORE document structure.
def initialize(self, pid, ore_software_id=d1_common.const.ORE_SOFTWARE_ID):
"""Create the basic ORE document structure."""
# Set nice prefixes for the namespaces
for k in list(d1_common.const.ORE_NAMESPACE_DICT.keys()):
self.bind(k, d1_common... |
Serialize ResourceMap to UTF-8 encoded XML document.
Args:
doc_format: str
One of: ``xml``, ``n3``, ``turtle``, ``nt``, ``pretty-xml``, ``trix``,
``trig`` and ``nquads``.
args and kwargs:
Optional arguments forwarded to rdflib.ConjunctiveGraph.serialize(... |
Serialize ResourceMap to an XML doc that is pretty printed for display.
Args:
doc_format: str
One of: ``xml``, ``n3``, ``turtle``, ``nt``, ``pretty-xml``, ``trix``,
``trig`` and ``nquads``.
args and kwargs:
Optional arguments forwarded to rdflib.Conjunct... |
Deserialize Resource Map XML doc.
The source is specified using one of source, location, file or data.
Args:
source: InputSource, file-like object, or string
In the case of a string the string is the location of the source.
location: str
String indicating t... |
Returns:
str : URIRef of the Aggregation entity
def getAggregation(self):
"""Returns:
str : URIRef of the Aggregation entity
"""
self._check_initialized()
return [
o for o in self.subjects(predicate=rdflib.RDF.type, object=ORE.Aggregation)
][0] |
Args:
pid : str
Returns:
str : URIRef of the entry identified by ``pid``.
def getObjectByPid(self, pid):
"""
Args:
pid : str
Returns:
str : URIRef of the entry identified by ``pid``."""
self._check_initialized()
opid = rdflib.term.Literal(pid)
res =... |
Add a resource to the Resource Map.
Args:
pid : str
def addResource(self, pid):
"""Add a resource to the Resource Map.
Args:
pid : str
"""
self._check_initialized()
try:
# is entry already in place?
self.getObjectByPid(pid)
... |
Add a CiTO, the Citation Typing Ontology, triple asserting that
``documenting_pid`` documents ``documented_pid``.
Adds assertion: ``documenting_pid cito:documents documented_pid``
Args:
documenting_pid: str
PID of a Science Object that documents ``documented_pid``.
... |
Add a CiTO, the Citation Typing Ontology, triple asserting that
``documented_pid`` isDocumentedBy ``documenting_pid``.
Adds assertion: ``documented_pid cito:isDocumentedBy documenting_pid``
Args:
documented_pid: str
PID of a Science Object that is documented by ``document... |
Add Science Data object(s)
Args:
scidata_pid_list : list of str
List of one or more PIDs of Science Data objects
scimeta_pid: str
PID of a Science Metadata object that documents the Science Data objects.
def addDataDocuments(self, scidata_pid_list, scimeta_pid=None... |
Returns:
str : PID of the Resource Map itself.
def getResourceMapPid(self):
"""Returns:
str : PID of the Resource Map itself.
"""
ore = [
o for o in self.subjects(predicate=rdflib.RDF.type, object=ORE.ResourceMap)
][0]
pid = [str(o) for o in self.o... |
Returns:
list of tuples : Each tuple holds a subject, predicate, object triple
def getAllTriples(self):
"""Returns:
list of tuples : Each tuple holds a subject, predicate, object triple
"""
return [(str(s), str(p), str(o)) for s, p, o in self] |
Args:
predicate : str
Predicate for which to return subject, object tuples.
Returns:
list of subject, object tuples: All subject/objects with ``predicate``.
Notes:
Equivalent SPARQL:
.. highlight: sql
::
SELECT DISTINCT ?s ?o
WHERE {{
?s {0} ... |
Parse a OAI-ORE Resource Maps document.
See Also: ``rdflib.ConjunctiveGraph.parse`` for documentation on arguments.
def parseDoc(self, doc_str, format="xml"):
"""Parse a OAI-ORE Resource Maps document.
See Also: ``rdflib.ConjunctiveGraph.parse`` for documentation on arguments.
""... |
Converts a pid to a URI that can be used as an OAI-ORE identifier.
def _pid_to_id(self, pid):
"""Converts a pid to a URI that can be used as an OAI-ORE identifier."""
return d1_common.url.joinPathElements(
self._base_url,
self._version_tag,
"resolve",
d1_... |
Make batch files required for checking checksums from another machine.
def make_checksum_validation_script(stats_list):
"""Make batch files required for checking checksums from another machine."""
if not os.path.exists('./hash_check'):
os.mkdir('./hash_check')
with open('./hash_check/curl.sh', 'w'... |
:returns: A :class:`~django.forms.FloatField` with ``max_value`` 90 and
``min_value`` -90.
def formfield(self, **kwargs):
"""
:returns: A :class:`~django.forms.FloatField` with ``max_value`` 90 and
``min_value`` -90.
"""
kwargs.update({
'max_value': 9... |
:returns: A :class:`~django.forms.FloatField` with ``max_value`` 180 and
``min_value`` -180.
def formfield(self, **kwargs):
"""
:returns: A :class:`~django.forms.FloatField` with ``max_value`` 180 and
``min_value`` -180.
"""
kwargs.update({
'max_value... |
:returns: A :class:`~osm_field.forms.OSMFormField` with a
:class:`~osm_field.widgets.OSMWidget`.
def formfield(self, **kwargs):
"""
:returns: A :class:`~osm_field.forms.OSMFormField` with a
:class:`~osm_field.widgets.OSMWidget`.
"""
widget_kwargs = {
... |
The name of the related :class:`LatitudeField`.
def latitude_field_name(self):
"""
The name of the related :class:`LatitudeField`.
"""
if self._lat_field_name is None:
self._lat_field_name = self.name + '_lat'
return self._lat_field_name |
The name of the related :class:`LongitudeField`.
def longitude_field_name(self):
"""
The name of the related :class:`LongitudeField`.
"""
if self._lon_field_name is None:
self._lon_field_name = self.name + '_lon'
return self._lon_field_name |
Update historical dependency kinds as they may be wrong.
def update_dependency_kinds(apps, schema_editor):
"""Update historical dependency kinds as they may be wrong."""
DataDependency = apps.get_model('flow', 'DataDependency')
for dependency in DataDependency.objects.all():
# Assume dependency is ... |
Escape given value.
def escape(self, value):
"""Escape given value."""
value = soft_unicode(value)
if self._engine._escape is None: # pylint: disable=protected-access
return value
return self._engine._escape(value) |
Propagate exceptions as undefined values filter.
def _wrap_jinja_filter(self, function):
"""Propagate exceptions as undefined values filter."""
def wrapper(*args, **kwargs):
"""Filter wrapper."""
try:
return function(*args, **kwargs)
except Exception:... |
Register any custom filter modules.
def _register_custom_filters(self):
"""Register any custom filter modules."""
custom_filters = self.settings.get('CUSTOM_FILTERS', [])
if not isinstance(custom_filters, list):
raise KeyError("`CUSTOM_FILTERS` setting must be a list.")
for... |
Configure the evaluation context.
def _evaluation_context(self, escape, safe_wrapper):
"""Configure the evaluation context."""
self._escape = escape
self._safe_wrapper = safe_wrapper
try:
yield
finally:
self._escape = None
self._safe_wrapper ... |
Evaluate a template block.
def evaluate_block(self, template, context=None, escape=None, safe_wrapper=None):
"""Evaluate a template block."""
if context is None:
context = {}
try:
with self._evaluation_context(escape, safe_wrapper):
template = self._envi... |
Evaluate an inline expression.
def evaluate_inline(self, expression, context=None, escape=None, safe_wrapper=None):
"""Evaluate an inline expression."""
if context is None:
context = {}
try:
with self._evaluation_context(escape, safe_wrapper):
compiled =... |
Set show_diff to False to overwrite module_path with a new file generated from
``redbaron_tree``.
Returns True if tree is different from source.
def update_module_file(redbaron_tree, module_path, show_diff=False, dry_run=False):
"""Set show_diff to False to overwrite module_path with a new file generated ... |
Given a path to an item in a git repository, find the root of the repository.
def find_repo_root_by_path(path):
"""Given a path to an item in a git repository, find the root of the repository."""
repo = git.Repo(path, search_parent_directories=True)
repo_path = repo.git.rev_parse('--show-toplevel')
log... |
A value that exists in the operation but has value None is displayed.
A value that does not exist in the operation is left out entirely. The value
name in the operation must match the value name in the template, but the
location does not have to match.
def _format_value(self, operation, key, i... |
Add Cross-Origin Resource Sharing (CORS) headers to response.
- ``method_list`` is a list of HTTP methods that are allowed for the endpoint that
was called. It should not include "OPTIONS", which is included automatically
since it's allowed for all endpoints.
def add_cors_headers(response, request):
... |
Run a new process from a running process.
def run_process(self, slug, inputs):
"""Run a new process from a running process."""
def export_files(value):
"""Export input files of spawned process."""
if isinstance(value, str) and os.path.isfile(value):
# TODO: Use t... |
Log informational message.
def info(self, *args):
"""Log informational message."""
report = resolwe_runtime_utils.info(' '.join([str(x) for x in args]))
# TODO: Use the protocol to report progress.
print(report) |
Find data object ID for given slug.
This method queries the Resolwe API and requires network access.
def get_data_id_by_slug(self, slug):
"""Find data object ID for given slug.
This method queries the Resolwe API and requires network access.
"""
resolwe_host = os.environ.get('... |
Process requirements.
def requirements(self):
"""Process requirements."""
class dotdict(dict): # pylint: disable=invalid-name
"""Dot notation access to dictionary attributes."""
def __getattr__(self, attr):
value = self.get(attr)
return dotdict(... |
Start the process.
:param inputs: An instance of `Inputs` describing the process inputs
:return: An instance of `Outputs` describing the process outputs
def start(self, inputs):
"""Start the process.
:param inputs: An instance of `Inputs` describing the process inputs
:return:... |
Perform process discovery in given path.
This method will be called during process registration and
should return a list of dictionaries with discovered process
schemas.
def discover_process(self, path):
"""Perform process discovery in given path.
This method will be called du... |
Evaluate the code needed to compute a given Data object.
def evaluate(self, data):
"""Evaluate the code needed to compute a given Data object."""
return 'PYTHONPATH="{runtime}" python3 -u -m resolwe.process {program} --slug {slug} --inputs {inputs}'.format(
runtime=PYTHON_RUNTIME_VOLUME,
... |
Prepare runtime directory.
def prepare_runtime(self, runtime_dir, data):
"""Prepare runtime directory."""
# Copy over Python process runtime (resolwe.process).
import resolwe.process as runtime_package
src_dir = os.path.dirname(inspect.getsourcefile(runtime_package))
dest_packa... |
Validate the JWT and return the subject it contains.
- The JWT is validated by checking that it was signed with a CN certificate.
- The returned subject can be trusted for authz and authn operations.
- Possible validation errors include:
- A trusted (TLS/SSL) connection could not be made to the C... |
Same as get_subject_with_local_validation() except that the signing certificate
is automatically downloaded from the CN.
- Additional possible validations errors:
- The certificate could not be retrieved from the root CN.
def get_subject_with_remote_validation(jwt_bu64, base_url):
"""Same as get_su... |
Same as get_subject_with_local_validation() except that the signing certificate
is read from a local PEM file.
def get_subject_with_file_validation(jwt_bu64, cert_path):
"""Same as get_subject_with_local_validation() except that the signing certificate
is read from a local PEM file."""
cert_obj = d1_co... |
Extract subject from the JWT without validating the JWT.
- The extracted subject cannot be trusted for authn or authz.
Args:
jwt_bu64: bytes
JWT, encoded using a a URL safe flavor of Base64.
Returns:
str: The subject contained in the JWT.
def get_subject_without_validation(jwt_bu64):... |
Parse Base64 encoded JWT and return as a dict.
- JWTs contain a set of values serialized to a JSON dict. This decodes the JWT and
returns it as a dict containing Unicode strings.
- In addition, a SHA1 hash is added to the dict for convenience.
Args:
jwt_bu64: bytes
JWT, encoded using a... |
Validate the JWT and return as a dict.
- JWTs contain a set of values serialized to a JSON dict. This decodes the JWT and
returns it as a dict.
Args:
jwt_bu64: bytes
The JWT encoded using a a URL safe flavor of Base64.
cert_obj: cryptography.Certificate
Public certificate us... |
Dump JWT to log.
Args:
log: Logger
Logger to which to write the message.
msg_str: str
A message to write to the log before the JWT values.
jwt_dict: dict
JWT containing values to log.
Returns:
None
def log_jwt_dict_info(log, msg_str, jwt_dict):
"""Dump JW... |
Convert timestamps in JWT to human readable dates.
Args:
jwt_dict: dict
JWT with some keys containing timestamps.
Returns:
dict: Copy of input dict where timestamps have been replaced with human readable
dates.
def ts_to_str(jwt_dict):
"""Convert timestamps in JWT to human reada... |
Convert timestamps in JWT to datetime objects.
Args:
jwt_dict: dict
JWT with some keys containing timestamps.
Returns:
dict: Copy of input dict where timestamps have been replaced with
datetime.datetime() objects.
def ts_to_dt(jwt_dict):
"""Convert timestamps in JWT to datetime ... |
Encode bytes to a URL safe flavor of Base64 used by JWTs.
- Reverse of decode_bu64().
Args:
b: bytes
Bytes to Base64 encode.
Returns:
bytes: URL safe Base64 encoded version of input.
def encode_bu64(b):
"""Encode bytes to a URL safe flavor of Base64 used by JWTs.
- Reverse o... |
Encode bytes to a URL safe flavor of Base64 used by JWTs.
- Reverse of encode_bu64().
Args:
b: bytes
URL safe Base64 encoded bytes to encode.
Returns:
bytes: Decoded bytes.
def decode_bu64(b):
"""Encode bytes to a URL safe flavor of Base64 used by JWTs.
- Reverse of encode_b... |
Evaluate the code needed to compute a given Data object.
def evaluate(self, data):
"""Evaluate the code needed to compute a given Data object."""
try:
inputs = copy.deepcopy(data.input)
hydrate_input_references(inputs, data.process.input_schema)
hydrate_input_uploads... |
Escape given value unless it is safe.
def _escape(self, value):
"""Escape given value unless it is safe."""
if isinstance(value, SafeString):
return value
return shellescape.quote(value) |
Open the file containing the Science Object bytes of ``pid`` in the default
location within the tree of the local SciObj store.
If ``write`` is True, the file is opened for writing and any missing directories are
created. Return the file handle and file_url with the file location in a suitable
form for... |
Open the file containing the Science Object bytes at the custom location
``abs_path`` in the local filesystem.
If ``write`` is True, the file is opened for writing and any missing directores are
created. Return the file handle and file_url with the file location in a suitable
form for storing in the DB... |
Open the file containing the Science Object bytes at the custom location
``abs_path`` in the local filesystem for read.
def open_sciobj_file_by_pid(pid, write=False):
"""Open the file containing the Science Object bytes at the custom location
``abs_path`` in the local filesystem for read."""
abs_path =... |
Open a SciObj file for read or write. If opened for write, create any missing
directories. For a SciObj stored in the default SciObj store, the path includes the
PID hash based directory levels.
This is the only method in GMN that opens SciObj files, so can be modified to
customize the SciObj storage l... |
Get the relative local path to the file holding an object's bytes.
- The path is relative to settings.OBJECT_STORE_PATH
- There is a one-to-one mapping between pid and path
- The path is based on a SHA1 hash. It's now possible to craft SHA1 collisions, but
it's so unlikely that we ignore it for now
... |
Get the absolute path to the file holding an object's bytes.
- ``file_url`` is an absolute or relative file:// url as stored in the DB.
def get_abs_sciobj_file_path_by_url(file_url):
"""Get the absolute path to the file holding an object's bytes.
- ``file_url`` is an absolute or relative file:// url as s... |
Return the version currently running on a GMN instance.
(is_gmn, version_or_error)
def get_gmn_version(base_url):
"""Return the version currently running on a GMN instance.
(is_gmn, version_or_error)
"""
home_url = d1_common.url.joinPathElements(base_url, 'home')
try:
response = requ... |
Extract a set of authenticated subjects from a DataONE SubjectInfo.
- See subject_info_tree for details.
Args:
subject_info_xml : str
A SubjectInfo XML document.
primary_str : str
A DataONE subject, typically a DataONE compliant serialization of the DN of
t... |
Deserialize SubjectInfo XML doc to native object.
Args:
subject_info_xml: str
SubjectInfo XML doc
Returns:
SubjectInfo PyXB object
def deserialize_subject_info(subject_info_xml):
"""Deserialize SubjectInfo XML doc to native object.
Args:
subject_info_xml: str
... |
Convert the flat, self referential lists in the SubjectInfo to a tree structure.
Args:
subject_info_pyxb: SubjectInfo PyXB object
authn_subj: str
The authenticated subject that becomes the root subject in the tree of
subjects built from the SubjectInfo.
Only su... |
Trim empty leaf nodes from the tree.
- To simplify the tree conversion, empty nodes are added before it is known if they
will contain items that connect back to the authenticated subject. If there are
no connections, the nodes remain empty, which causes them to be removed here.
- Removing a leaf n... |
Add a child node.
def add_child(self, label_str, type_str):
"""Add a child node."""
child_node = SubjectInfoNode(label_str, type_str)
child_node.parent = self
self.child_list.append(child_node)
return child_node |
Get path from root to this node.
Args:
sep: str
One or more characters to insert between each element in the path.
Defaults to "/" on Unix and "\" on Windows.
type_str:
SUBJECT_NODE_TAG, TYPE_NODE_TAG or None. If set, only include
... |
Get paths for all leaf nodes for the tree rooted at this node.
Args:
sep: str
One or more characters to insert between each element in the path.
Defaults to "/" on Unix and "\" on Windows.
type_str:
SUBJECT_NODE_TAG, TYPE_NODE_TAG or None... |
Get list of the labels of the nodes leading up to this node from the root.
Args:
type_str:
SUBJECT_NODE_TAG, TYPE_NODE_TAG or None. If set, only include
information from nodes of that type.
Returns:
list of str: The labels of the nodes leading up... |
Get a set of label_str for the tree rooted at this node.
Args:
type_str:
SUBJECT_NODE_TAG, TYPE_NODE_TAG or None. If set, only include
information from nodes of that type.
Returns:
set: The labels of the nodes leading up to this node from the roo... |
Call when about to start processing a new type of task, typically just before
entering a loop that processes many task of the given type.
Args:
task_type_str (str):
The name of the task, used as a dict key and printed in the progress
updates.
tot... |
Call when processing of all tasks of the given type is completed, typically
just after exiting a loop that processes many tasks of the given type.
Progress messages logged at intervals will typically not include the final entry
which shows that processing is 100% complete, so a final progress m... |
Call when processing is about to start on a single task of the given task
type, typically at the top inside of the loop that processes the tasks.
Args:
task_type_str (str):
The name of the task, used as a dict key and printed in the progress
updates.
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.