text
stringlengths
18
773k
def to_internal_value(self, data): """Format the internal value.""" # When setting the contributor, it may be passed as an integer. if isinstance(data, dict) and isinstance(data.get('id', None), int): data = data['id'] elif isinstance(data, int): pass else...
def extract_descriptor(self, obj): """Extract data from the descriptor.""" descriptor = [] def flatten(current): """Flatten descriptor.""" if isinstance(current, dict): for key in current: flatten(current[key]) elif isinsta...
def _serialize_items(self, serializer, kind, items): """Return serialized items or list of ids, depending on `hydrate_XXX` query param.""" if self.request and self.request.query_params.get('hydrate_{}'.format(kind), False): serializer = serializer(items, many=True, read_only=True) ...
def get_entity_names(self, data): """Return serialized list of entity names on data that user has `view` permission on.""" entities = self._filter_queryset('view_entity', data.entity_set.all()) return list(entities.values_list('name', flat=True))
def get_collections(self, data): """Return serialized list of collection objects on data that user has `view` permission on.""" collections = self._filter_queryset('view_collection', data.collection_set.all()) from .collection import CollectionSerializer class CollectionWithoutDataSeri...
def get_entities(self, data): """Return serialized list of entity objects on data that user has `view` permission on.""" entities = self._filter_queryset('view_entity', data.entity_set.all()) from .entity import EntitySerializer class EntityWithoutDataSerializer(WithoutDataSerializerMi...
def get_fields(self): """Dynamically adapt fields based on the current request.""" fields = super(DataSerializer, self).get_fields() # Hide collections/entities fields on list views as fetching them may be expensive. if self.parent is not None: del fields['collections'] ...
def handle(self, *args, **options): """Handle command list_docker_images.""" verbosity = int(options.get('verbosity')) # Check that the specified output format is valid if options['format'] != 'plain' and options['format'] != 'yaml': raise CommandError("Unknown output format...
def create(self, request, *args, **kwargs): """Create a resource.""" collections = request.data.get('collections', []) # check that user has permissions on all collections that Data # object will be added to for collection_id in collections: try: coll...
def get_or_create(self, request, *args, **kwargs): """Get ``Data`` object if similar already exists, otherwise create it.""" kwargs['get_or_create'] = True return self.create(request, *args, **kwargs)
def perform_get_or_create(self, request, *args, **kwargs): """Perform "get_or_create" - return existing object if found.""" serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) process = serializer.validated_data.get('process') process_inp...
def perform_create(self, serializer): """Create a resource.""" process = serializer.validated_data.get('process') if not process.is_active: raise exceptions.ParseError( 'Process retired (id: {}, slug: {}/{}).'.format(process.id, process.slug, process.version) ...
def ready(self): """Called once per Django process instance. If the filesystem setup fails or if an error is found in settings.py, django.core.exceptions.ImproperlyConfigured is raised, causing Django not to launch the main GMN app. """ # Stop the startup code from runn...
def _assert_dirs_exist(self, setting_name): """Check that the dirs leading up to the given file path exist. Does not check if the file exists. """ v = self._get_setting(setting_name) if (not os.path.isdir(os.path.split(v)[0])) or os.path.isdir(v): self.raise_config_...
def _warn_unsafe_for_prod(self): """Warn on settings that are not safe for production.""" safe_settings_list = [ ('DEBUG', False), ('DEBUG_GMN', False), ('STAND_ALONE', False), ('DATABASES.default.ATOMIC_REQUESTS', True), ('SECRET_KEY', '<Do no...
def _get_setting(self, setting_dotted_name, default=None): """Return the value of a potentially nested dict setting. E.g., 'DATABASES.default.NAME """ name_list = setting_dotted_name.split('.') setting_obj = getattr(django.conf.settings, name_list[0], default) # if len(...
def _refresh_connection(self): """Refresh connection to Elasticsearch when worker is started. File descriptors (sockets) can be shared between multiple threads. If same connection is used by multiple threads at the same time, this can cause timeouts in some of the pushes. So con...
def generate_id(self, obj): """Generate unique document id for ElasticSearch.""" object_type = type(obj).__name__.lower() return '{}_{}'.format(object_type, self.get_object_id(obj))
def process_object(self, obj): """Process current object and push it to the ElasticSearch.""" document = self.document_class(meta={'id': self.generate_id(obj)}) for field in document._doc_type.mapping: # pylint: disable=protected-access if field in ['users_with_permissions', 'group...
def create_mapping(self): """Create the mappings in elasticsearch.""" try: self.document_class.init() self._mapping_created = True except IllegalOperation as error: if error.args[0].startswith('You cannot update analysis configuration'): # Igno...
def build(self, obj=None, queryset=None, push=True): """Build indexes.""" if obj is not None and queryset is not None: raise ValueError( "Only one of 'obj' and 'queryset' parameters can be passed to the build method." ) if obj is not None: if ...
def _build(self, obj=None, queryset=None, push=True): """Build indexes.""" logger.debug("Building '%s' Elasticsearch index...", self.__class__.__name__) if obj is not None: build_list = [obj] elif queryset is not None: build_list = self.queryset.intersection(que...
def push(self): """Push built documents to ElasticSearch.""" self._refresh_connection() # Check if we need to update mappings as this needs to be done # before we push anything to the Elasticsearch server. # This must be done even if the queue is empty, as otherwise ES #...
def destroy(self): """Destroy an index.""" self._refresh_connection() self.push_queue = [] index_name = self.document_class()._get_index() # pylint: disable=protected-access connections.get_connection().indices.delete(index_name, ignore=404) self._mapping_created = Fal...
def get_permissions(self, obj): """Return users and groups with ``view`` permission on the current object. Return a dict with two keys - ``users`` and ``groups`` - which contain list of ids of users/groups with ``view`` permission. """ # TODO: Optimize this for bulk running ...
def remove_object(self, obj): """Remove current object from the ElasticSearch.""" obj_id = self.generate_id(obj) es_obj = self.document_class.get(obj_id, ignore=[404]) # Object may not exist in this index. if es_obj: es_obj.delete(refresh=True)
def generate_pyxb_binding(self, args): """Args: args: """ pyxbgen_args = [] pyxbgen_args.append('--schema-root=\'{}\''.format(self.schema_dir)) pyxbgen_args.append('--binding-root=\'{}\''.format(self.binding_dir)) pyxbgen_args.append( '--schema-strip...
def run_pyxbgen(self, args): """Args: args: """ cmd = 'pyxbgen {}'.format(' '.join(args)) print(cmd) os.system(cmd)
def generate_version_file(self, schema_filename, binding_filename): """Given a DataONE schema, generates a file that contains version information about the schema.""" version_filename = binding_filename + '_version.txt' version_path = os.path.join(self.binding_dir, version_filename) ...
def write_version_file(self, version_file_path, tstamp, svnpath, svnrev, version): """Args: version_file_path: tstamp: svnpath: svnrev: version: """ txt = """# This file is automatically generated. Manual edits will be erased. # When this file was generated TIMESTAMP="{}" # Path of t...
def updateSystemMetadataResponse(self, pid, sysmeta_pyxb, vendorSpecific=None): """MNStorage.updateSystemMetadata(session, pid, sysmeta) → boolean http://jenkins-1.dataone.org/documentation/unstable/API-Documentation- development/apis/MN_APIs.html#MNStorage.updateSystemMetadata. Args: ...
def set_data_location(apps, schema_editor): """Create DataLocation for each Data.""" Data = apps.get_model('flow', 'Data') DataLocation = apps.get_model('flow', 'DataLocation') for data in Data.objects.all(): if os.path.isdir(os.path.join(settings.FLOW_EXECUTOR['DATA_DIR'], str(data.id))): ...
def _loadMore(self, start=0, trys=0, validation=True): """Retrieves the next page of results.""" self._log.debug("Loading page starting from %d" % start) self._czero = start self._pageoffs = 0 try: pyxb.RequireValidWhenParsing(validation) self._object_list...
def parse_mime_type(mime_type): """Carves up a mime-type and returns a tuple of the (type, subtype, params) where 'params' is a dictionary of all the parameters for the media range. For example, the media range 'application/xhtml;q=0.5' would get parsed into: ('application', 'xhtml', {'q', '0.5'}) ...
def best_match(supported, header): """Takes a list of supported mime-types and finds the best match for all the media- ranges listed in header. The value of header must be a string that conforms to the format of the HTTP Accept: header. The value of 'supported' is a list of mime-types. >>> best_match([...
def _delete_chunked(queryset, chunk_size=500): """Chunked delete, which should be used if deleting many objects. The reason why this method is needed is that deleting a lot of Data objects requires Django to fetch all of them into memory (fast path is not used) and this causes huge memo...
def duplicate(self, contributor=None): """Duplicate (make a copy) ``Data`` objects. :param contributor: Duplication user """ bundle = [ {'original': data, 'copy': data.duplicate(contributor=contributor)} for data in self ] bundle = rewire_inputs(...
def save_storage(self, instance, schema): """Save basic:json values to a Storage collection.""" for field_schema, fields in iterate_fields(instance, schema): name = field_schema['name'] value = fields[name] if field_schema.get('type', '').startswith('basic:json:'): ...
def resolve_secrets(self): """Retrieve handles for all basic:secret: fields on input. The process must have the ``secrets`` resource requirement specified in order to access any secrets. Otherwise this method will raise a ``PermissionDenied`` exception. :return: A dictionary of...
def save_dependencies(self, instance, schema): """Save data: and list:data: references as parents.""" def add_dependency(value): """Add parent Data dependency.""" try: DataDependency.objects.update_or_create( parent=Data.objects.get(pk=value), ...
def create_entity(self): """Create entity if `flow_collection` is defined in process. Following rules applies for adding `Data` object to `Entity`: * Only add `Data object` to `Entity` if process has defined `flow_collection` field * Add object to existing `Entity`, if all paren...
def save(self, render_name=False, *args, **kwargs): # pylint: disable=keyword-arg-before-vararg """Save the data model.""" if self.name != self._original_name: self.named_by_user = True create = self.pk is None if create: fill_with_defaults(self.input, self.proc...
def delete(self, *args, **kwargs): """Delete the data model.""" # Store ids in memory as relations are also deleted with the Data object. storage_ids = list(self.storages.values_list('pk', flat=True)) # pylint: disable=no-member super().delete(*args, **kwargs) Storage.objects....
def duplicate(self, contributor=None): """Duplicate (make a copy).""" if self.status not in [self.STATUS_DONE, self.STATUS_ERROR]: raise ValidationError('Data object must have done or error status to be duplicated') duplicate = Data.objects.get(id=self.id) duplicate.pk = Non...
def _render_name(self): """Render data name. The rendering is based on name template (`process.data_name`) and input context. """ if not self.process.data_name or self.named_by_user: # pylint: disable=no-member return inputs = copy.deepcopy(self.input) ...
def get_path(self, prefix=None, filename=None): """Compose data location path.""" prefix = prefix or settings.FLOW_EXECUTOR['DATA_DIR'] path = os.path.join(prefix, self.subpath) if filename: path = os.path.join(path, filename) return path
def get_runtime_path(self, filename=None): """Compose data runtime location path.""" return self.get_path(prefix=settings.FLOW_EXECUTOR['RUNTIME_DIR'], filename=filename)
def get_data(self, entity): """Return serialized list of data objects on entity that user has `view` permission on.""" data = self._filter_queryset('view_data', entity.data.all()) return self._serialize_data(data)
def validate(self): """Validate process descriptor.""" required_fields = ('slug', 'name', 'process_type', 'version') for field in required_fields: if getattr(self.metadata, field, None) is None: raise ValidationError("process '{}' is missing required meta attribute: {...
def to_schema(self): """Return process schema for this process.""" process_type = self.metadata.process_type if not process_type.endswith(':'): process_type = '{}:'.format(process_type) schema = { 'slug': self.metadata.slug, 'name': self.metadata.name...
def post_register_hook(self, verbosity=1): """Pull Docker images needed by processes after registering.""" if not getattr(settings, 'FLOW_DOCKER_DONT_PULL', False): call_command('list_docker_images', pull=True, verbosity=verbosity)
def resolve_data_path(self, data=None, filename=None): """Resolve data path for use with the executor. :param data: Data object instance :param filename: Filename to resolve :return: Resolved filename, which can be used to access the given data file in programs executed usin...
def resolve_upload_path(self, filename=None): """Resolve upload path for use with the executor. :param filename: Filename to resolve :return: Resolved filename, which can be used to access the given uploaded file in programs executed using this executor """ ...
def are_equal(a_dt, b_dt, round_sec=1): """Determine if two datetimes are equal with fuzz factor. A naive datetime (no timezone information) is assumed to be in in UTC. Args: a_dt: datetime Timestamp to compare. b_dt: datetime Timestamp to compare. round_sec: int or flo...
def http_datetime_str_from_dt(dt): """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 ...
def dt_from_http_datetime_str(http_full_datetime): """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 ; ...
def normalize_datetime_to_utc(dt): """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....
def cast_naive_datetime_to_tz(dt, tz=UTC()): """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: ...
def round_to_nearest(dt, n_round_sec=1.0): """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 ...
def submit(self, data, runtime_dir, argv): """Run process with SLURM. For details, see :meth:`~resolwe.flow.managers.workload_connectors.base.BaseConnector.submit`. """ limits = data.process.get_resource_limits() logger.debug(__( "Connector '{}' running for D...
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 fn == paths[i]: ...
def location_purge(location_id, delete=False, verbosity=0): """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 unreference...
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: logger.info("No data locations")
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.count())) for storage...
def purge_all(delete=False, verbosity=0): """Purge all data locations.""" _location_purge_all(delete, verbosity) _storage_purge_all(delete, verbosity)
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
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 {}".format(self.choices.__name__)) ...
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 ex: # TODO: Handle err...
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: if isinstance(node, ast.ClassDef): field_gr...
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 isinstance(base, ast.Name) ...
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) return visitor.processes
def get_permissions_class(permissions_name=None): """Load and cache permissions class. If ``permissions_name`` is not given, it defaults to permissions class set in Django ``FLOW_API['PERMISSIONS']`` setting. """ def load_permissions(permissions_name): """Look for a fully qualified flow per...
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: # Attempt to ...
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 = d1_common.xml.get_opt_val(sysmeta_pyxb, 'identifier') sid = d1_common.xml.get_opt_val(sysmeta_pyxb, 'seriesId') obsoletes...
def topological_sort(unsorted_dict): """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 ...
def get_pids_in_revision_chain(client, did): """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 sam...
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.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter ) parser.add_argument("path", na...
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
def unwrap(s, node_indent): """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_li...
def wrap(indent_int, unwrap_str): """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. """ with io.StringIO() as str_buf:...
def createSimpleResourceMap(ore_pid, scimeta_pid, sciobj_pid_list): """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...
def createResourceMapFromStream(in_stream, base_url=d1_common.const.URL_DATAONE_ROOT): """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 resourc...
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.const.ORE_NAMESPACE_DICT[k]) # Cr...
def serialize_to_transport(self, doc_format="xml", *args, **kwargs): """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...
def serialize_to_display(self, doc_format="pretty-xml", *args, **kwargs): """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``. ...
def deserialize(self, *args, **kwargs): """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. ...
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]
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 = [o for o in self.subjects(predicate=DCTERMS.identifier, object=opid)] return res[0]
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) return except IndexError: pass #...
def setDocuments(self, documenting_pid, documented_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 ...
def setDocumentedBy(self, documented_pid, documenting_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: s...
def addDataDocuments(self, scidata_pid_list, scimeta_pid=None): """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 D...
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.objects(predicate=DCTERMS.identifier, subject=ore)][ ...
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]
def getSubjectObjectsByPredicate(self, predicate): """ 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 :...
def parseDoc(self, doc_str, format="xml"): """Parse a OAI-ORE Resource Maps document. See Also: ``rdflib.ConjunctiveGraph.parse`` for documentation on arguments. """ self.parse(data=doc_str, format=format) self._ore_initialized = True return self
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_common.url.encodePathElement(pid), )
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') as curl_f, open( './hash_check/md5.txt', 'w' ) as md5_f, o...
def formfield(self, **kwargs): """ :returns: A :class:`~django.forms.FloatField` with ``max_value`` 90 and ``min_value`` -90. """ kwargs.update({ 'max_value': 90, 'min_value': -90, }) return super(LatitudeField, self).formfield(**kwargs...
def formfield(self, **kwargs): """ :returns: A :class:`~django.forms.FloatField` with ``max_value`` 180 and ``min_value`` -180. """ kwargs.update({ 'max_value': 180, 'min_value': -180, }) return super(LongitudeField, self).formfield(**k...