text
stringlengths
81
112k
Connect signals needed for dependency updates. Pre- and post-delete signals have to be handled separately, as: * in the pre-delete signal we have the information which objects to rebuild, but affected relations are still presented, so rebuild would reflect in the wrong (outda...
Connect signals needed for dependency updates. def connect(self, index): """Connect signals needed for dependency updates.""" # Determine which model is the target model as either side of the relation # may be passed as `field`. if index.object_type == self.field.rel.model: ...
Determine if dependent object should be processed. def _filter(self, objects, **kwargs): """Determine if dependent object should be processed.""" for obj in objects: if self.filter(obj, **kwargs) is False: return False return True
Prepare arguments for rebuilding indices. def _get_build_kwargs(self, obj, pk_set=None, action=None, update_fields=None, reverse=None, **kwargs): """Prepare arguments for rebuilding indices.""" if action is None: # Check filter before rebuilding index. if not self._filter([obj],...
Render the queryset of influenced objects and cache it. def process_predelete(self, obj, pk_set=None, action=None, update_fields=None, **kwargs): """Render the queryset of influenced objects and cache it.""" build_kwargs = self._get_build_kwargs(obj, pk_set, action, update_fields, **kwargs) sel...
Recreate queryset from the index and rebuild the index. def process_delete(self, obj, pk_set=None, action=None, update_fields=None, **kwargs): """Recreate queryset from the index and rebuild the index.""" build_kwargs = self.delete_cache.take(obj) if build_kwargs: self.index.build(...
Process signals from dependencies. Remove signal is processed in two parts. For details see: :func:`~Dependency.connect` def process_m2m(self, obj, pk_set=None, action=None, update_fields=None, cache_key=None, **kwargs): """Process signals from dependencies. Remove signal is processed...
Process custom M2M through model actions. def _process_m2m_through(self, obj, action): """Process custom M2M through model actions.""" source = getattr(obj, self.field.rel.field.m2m_field_name()) target = getattr(obj, self.field.rel.field.m2m_reverse_field_name()) pk_set = set() ...
Process M2M post save for custom through model. def process_m2m_through_save(self, obj, created=False, **kwargs): """Process M2M post save for custom through model.""" # We are only interested in signals that establish relations. if not created: return self._process_m2m_thr...
Process signals from dependencies. def process(self, obj, pk_set=None, action=None, update_fields=None, **kwargs): """Process signals from dependencies.""" build_kwargs = self._get_build_kwargs(obj, pk_set, action, update_fields, **kwargs) if build_kwargs: self.index.build(**build_...
Create signals for building indexes. def _connect_signal(self, index): """Create signals for building indexes.""" post_save_signal = ElasticSignal(index, 'build') post_save_signal.connect(post_save, sender=index.object_type) self.signals.append(post_save_signal) post_delete_sig...
Register signals for all indexes. def register_signals(self): """Register signals for all indexes.""" for index in self.indexes: if index.object_type: self._connect_signal(index)
Save list of index builders into ``_index_builders``. def discover_indexes(self): """Save list of index builders into ``_index_builders``.""" self.indexes = [] for app_config in apps.get_app_configs(): indexes_path = '{}.elastic_indexes'.format(app_config.name) try: ...
Trigger building of the indexes. Support passing ``obj`` parameter to the indexes, so we can trigger build only for one object. def build(self, obj=None, queryset=None, push=True): """Trigger building of the indexes. Support passing ``obj`` parameter to the indexes, so we can ...
Push built documents to ElasticSearch. If ``index`` is specified, only that index will be pushed. def push(self, index=None): """Push built documents to ElasticSearch. If ``index`` is specified, only that index will be pushed. """ for ind in self.indexes: if index ...
Delete all entries from ElasticSearch. def delete(self, skip_mapping=False): """Delete all entries from ElasticSearch.""" for index in self.indexes: index.destroy() if not skip_mapping: index.create_mapping()
Delete all indexes from Elasticsearch and index builder. def destroy(self): """Delete all indexes from Elasticsearch and index builder.""" self.unregister_signals() for index in self.indexes: index.destroy() self.indexes = []
r"""Set the initial values for parameters and Wilson coefficients at the scale `scale_in`. def _set_initial(self, C_in, scale_in): r"""Set the initial values for parameters and Wilson coefficients at the scale `scale_in`.""" self.C_in = C_in self.scale_in = scale_in
Load the initial values for Wilson coefficients from a wcxf.WC instance. Parameters: - `get_smpar`: boolean, optional, defaults to True. If True, an attempt is made to determine the SM parameters from the requirement of reproducing the correct SM masses and mixings at the e...
Return the Wilson coefficients `C_out` as a wcxf.WC instance. Note that the Wilson coefficients are rotated into the Warsaw basis as defined in WCxf, i.e. to the basis where the down-type and charged lepton mass matrices are diagonal. def _to_wcxf(self, C_out, scale_out): """Return the...
Solve the SMEFT RGEs from the initial scale to `scale_out`. Returns a dictionary with parameters and Wilson coefficients at `scale_out`. Additional keyword arguments will be passed to the ODE solver `scipy.integrate.odeint`. def _rgevolve(self, scale_out, **kwargs): """Solve the SMEFT R...
Compute the leading logarithmic approximation to the solution of the SMEFT RGEs from the initial scale to `scale_out`. Returns a dictionary with parameters and Wilson coefficients. Much faster but less precise that `rgevolve`. def _rgevolve_leadinglog(self, scale_out): """Compute the le...
Get the SM parameters at the EW scale, using an estimate `C_out` of the Wilson coefficients at that scale, and run them to the input scale. def _run_sm_scale_in(self, C_out, scale_sm=91.1876): """Get the SM parameters at the EW scale, using an estimate `C_out` of the Wilson coefficients...
Compute the SM MS-bar parameters at the electroweak scale. This method can be used to validate the accuracy of the iterative extraction of SM parameters. If successful, the values returned by this method should agree with the values in the dictionary `wilson.run.smeft.smpar.p`. def get...
Get an estimate of the SM parameters at the input scale by running them from the EW scale using constant values for the Wilson coefficients (corresponding to their leading log approximated values at the EW scale). Note that this is not guaranteed to work and will fail if some of the ...
Return the Wilson coefficients (as wcxf.WC instance) evolved to the scale `scale`. Parameters: - `scale`: scale in GeV - accuracy: whether to use the numerical solution to the RGE ('integrate', the default, slow but precise) or the leading logarithmic approximation ('l...
Return a continuous solution to the RGE as `RGsolution` instance. def run_continuous(self, scale): """Return a continuous solution to the RGE as `RGsolution` instance.""" if scale == self.scale_in: raise ValueError("The scale must be different from the input scale") elif scale < sel...
Deconstruct method. def deconstruct(self): """Deconstruct method.""" name, path, args, kwargs = super().deconstruct() if self.populate_from is not None: kwargs['populate_from'] = self.populate_from if self.unique_with != (): kwargs['unique_with'] = self.unique_...
Return SQL filter for filtering by fields in ``unique_with`` attribute. Filter is returned as tuple of two elements where first one is placeholder which is safe to insert into SQL query and second one may include potentially dangerous values and must be passed to SQL query in ``params``...
Get the value from ``populate_from`` attribute. def _get_populate_from_value(self, instance): """Get the value from ``populate_from`` attribute.""" if hasattr(self.populate_from, '__call__'): # ResolweSlugField(populate_from=lambda instance: ...) return self.populate_from(instan...
Ensure slug uniqunes before save. def pre_save(self, instance, add): """Ensure slug uniqunes before save.""" slug = self.value_from_object(instance) # We don't want to change slug defined by user. predefined_slug = bool(slug) if not slug and self.populate_from: slu...
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...
Recursively evaluate expressions in a dictionary of values. def _evaluate_expressions(self, expression_engine, step_id, values, context): """Recursively evaluate expressions in a dictionary of values.""" if expression_engine is None: return values processed = {} for name, v...
Evaluate the code needed to compute a given Data object. def evaluate(self, data): """Evaluate the code needed to compute a given Data object.""" expression_engine = data.process.requirements.get('expression-engine', None) if expression_engine is not None: expression_engine = self.g...
Create a connection to the Redis server. async def init(): """Create a connection to the Redis server.""" global redis_conn # pylint: disable=global-statement,invalid-name conn = await aioredis.create_connection( 'redis://{}:{}'.format( SETTINGS.get('FLOW_EXECUTOR', {}).get('REDIS_CONN...
Send a properly formatted command to the manager. :param cmd: The command to send (:class:`str`). :param expect_reply: If ``True``, wait for the manager to reply with an acknowledgement packet. :param extra_fields: A dictionary of extra information that's merged into the packet body (i.e. n...
Get list of dicts where each dict holds values from one SciObj. Args: field_list: list of str List of field names for which to return values. Must be strings from FIELD_NAME_TO_generate_dict.keys(). If None, return all fields. filter_arg_dict: dict ...
Get list of dicts where each dict holds values from one SciObj. Args: field_list: list of str List of field names for which to return values. Must be strings from FIELD_NAME_TO_generate_dict.keys(). If None, return all fields. filter_arg_dict: dict ...
raise d1_common.types.exceptions.InvalidRequest() if ``field_list`` contains any invalid field names. A list of the invalid fields is included in the exception. - Implicitly called by ``extract_values()``. def assert_invalid_field_list(field_list): """raise d1_common.types.exceptions.InvalidRequest() if `...
Add annotations to the query to retrieve values required by field value generate functions. def _annotate_query(query, generate_dict): """Add annotations to the query to retrieve values required by field value generate functions.""" annotate_key_list = [] for field_name, annotate_dict in generate_d...
Create a dict where the keys are the requested field names, from the values returned by Django. def _value_list_to_sciobj_dict( sciobj_value_list, lookup_list, lookup_dict, generate_dict ): """Create a dict where the keys are the requested field names, from the values returned by Django.""" sciobj...
Split the list of fields for which to extract values into lists by extraction methods. - Remove any duplicated field names. - Raises ValueError with list of any invalid field names in ``field_list``. def _split_field_list(field_list): """Split the list of fields for which to extract values into lists ...
Return the PyXB binding to use when handling a request. def dataoneTypes(request): """Return the PyXB binding to use when handling a request.""" if is_v1_api(request): return d1_common.types.dataoneTypes_v1_1 elif is_v2_api(request) or is_diag_api(request): return d1_common.types.dataoneTyp...
Parse a ISO 8601 date-time with optional timezone. - Return as datetime with timezone adjusted to UTC. - Return naive date-time set to UTC. def parse_and_normalize_url_date(date_str): """Parse a ISO 8601 date-time with optional timezone. - Return as datetime with timezone adjusted to UTC. - Retur...
Retrieve the specified document. def get(self, doc_id): """Retrieve the specified document.""" resp_dict = self._get_query(q='id:{}'.format(doc_id)) if resp_dict['response']['numFound'] > 0: return resp_dict['response']['docs'][0]
Retrieve a list of identifiers for documents matching the query. def get_ids(self, start=0, rows=1000, **query_dict): """Retrieve a list of identifiers for documents matching the query.""" resp_dict = self._get_query(start=start, rows=rows, **query_dict) return { 'matches': resp_dic...
Return the number of entries that match query. def count(self, **query_dict): """Return the number of entries that match query.""" param_dict = query_dict.copy() param_dict['count'] = 0 resp_dict = self._get_query(**param_dict) return resp_dict['response']['numFound']
Retrieve the unique values for a field, along with their usage counts. :param name: Name of field for which to retrieve values :type name: string :param sort: Sort the result :param maxvalues: Maximum number of values to retrieve. Default is -1, which causes retrieval of all...
Returns the minimum and maximum values of the specified field. This requires two search calls to the service, each requesting a single value of a single field. @param name(string) Name of the field @param q(string) Query identifying range of records for min and max values @param...
Generates a histogram of values from a string field. Output is: [[low, high, count, query], ... ]. Bin edges is determined by equal division of the fields. def field_alpha_histogram( self, name, n_bins=10, include_queries=True, **query_dict ): """Generates a histogram of values fro...
docs is a list of fields that are a dictionary of name:value for a record. def add_docs(self, docs): """docs is a list of fields that are a dictionary of name:value for a record.""" return self.query( 'solr', '<add>{}</add>'.format( ''.join([self._format_add(fiel...
Returns unicode(value) after trying to coerce it into the Solr field type. @param field_type(string) The Solr field type for the value @param value(any) The value that is to be represented as Unicode text. def _coerce_type(self, field_type, value): """Returns unicode(value) after trying to coe...
Returns the Solr type of the specified field name. Assumes the convention of dynamic fields using an underscore + type character code for the field name. def _get_solr_type(self, field): """Returns the Solr type of the specified field name. Assumes the convention of dynamic fields usi...
Perform a GET query against Solr and return the response as a Python dict. def _get_query(self, **query_dict): """Perform a GET query against Solr and return the response as a Python dict.""" param_dict = query_dict.copy() return self._send_query(do_post=False, **param_dict)
Perform a POST query against Solr and return the response as a Python dict. def _post_query(self, **query_dict): """Perform a POST query against Solr and return the response as a Python dict.""" param_dict = query_dict.copy() return self._send_query(do_post=True, **param_dict)
Perform a query against Solr and return the response as a Python dict. def _send_query(self, do_post=False, **query_dict): """Perform a query against Solr and return the response as a Python dict.""" # self._prepare_query_term() param_dict = query_dict.copy() param_dict.setdefault('wt',...
Prepare a query term for inclusion in a query. This escapes the term and if necessary, wraps the term in quotes. def _prepare_query_term(self, field, term): """Prepare a query term for inclusion in a query. This escapes the term and if necessary, wraps the term in quotes. """ ...
Escape a query term for inclusion in a query. - Also see: prepare_query_term(). def _escape_query_term(self, term): """Escape a query term for inclusion in a query. - Also see: prepare_query_term(). """ term = term.replace('\\', '\\\\') for c in RESERVED_CHAR_LIST: ...
Retrieves the next set of results from the service. def _next_page(self, offset): """Retrieves the next set of results from the service.""" self._log.debug("Iterator c_record={}".format(self.c_record)) page_size = self.page_size if (offset + page_size) > self.max_records: pa...
Retrieves the next set of results from the service. def _next_page(self, offset): """Retrieves the next set of results from the service.""" self._log.debug("Iterator c_record={}".format(self.c_record)) param_dict = self.query_dict.copy() param_dict.update( { ...
Migrate 'flow_collection' field to 'entity_type'. def migrate_flow_collection(apps, schema_editor): """Migrate 'flow_collection' field to 'entity_type'.""" Process = apps.get_model('flow', 'Process') DescriptorSchema = apps.get_model('flow', 'DescriptorSchema') for process in Process.objects.all(): ...
Map DataONE API version tag to PyXB binding. Given a DataONE API major version number, return PyXB binding that can serialize and deserialize DataONE XML docs of that version. Args: api_major, api_minor: str or int DataONE API major and minor version numbers. - If ``api_major`` is a...
Extract a DataONE API version tag from a MN or CN service endpoint URL. Args: url : str Service endpoint URL. E.g.: ``https://mn.example.org/path/v2/object/pid``. Returns: str : Valid version tags are currently ``v1`` or ``v2``. def extract_version_tag_from_url(url): """Extract a Data...
Convert a API v2 XML doc to v1 XML doc. Removes elements that are only valid for v2 and changes namespace to v1. If doc is already v1, it is returned unchanged. Args: xml_str : str API v2 XML doc. E.g.: ``SystemMetadata v2``. Returns: str : API v1 XML doc. E.g.: ``SystemMetadata ...
Convert a API v1 XML doc to v2 XML doc. All v1 elements are valid for v2, so only changes namespace. Args: xml_str : str API v1 XML doc. E.g.: ``SystemMetadata v1``. Returns: str : API v2 XML doc. E.g.: ``SystemMetadata v2``. def str_to_v2_str(xml_str): """Convert a API v1 XML do...
Args: xml_str : str DataONE API XML doc. Returns: bool: **True** if XML doc is well formed. def str_is_well_formed(xml_str): """ Args: xml_str : str DataONE API XML doc. Returns: bool: **True** if XML doc is well formed. """ try: str_to_etree(xml_str) except xm...
Args: pyxb_obj : PyXB object PyXB object holding an unknown type. Returns: bool: **True** if ``pyxb_obj`` holds an API v1 type. def pyxb_is_v1(pyxb_obj): """ Args: pyxb_obj : PyXB object PyXB object holding an unknown type. Returns: bool: **True** if ``pyxb_obj`` holds an API v1...
Args: pyxb_obj : PyXB object PyXB object holding an unknown type. Returns: bool: **True** if ``pyxb_obj`` holds an API v2 type. def pyxb_is_v2(pyxb_obj): """ Args: pyxb_obj : PyXB object PyXB object holding an unknown type. Returns: bool: **True** if ``pyxb_obj`` holds an API v2...
Deserialize API XML doc to an ElementTree. Args: xml_str: bytes DataONE API XML doc encoding: str Decoder to use when converting the XML doc ``bytes`` to a Unicode str. Returns: ElementTree: Matching the API version of the XML doc. def str_to_etree(xml_str, encoding='utf-8'...
Convert XML tag names with namespace on the form ``{namespace}tag`` to form ``prefix:tag``. Args: tag_str: str Tag name with namespace. E.g.: ``{http://www.openarchives.org/ore/terms/}ResourceMap``. ns_reverse_dict : dict A dictionary of namespace to prefix to use for the c...
In-place change the namespace of elements in an ElementTree. Args: etree_obj: ElementTree ns_str : str The namespace to set. E.g.: ``http://ns.dataone.org/service/types/v1``. def etree_replace_namespace(etree_obj, ns_str): """In-place change the namespace of elements in an ElementTree. ...
In-place remove elements and attributes that are only valid in v2 types. Args: etree_obj: ElementTree ElementTree holding one of the DataONE API types that changed between v1 and v2. def strip_v2_elements(etree_obj): """In-place remove elements and attributes that are only valid in v2 types. Ar...
In-place remove elements and attributes that are only valid in v2 types from v1 System Metadata. Args: etree_obj: ElementTree ElementTree holding a v1 SystemMetadata. def strip_system_metadata(etree_obj): """In-place remove elements and attributes that are only valid in v2 types from v1 System M...
GMN handles replicas differently from native objects, with the main differences being related to handling of restrictions related to revision chains and SIDs. So this create sequence differs significantly from the regular one that is accessed through MNStorage.create(). def _create_rep...
Import only the Science Objects specified by a text file. The file must be UTF-8 encoded and contain one PIDs or SIDs per line. async def restricted_import(self, async_client, node_type): """Import only the Science Objects specified by a text file. The file must be UTF-8 encoded and contain o...
Import the SciObj at {pid}. If the SciObj is a Resource Map, also recursively import the aggregated objects. async def import_aggregated(self, async_client, pid): """Import the SciObj at {pid}. If the SciObj is a Resource Map, also recursively import the aggregated objects. """ ...
If object is proxied, return the proxy location URL. If object is local, return None. async def get_object_proxy_location(self, client, pid): """If object is proxied, return the proxy location URL. If object is local, return None. """ try: return (await client.des...
Create a dict of arguments that will be passed to listObjects(). If {node_type} is a CN, add filtering to include only objects from this GMN instance in the ObjectList returned by CNCore.listObjects(). def get_list_objects_arg_dict(self, node_type): """Create a dict of arguments that will be p...
Create a dict of arguments that will be passed to getLogRecords(). If {node_type} is a CN, add filtering to include only objects from this GMN instance in the ObjectList returned by CNCore.listObjects(). def get_log_records_arg_dict(self, node_type): """Create a dict of arguments that will be ...
Return True if node at {base_url} is a CN, False if it is an MN. Raise a DataONEException if it's not a functional CN or MN. async def is_cn(self, client): """Return True if node at {base_url} is a CN, False if it is an MN. Raise a DataONEException if it's not a functional CN or MN. ...
Determine if import source node is a CN or MN and which major version API to use. async def probe_node_type_major(self, client): """Determine if import source node is a CN or MN and which major version API to use.""" try: node_pyxb = await self.get_node_doc(client) e...
Search NodeList for Node that has {base_url}. Return matching Node or None def find_node(self, node_list_pyxb, base_url): """Search NodeList for Node that has {base_url}. Return matching Node or None """ for node_pyxb in node_list_pyxb.node: if node_pyxb.baseURL =...
When importing from a CN, ensure that the NodeID which the ObjectList will be filtered by is known to the CN. def assert_is_known_node_id(self, node_list_pyxb, node_id): """When importing from a CN, ensure that the NodeID which the ObjectList will be filtered by is known to the CN.""" n...
Find the highest API major version supported by node. def find_node_api_version(self, node_pyxb): """Find the highest API major version supported by node.""" max_major = 0 for s in node_pyxb.services.service: max_major = max(max_major, int(s.version[1:])) return max_major
Search NodeList for Node with {node_id}. Return matching Node or None def find_node_by_id(self, node_list_pyxb, node_id): """Search NodeList for Node with {node_id}. Return matching Node or None """ for node_pyxb in node_list_pyxb.node: # if node_pyxb.baseURL == b...
Run process executor. :param data_id: The id of the :class:`~resolwe.flow.models.Data` object to be processed. :param runtime_dir: The directory from which to run the executor. :param argv: The argument vector used to run the executor. :param verbosity: The logging verbosity level. def celery_...
Set the status of an object to archived. Preconditions: - The object with the pid is verified to exist. - The object is not a replica. - The object is not archived. def archive_sciobj(pid): """Set the status of an object to archived. Preconditions: - The object with the pid is verified to...
Create or update database representation of a System Metadata object and closely related internal state. - If ``sciobj_url`` is not passed on create, storage in the internal sciobj store is assumed - If ``sciobj_url`` is passed on create, it can reference a location in the internal sciobj store...
Create or update the database representation of the sysmeta_pyxb access policy. If called without an access policy, any existing permissions on the object are removed and the access policy for the rights holder is recreated. Preconditions: - Each subject has been verified to a valid DataONE account....
Args: parser: def add_arguments(self, parser): """Args: parser: """ parser.description = __doc__ parser.formatter_class = argparse.RawDescriptionHelpFormatter parser.add_argument("--debug", action="store_true", help="Debug level logging") parser.add_ar...
Args: *args: **opt: def handle(self, *args, **opt): """Args: *args: **opt: """ d1_gmn.app.management.commands.util.util.log_setup(opt["debug"]) logging.info( "Running management command: {}".format( __name__ ) #...
Args: log_record_pyxb: def _create_log_entry(self, log_record_pyxb): """Args: log_record_pyxb: """ event_log_model = d1_gmn.app.event_log.create_log_entry( d1_gmn.app.model_util.get_sci_model( d1_common.xml.get_req_val(log_record_pyxb.identifier) ...
Args: client: pid: def _download_source_sciobj_bytes_to_store(self, client, pid): """Args: client: pid: """ if d1_gmn.app.sciobj_store.is_existing_sciobj_file(pid): self._events.log_and_count( "Skipped download of existing sciobj bytes", 'pid="{}"'...
Args: dir_path: def _assert_path_is_dir(self, dir_path): """Args: dir_path: """ if not os.path.isdir(dir_path): raise django.core.management.base.CommandError( 'Invalid dir path. path="{}"'.format(dir_path) )
Deserialize a SubjectInfo XML file to a PyXB object. def deserialize_subject_info(subject_info_xml_path): """Deserialize a SubjectInfo XML file to a PyXB object.""" try: with open(subject_info_xml_path) as f: return d1_common.xml.deserialize(f.read()) except ValueError as e: rai...
Send a HEAD request. See requests.sessions.request for optional parameters. :returns: Response object def HEAD(self, rest_path_list, **kwargs): """Send a HEAD request. See requests.sessions.request for optional parameters. :returns: Response object """ kwargs.setdefault("allo...
Send a POST request with optional streaming multipart encoding. See requests.sessions.request for optional parameters. To post regular data, pass a string, iterator or generator as the ``data`` argument. To post a multipart stream, pass a dictionary of multipart elements as the ``fields`` argume...
Send a PUT request with optional streaming multipart encoding. See requests.sessions.request for optional parameters. See post() for parameters. :returns: Response object def PUT(self, rest_path_list, **kwargs): """Send a PUT request with optional streaming multipart encoding. See requ...
Get request as cURL command line for debugging. def get_curl_command_line(self, method, url, **kwargs): """Get request as cURL command line for debugging.""" if kwargs.get("query"): url = "{}?{}".format(url, d1_common.url.urlencode(kwargs["query"])) curl_list = ["curl"] if m...
Return a string containing a nicely formatted representation of the request and response objects for logging and debugging. - Note: Does not work if the request or response body is a MultipartEncoder object. def dump_request_and_response(self, response): """Return a string containing...