text
stringlengths
18
773k
def set_mn_controlled_values(request, sysmeta_pyxb, is_modification): """See the description of TRUST_CLIENT_* in settings.py.""" now_datetime = d1_common.date_time.utc_now() default_value_list = [ ('originMemberNode', django.conf.settings.NODE_IDENTIFIER, True), ('authoritativeMemberNode',...
def duplicate(self, contributor=None, inherit_collections=False): """Duplicate (make a copy) ``Entity`` objects. :param contributor: Duplication user :param inherit_collections: If ``True`` then duplicated entities will be added to collections the original entity is part...
def move_to_collection(self, source_collection, destination_collection): """Move entities from source to destination collection.""" for entity in self: entity.move_to_collection(source_collection, destination_collection)
def duplicate(self, contributor=None, inherit_collections=False): """Duplicate (make a copy).""" duplicate = Entity.objects.get(id=self.id) duplicate.pk = None duplicate.slug = None duplicate.name = 'Copy of {}'.format(self.name) duplicate.duplicated = now() if co...
def move_to_collection(self, source_collection, destination_collection): """Move entity from source to destination collection.""" # Remove from collection. self.collections.remove(source_collection) # pylint: disable=no-member source_collection.data.remove(*self.data.all()) # pylint: d...
def unquote(s): """unquote('abc%20def') -> 'abc def'.""" res = s.split('%') # fastpath if len(res) == 1: return s s = res[0] for item in res[1:]: try: s += _hextochr[item[:2]] + item[2:] except KeyError: s += '%' + item except UnicodeDecode...
def quote(s, unsafe='/'): """Pass in a dictionary that has unsafe characters as the keys, and the percent encoded value as the value.""" res = s.replace('%', '%25') for c in unsafe: res = res.replace(c, '%' + (hex(ord(c)).upper())[2:]) return res
def get_dependencies(self): """Return dependencies, which should trigger updates of this model.""" # pylint: disable=no-member return super().get_dependencies() + [ Data.collection_set, Data.entity_set, Data.parents, ]
def alpha_s(scale, f, alphasMZ=0.1185, loop=3): """3-loop computation of alpha_s for f flavours with initial condition alpha_s(MZ) = 0.1185""" if scale == MZ and f == 5: return alphasMZ # nothing to do _sane(scale, f) crd = rundec.CRunDec() if f == 5: return_value = crd.AlphasEx...
def m_b(mbmb, scale, f, alphasMZ=0.1185, loop=3): r"""Get running b quark mass in the MSbar scheme at the scale `scale` in the theory with `f` dynamical quark flavours starting from $m_b(m_b)$""" if scale == mbmb and f == 5: return mbmb # nothing to do _sane(scale, f) alphas_mb = alpha_s(mb...
def m_c(mcmc, scale, f, alphasMZ=0.1185, loop=3): r"""Get running c quark mass in the MSbar scheme at the scale `scale` in the theory with `f` dynamical quark flavours starting from $m_c(m_c)$""" if scale == mcmc: return mcmc # nothing to do _sane(scale, f) crd = rundec.CRunDec() alphas...
def m_s(ms2, scale, f, alphasMZ=0.1185, loop=3): r"""Get running s quark mass in the MSbar scheme at the scale `scale` in the theory with `f` dynamical quark flavours starting from $m_s(2 \,\text{GeV})$""" if scale == 2 and f == 3: return ms2 # nothing to do _sane(scale, f) crd = rundec.CRu...
def get_confirmation(self): """Get user confirmation to proceed.""" if self.clear: action = 'This will DELETE ALL FILES in this location!' else: action = 'This will overwrite existing files!' message = ( "\n" "You have requested to collect...
def clear_dir(self): """Delete contents of the directory on the given path.""" self.stdout.write("Deleting contents of '{}'.".format(self.destination_path)) for filename in os.listdir(self.destination_path): if os.path.isfile(filename) or os.path.islink(filename): os...
def change_path_prefix(self, path, old_prefix, new_prefix, app_name): """Change path prefix and include app name.""" relative_path = os.path.relpath(path, old_prefix) return os.path.join(new_prefix, app_name, relative_path)
def collect(self): """Get tools' locations and copy them to a single location.""" for app_name, tools_path in get_apps_tools().items(): self.stdout.write("Copying files from '{}'.".format(tools_path)) app_name = app_name.replace('.', '_') app_destination_path = os.p...
def handle(self, **options): """Collect tools.""" self.set_options(**options) os.makedirs(self.destination_path, exist_ok=True) if self.interactive and any(os.listdir(self.destination_path)): self.get_confirmation() if self.clear: self.clear_dir() ...
def get_data_checksum(proc_input, proc_slug, proc_version): """Compute checksum of processor inputs, name and version.""" checksum = hashlib.sha256() checksum.update(json.dumps(proc_input, sort_keys=True).encode('utf-8')) checksum.update(proc_slug.encode('utf-8')) checksum.update(str(proc_version).e...
def dict_dot(d, k, val=None, default=None): """Get or set value using a dot-notation key in a multilevel dict.""" if val is None and k == '': return d def set_default(dict_or_model, key, default_value): """Set default field value.""" if isinstance(dict_or_model, models.Model): ...
def get_apps_tools(): """Get applications' tools and their paths. Return a dict with application names as keys and paths to tools' directories as values. Applications without tools are omitted. """ tools_paths = {} for app_config in apps.get_app_configs(): proc_path = os.path.join(app_...
def rewire_inputs(data_list): """Rewire inputs of provided data objects. Input parameter is a list of original and copied data object model instances: ``[{'original': original, 'copy': copy}]``. This function finds which objects reference other objects (in the list) on the input and replaces origin...
def CreateFromDocument(xml_text, default_namespace=None, location_base=None): """Parse the given XML and use the document element to create a Python instance. @param xml_text An XML document. This should be data (Python 2 str or Python 3 bytes), or a text (Python 2 unicode or Python 3 str) in the L{py...
def CreateFromDOM(node, default_namespace=None): """Create a Python instance from the given DOM node. The node tag must correspond to an element declaration in this module. @deprecated: Forcing use of DOM interface is unnecessary; use L{CreateFromDocument}. """ if default_namespace is None: ...
def postloop(self): """Take care of any unfinished business. Despite the claims in the Cmd documentation, Cmd.postloop() is not a stub. """ cmd.Cmd.postloop(self) # Clean up command completion d1_cli.impl.util.print_info("Exiting...")
def precmd(self, line): """This method is called after the line has been input but before it has been interpreted. If you want to modify the input line before execution (for example, variable substitution) do it here. """ line = self.prefix + line self._history ...
def default(self, line): """Called on an input line when the command prefix is not recognized.""" args = self._split_args(line, 0, 99) d1_cli.impl.util.print_error("Unknown command: {}".format(args[0]))
def do_help(self, line): """Get help on commands "help" or "?" with no arguments displays a list_objects of commands for which help is available "help <command>" or "? <command>" gives help on <command> """ command, = self._split_args(line, 0, 1) if command is None: ...
def do_history(self, line): """history Display a list of commands that have been entered.""" self._split_args(line, 0, 0) for idx, item in enumerate(self._history): d1_cli.impl.util.print_info("{0: 3d} {1}".format(idx, item))
def do_exit(self, line): """exit Exit from the CLI.""" n_remaining_operations = len(self._command_processor.get_operation_queue()) if n_remaining_operations: d1_cli.impl.util.print_warn( """There are {} unperformed operations in the write operation queue. These will b...
def do_eof(self, line): """Exit on system EOF character.""" d1_cli.impl.util.print_info("") self.do_exit(line)
def do_set(self, line): """set [parameter [value]] set (without parameters): Display the value of all session variables. set <session variable>: Display the value of a single session variable. set <session variable> <value>: Set the value of a session variable. """ sess...
def do_load(self, line): """load [file] Load session variables from file load (without parameters): Load session from default file ~/.dataone_cli.conf load. <file>: Load session from specified file. """ config_file = self._split_args(line, 0, 1)[0] self._command_process...
def do_save(self, line): """save [config_file] Save session variables to file save (without parameters): Save session to default file ~/.dataone_cli.conf save. <file>: Save session to specified file. """ config_file = self._split_args(line, 0, 1)[0] self._command_proces...
def do_reset(self, line): """reset Set all session variables to their default values.""" self._split_args(line, 0, 0) self._command_processor.get_session().reset() self._print_info_if_verbose("Successfully reset session variables")
def do_allowaccess(self, line): """allowaccess <subject> [access-level] Set the access level for subject Access level is "read", "write" or "changePermission". Access level defaults to "read" if not specified. Special subjects: public: Any subject, authenticated and not authenticated ...
def do_denyaccess(self, line): """denyaccess <subject> Remove subject from access policy.""" subject, = self._split_args(line, 1, 0) self._command_processor.get_session().get_access_control().remove_allowed_subject( subject ) self._print_info_if_verbose( '...
def do_clearaccess(self, line): """clearaccess Remove all subjects from access policy Only the submitter will have access to the object.""" self._split_args(line, 0, 0) self._command_processor.get_session().get_access_control().clear() self._print_info_if_verbose("Removed all sub...
def do_allowrep(self, line): """allowrep Allow new objects to be replicated.""" self._split_args(line, 0, 0) self._command_processor.get_session().get_replication_policy().set_replication_allowed( True ) self._print_info_if_verbose("Set replication policy to allow rep...
def do_denyrep(self, line): """denyrep Prevent new objects from being replicated.""" self._split_args(line, 0, 0) self._command_processor.get_session().get_replication_policy().set_replication_allowed( False ) self._print_info_if_verbose("Set replication policy to den...
def do_preferrep(self, line): """preferrep <member node> [member node ...] Add one or more preferred Member Nodes to replication policy.""" mns = self._split_args(line, 1, -1) self._command_processor.get_session().get_replication_policy().add_preferred( mns ) ...
def do_blockrep(self, line): """blockrep <member node> [member node ...] Add one or more blocked Member Node to replication policy.""" mns = self._split_args(line, 1, -1) self._command_processor.get_session().get_replication_policy().add_blocked(mns) self._print_info_if_verbose( ...
def do_removerep(self, line): """removerep <member node> [member node ...] Remove one or more Member Nodes from replication policy.""" mns = self._split_args(line, 1, -1) self._command_processor.get_session().get_replication_policy().repremove(mns) self._print_info_if_verbose( ...
def do_numberrep(self, line): """numberrep <number of replicas> Set preferred number of replicas for new objects If the preferred number of replicas is set to zero, replication is also disallowed.""" n_replicas = self._split_args(line, 1, 0)[0] self._command_processor.get_session...
def do_clearrep(self, line): """clearrep Set the replication policy to default. The default replication policy has no preferred or blocked member nodes, allows replication and sets the preferred number of replicas to 3. """ self._split_args(line, 0, 0) self._command_pro...
def do_get(self, line): """get <identifier> <file> Get an object from a Member Node. The object is saved to <file>. """ pid, output_file = self._split_args(line, 2, 0) self._command_processor.science_object_get(pid, output_file) self._print_info_if_verbose( ...
def do_meta(self, line): """meta <identifier> [file] Get the System Metadata that is associated with a Science Object. If the metadata is not on the Coordinating Node, the Member Node is checked. Provide ``file`` to save the System Metada to disk instead of displaying it. """ ...
def do_list(self, line): """list [path] Retrieve a list of available Science Data Objects from Member Node The response is filtered by the from-date, to-date, search, start and count session variables. See also: search """ path = self._split_args(line, 0, 1, pad=False) ...
def do_log(self, line): """log [path] Retrieve event log from Member Node The response is filtered by the from-date, to-date, start and count session parameters.""" path = self._split_args(line, 0, 1, pad=False) if len(path): path = path[0] self._command_processor.log...
def do_resolve(self, line): """resolve <identifier> Find all locations from which the given Science Object can be downloaded.""" pid, = self._split_args(line, 1, 0) self._command_processor.resolve(pid)
def do_create(self, line): """create <identifier> <file> Create a new Science Object on a Member Node. The System Metadata that becomes associated with the new Science Object is generated from the session variables. """ pid, sciobj_path = self._split_args(line, 2, 0) se...
def do_update(self, line): """update <old-pid> <new-pid> <file> Replace an existing Science Object in a. :term:`MN` with another. """ curr_pid, pid_new, input_file = self._split_args(line, 3, 0) self._command_processor.science_object_update(curr_pid, input_file, pid_new) ...
def do_package(self, line): """package <package-pid> <science-metadata-pid> <science-pid> [science- pid. ...] Create a simple OAI-ORE Resource Map on a Member Node. """ pids = self._split_args(line, 3, -1, pad=False) self._command_processor.create_package(pids) self._pr...
def do_archive(self, line): """archive <identifier> [identifier ...] Mark one or more existing Science Objects as archived.""" pids = self._split_args(line, 1, -1) self._command_processor.science_object_archive(pids) self._print_info_if_verbose( "Added archive operati...
def do_updateaccess(self, line): """updateaccess <identifier> [identifier ...] Update the Access Policy on one or more existing Science Data Objects.""" pids = self._split_args(line, 1, -1) self._command_processor.update_access_policy(pids) self._print_info_if_verbose( ...
def do_updatereplication(self, line): """updatereplication <identifier> [identifier ...] Update the Replication Policy on one or more existing Science Data Objects.""" pids = self._split_args(line, 1, -1) self._command_processor.update_replication_policy(pids) self._print_info_if...
def do_search(self, line): """search [query] Comprehensive search for Science Data Objects across all available MNs. See https://releases.dataone.org/online/api- documentation-v2.0.1/design/SearchMetadata.html for the available search terms. """ args = self._split_args(...
def do_ping(self, line): """ping [base-url ...] Check if a server responds to the DataONE ping() API method ping (no arguments): Ping the CN and MN that is specified in the session ping <base-url> [base-url ...]: Ping each CN or MN. If an incomplete base-url is provided, default CN and ...
def do_queue(self, line): """queue Print the queue of write operations.""" self._split_args(line, 0, 0) self._command_processor.get_operation_queue().display()
def do_run(self, line): """run Perform each operation in the queue of write operations.""" self._split_args(line, 0, 0) self._command_processor.get_operation_queue().execute() self._print_info_if_verbose( "All operations in the write queue were successfully executed" ...
def do_edit(self, line): """edit Edit the queue of write operations.""" self._split_args(line, 0, 0) self._command_processor.get_operation_queue().edit() self._print_info_if_verbose("The write operation queue was successfully edited")
def do_clearqueue(self, line): """clearqueue Remove the operations in the queue of write operations without performing them.""" self._split_args(line, 0, 0) self._command_processor.get_operation_queue().clear() self._print_info_if_verbose("All operations in the write queue were c...
def _print_help(self): """Custom help message to group commands by functionality.""" msg = """Commands (type help <command> for details) CLI: help history exit quit Session, General: set load save reset Session, Access Control: allowaccess denyaccess clearaccess Session, Repl...
def get_groups_with_perms(obj, attach_perms=False): """Return queryset of all ``Group`` objects with *any* object permissions for the given ``obj``.""" ctype = get_content_type(obj) group_model = get_group_obj_perms_model(obj) if not attach_perms: # It's much easier without attached perms so we...
def _group_groups(perm_list): """Group permissions by group. Input is list of tuples of length 3, where each tuple is in following format:: (<group_id>, <group_name>, <single_permission>) Permissions are regrouped and returned in such way that there is only one tuple for each group:: ...
def get_user_group_perms(user_or_group, obj): """Get permissins for user groups. Based on guardian.core.ObjectPermissionChecker. """ user, group = get_identity(user_or_group) if user and not user.is_active: return [], [] user_model = get_user_model() ctype = ContentType.objects.ge...
def get_object_perms(obj, user=None): """Return permissions for given object in Resolwe specific format. Function returns permissions for given object ``obj`` in following format:: { "type": "group"/"user"/"public", "id": <group_or_user_id>, "name": <group_or_user_n...
def get_objects_for_user(user, perms, klass=None, use_groups=True, any_perm=False, with_superuser=True, accept_global_perms=True, perms_filter='pk__in'): """Return queryset with required permissions.""" if isinstance(perms, str): perms = [perms] ctype = None app_label =...
def get_users_with_permission(obj, permission): """Return users with specific permission on object. :param obj: Object to return users for :param permission: Permission codename """ user_model = get_user_model() return user_model.objects.filter( userobjectpermission__object_pk=obj.pk, ...
def purge_run(self, event): """Run purge for the object with ``location_id`` specified in ``event`` argument.""" location_id = event['location_id'] verbosity = event['verbosity'] try: logger.info(__("Running purge for location id {}.", location_id)) location_purg...
def get_resource_limits(self): """Get the core count and memory usage limits for this process. :return: A dictionary with the resource limits, containing the following keys: - ``memory``: Memory usage limit, in MB. Defaults to 4096 if not otherwise specified in th...
def validate_query_params(self): """Ensure no unsupported query params were used.""" allowed_params = set(self.get_filters().keys()) allowed_params.update(self.get_always_allowed_arguments()) unallowed = set(self.request.query_params.keys()) - allowed_params if unallowed: ...
def set_default_option(cls, key, value): """Class method. Set the default value of the option `key` (string) to `value` for all future instances of the class. Note that this does not affect existing instances or the instance called from.""" cls._default_options.update(cls._optio...
def set_option(self, key, value): """Set the option `key` (string) to `value`. Instance method, affects only current instance. This will clear the cache.""" self._options.update(self._option_schema({key: value})) self.clear_cache()
def get_option(self, key): """Return the current value of the option `key` (string). Instance method, only refers to current instance.""" return self._options.get(key, self._default_options[key])
def from_wc(cls, wc): """Return a `Wilson` instance initialized by a `wcxf.WC` instance""" return cls(wcdict=wc.dict, scale=wc.scale, eft=wc.eft, basis=wc.basis)
def load_wc(cls, stream): """Return a `Wilson` instance initialized by a WCxf file-like object""" wc = wcxf.WC.load(stream) return cls.from_wc(wc)
def match_run(self, scale, eft, basis, sectors='all'): """Run the Wilson coefficients to a different scale (and possibly different EFT) and return them as `wcxf.WC` instance. Parameters: - `scale`: output scale in GeV - `eft`: output EFT - `basis`: output basis ...
def _get_from_cache(self, sector, scale, eft, basis): """Try to load a set of Wilson coefficients from the cache, else return None.""" try: return self._cache[eft][scale][basis][sector] except KeyError: return None
def plotdata(self, key, part='re', scale='log', steps=50): """Return a tuple of arrays x, y that can be fed to plt.plot, where x is the scale in GeV and y is the parameter of interest. Parameters: - key: dicionary key of the parameter to be plotted (e.g. a WCxf coefficient na...
def plot(self, key, part='re', scale='log', steps=50, legend=True, plotargs={}): """Plot the RG evolution of parameter `key`. Parameters: - part, scale, steps: see `plotdata` - legend: boolean, show the legend (default: True) - plotargs: dictionary of arguments to be passed to ...
async def run_consumer(timeout=None, dry_run=False): """Run the consumer until it finishes processing. :param timeout: Set maximum execution time before cancellation, or ``None`` (default) for unlimited. :param dry_run: If ``True``, don't actually dispatch messages, just dequeue them. Defau...
def discover_extensions(self): """Discover available extensions.""" if self._discovery_done: return try: previous_state = self._extensions.copy() for app_config in apps.get_app_configs(): indexes_path = '{}.extensions'.format(app_config.name)...
def _get_class_path(self, klass_or_instance): """Return class path for a given class. :param klass_or_instance: Class or instance of given class :return: String containing the class path """ if inspect.isclass(klass_or_instance): klass = '{}.{}'.format(klass_or_insta...
def add_extension(self, klass, extension): """Register an extension for a class. :param klass: Class to register an extension for :param extension: Extension (arbitrary type) """ klass = self._get_class_path(klass) # TODO: Take order into account. self._extensio...
def get_extensions(self, klass): """Return all registered extensions of a class. :param klass: Class to get registered extensions for :return: All registered extensions for given class """ self.discover_extensions() return self._extensions.get(self._get_class_path(klass...
def _get_running_parameters(self, scale, f, loop=3): """Get the running parameters (e.g. quark masses and the strong coupling at a given scale.""" p = {} p['alpha_s'] = qcd.alpha_s(scale, self.f, self.parameters['alpha_s'], loop=loop) p['m_b'] = qcd.m_b(self.parameters['m_b'], sc...
def run(self, scale_out, sectors='all'): """Evolve the Wilson coefficients to the scale `scale_out`. Parameters: - scale_out: output scale - sectors: optional. If provided, must be a tuple of strings corresponding to WCxf sector names. Only Wilson coefficients belon...
def size(self): """Returns: int : The total number of bytes that will be returned by the iterator. """ if hasattr(self._stream, 'len'): return len(self._stream) elif hasattr(self._stream, 'fileno'): return os.fstat(self._stream.fileno()).st_size el...
def _get_cn_cert(): """Get the public TLS/SSL X.509 certificate from the root CN of the DataONE environment. The certificate is used for validating the signature of the JWTs. If certificate retrieval fails, a new attempt to retrieve the certificate is performed after the cache expires (settings.CACHES....
def key(self, key=""): """ Takes a user's API key string which applies content settings. API keys can be found at <https://derpibooru.org/users/edit>. """ params = join_params(self.parameters, {"key": key}) return self.__class__(**params)
def query(self, *q): """ Takes one or more strings for searching by tag and/or metadata. """ params = join_params(self.parameters, {"q": q}) return self.__class__(**params)
def sort_by(self, sf): """ Determines how to sort search results. Available sorting methods are sort.SCORE, sort.COMMENTS, sort.HEIGHT, sort.RELEVANCE, sort.CREATED_AT, and sort.RANDOM; default is sort.CREATED_AT. """ params = join_params(self.parameters, {"sf": sf}) return self.__class__(*...
def limit(self, limit): """ Set absolute limit on number of images to return, or set to None to return as many results as needed; default 50 posts. """ params = join_params(self.parameters, {"limit": limit}) return self.__class__(**params)
def filter(self, filter_id=""): """ Takes a filter's ID to be used in the current search context. Filter IDs can be found at <https://derpibooru.org/filters/> by inspecting the URL parameters. If no filter is provided, the user's current filter will be used. """ params = join_params(self.pa...
def faves(self, option): """ Set whether to filter by a user's faves list. Options available are user.ONLY, user.NOT, and None; default is None. """ params = join_params(self.parameters, {"faves": option}) return self.__class__(**params)
def upvotes(self, option): """ Set whether to filter by a user's upvoted list. Options available are user.ONLY, user.NOT, and None; default is None. """ params = join_params(self.parameters, {"upvotes": option}) return self.__class__(**params)
def uploads(self, option): """ Set whether to filter by a user's uploads list. Options available are user.ONLY, user.NOT, and None; default is None. """ params = join_params(self.parameters, {"uploads": option}) return self.__class__(**params)
def watched(self, option): """ Set whether to filter by a user's watchlist. Options available are user.ONLY, user.NOT, and None; default is None. """ params = join_params(self.parameters, {"watched": option}) return self.__class__(**params)
def define_contributor(self, request): """Define contributor by adding it to request.data.""" request.data['contributor'] = self.resolve_user(request.user).pk
def create(self, request, *args, **kwargs): """Create a resource.""" self.define_contributor(request) try: return super().create(request, *args, **kwargs) except IntegrityError as ex: return Response({'error': str(ex)}, status=status.HTTP_409_CONFLICT)