text
stringlengths
81
112k
Set the last call to expect that certain arguments will not exist. This is the opposite of :func:`fudge.Fake.with_matching_args`. It will fail if any of the arguments are passed. .. doctest:: >>> import fudge >>> query = fudge.Fake('query').expects_call().without_args...
Set the last call to expect an exact argument count. I.E.:: >>> auth = Fake('auth').provides('login').with_arg_count(2) >>> auth.login('joe_user') # forgot password Traceback (most recent call last): ... AssertionError: fake:auth.login() was called w...
Set the last call to expect an exact count of keyword arguments. I.E.:: >>> auth = Fake('auth').provides('login').with_kwarg_count(2) >>> auth.login(username='joe') # forgot password= Traceback (most recent call last): ... AssertionError: fake:auth.l...
connect to the various databases, the credientals and settings of which are found in the sherlock settings file **Return:** - ``transientsDbConn`` -- the database hosting the transient source data - ``cataloguesDbConn`` -- connection to the database hosting the contextual catalogues the...
*setup a ssh tunnel for a database connection to port through* **Key Arguments:** - ``tunnelParameters`` -- the tunnel parameters found associated with the database settings **Return:** - ``sshPort`` -- the port the ssh tunnel is connected via .. todo :: -...
Check that the TCP Port we've decided to use for tunnelling is available .. todo :: - update key arguments values and definitions with defaults - update return values and definitions - update usage examples and text - update docstring text - check su...
Decorator to switch an url from http to https. If a view is accessed through http and this decorator is applied to that view, than it will return a permanent redirect to the secure (https) version of the same view. The decorator also must check that ``ACCOUNTS_USE_HTTPS`` is enabled. If disable...
A simple identification field factory which enable you to set the label. :param label: String containing the label for this field. :param error_required: String containing the error message if the field is left empty. def identification_field_factory(label, error_required): """ A simp...
Validate that the username is unique and not listed in ``defaults.ACCOUNTS_FORBIDDEN_USERNAMES`` list. def clean_username(self): """ Validate that the username is unique and not listed in ``defaults.ACCOUNTS_FORBIDDEN_USERNAMES`` list. """ try: us...
Validate that the email address is unique. def clean_email(self): """ Validate that the email address is unique. """ if get_user_model().objects.filter( Q(email__iexact=self.cleaned_data['email']) | Q(email_unconfirmed__iexact=self.cleaned_data['email'...
Creates a new user and account. Returns the newly created user. def save(self): """ Creates a new user and account. Returns the newly created user. """ username, email, password = (self.cleaned_data['username'], self.cleaned_data['email'],...
Checks for the identification and password. If the combination can't be found will raise an invalid sign in error. def clean(self): """ Checks for the identification and password. If the combination can't be found will raise an invalid sign in error. """ identificatio...
Validate that the email is not already registered with another user. def clean_email(self): """ Validate that the email is not already registered with another user. """ if self.cleaned_data['email'].lower() == self.user.email: raise forms.ValidationError(_(u"You're...
Validates format and file size of uploaded profile picture. def clean_picture(self): """ Validates format and file size of uploaded profile picture. """ if self.cleaned_data.get('picture'): picture_data = self.cleaned_data['picture'] if 'error' in pictur...
TODO: def visit_grouping(self, grouping, asfrom=False, **kwargs): """" TODO: """ return { 'type': 'grouping', 'grouping': grouping.element._compiler_dispatch(self, **kwargs) }
if select._prefixes: text += self._generate_prefixes( select, select._prefixes, **kwargs) def visit_select(self, select, asfrom=False, parens=True, fromhints=None, compound_index=0, nested_join_translation=False, ...
produce labeled columns present in a select(). def _label_select_column(self, select, column, populate_result_map, asfrom, column_clause_args, name=None, within_columns_clause=True): """produce l...
Main function def run(): """Main function """ import argparse global LOGGER parser = argparse.ArgumentParser() parser.add_argument("-r", "--rotated", help="Time rotated log file") parser.add_argument("-v", "--verbose", help="print debug messages too", action="store...
Log stuff. def log(self): """Log stuff. """ with Subscribe(services=[""], addr_listener=True) as sub: for msg in sub.recv(1): if msg: if msg.type in ["log.debug", "log.info", "log.warning", "log.error", ...
Stop all started tasks on system exit. Note: This only handles signals caught by the atexit module by default. SIGKILL, for instance, will not be caught, so cleanup is not guaranteed in all cases. def cleanup(): """Stop all started tasks on system exit. Note: This only handles signals caught by t...
Start a task. This function depends on the underlying implementation of _start, which any subclass of ``Task`` should implement. Args: wait (bool): Whether or not to wait on the task to finish before returning from this function. Default `False`. Raises: ...
Wait on a task to finish and stop it when it has finished. Raises: RuntimeError: If the task hasn't been started or has already been stopped. Returns: The ``return_values`` of the task. def wait(self): """Wait on a task to finish and stop it when it has...
Stop a task immediately. Raises: RuntimeError: If the task hasn't been started or has already been stopped. def stop(self): """Stop a task immediately. Raises: RuntimeError: If the task hasn't been started or has already been stopped. ...
Reset a task. Allows a task to be started again, clears the ``return_values``. Raises: RuntimeError: If the task has not been stopped. def reset(self): """Reset a task. Allows a task to be started again, clears the ``return_values``. Raises: RuntimeEr...
Helper method to aggregate RemoteTasks into single ssh session. def _aggregate(self): """Helper method to aggregate RemoteTasks into single ssh session.""" # pylint: disable=W0212 nonremote = [t for t in self._tasks if not isinstance(t, RemoteTask)] remote = [t for t in self._tasks if i...
Uploads a picture for a user to the ``ACCOUNTS_PICTURE_PATH`` and saving it under unique hash for the image. This is for privacy reasons so others can't just browse through the picture directory. def upload_to_picture(instance, filename): """ Uploads a picture for a user to the ``ACCOUNTS_PICTURE_PAT...
Checks if activation key is expired. Returns ``True`` when the ``activation_key`` of the user is expired and ``False`` if the key is still valid. The key is expired when it's set to the value defined in ``ACCOUNTS_ACTIVATED`` or ``activation_key_created`` is beyond the amount ...
Sends a activation email to the user. This email is send when the user wants to activate their newly created user. def send_activation_email(self): """ Sends a activation email to the user. This email is send when the user wants to activate their newly created user. ...
Changes the email address for a user. A user needs to verify this new email address before it becomes active. By storing the new email address in a temporary field -- ``temporary_email`` -- we are able to set this email address after the user has verified it by clicking on the verific...
Sends an email to confirm the new email address. This method sends out two emails. One to the new email address that contains the ``email_confirmation_key`` which is used to verify this this email address with :func:`User.objects.confirm_email`. The other email is to the old email addr...
Returns the image containing the picture for the user. The picture can be a uploaded image or a Gravatar. Gravatar functionality will only be used when ``ACCOUNTS_GRAVATAR_PICTURE`` is set to ``True``. :return: ``None`` when Gravatar is not used and no default image is ...
Returns the full name of the user, or if none is supplied will return the username. Also looks at ``ACCOUNTS_WITHOUT_USERNAMES`` settings to define if it should return the username or email address when the full name is not supplied. :return: ``String`` containing t...
Verify sanity for a :class:`.Config` instance. This will raise an exception in case conditions are not met, otherwise will complete silently. :param config: (:class:`.Config`) Configuration container. def validate_config(config): """Verify sanity for a :class:`.Config` instance. ...
Construct a :class:`.Request` for the given resource type. Provided an :class:`.Entry` subclass, the Content Type ID will be inferred and requested explicitly. Examples:: client.fetch(Asset) client.fetch(Entry) client.fetch(ContentType) client.fetch(Cus...
Resolve a link to a CDA resource. Provided an `array` argument, attempt to retrieve the resource from the `mapped_items` section of that array (containing both included and regular resources), in case the resource cannot be found in the array (or if no `array` was provided) - attempt to fetch ...
Convenience method for resolving links given a :class:`.resources.ResourceLink` object. Extract link values and pass to the :func:`.resolve` method of this class. :param resource_link: (:class:`.ResourceLink`) instance. :param array: (:class:`.Array`) Optional array resource. :return: ...
Convenience method for resolving links given a dict object. Extract link values and pass to the :func:`.resolve` method of this class. :param dct: (dict) Dictionary with the link data. :param array: (:class:`.Array`) Optional array resource. :return: :class:`.Resource` subclass, `None`...
Invoke the given :class:`.Request` instance using the associated :class:`.Dispatcher`. :param request: :class:`.Request` instance to invoke. :return: :class:`.Resource` subclass. def invoke(self, request): """Invoke the given :class:`.Request` instance using the associated :class:`.Dispatcher`...
Attempt to retrieve all available resources matching this request. :return: Result instance as returned by the :class:`.Dispatcher`. def all(self): """Attempt to retrieve all available resources matching this request. :return: Result instance as returned by the :class:`.Dispatcher`. "...
Attempt to retrieve only the first resource matching this request. :return: Result instance, or `None` if there are no matching resources. def first(self): """Attempt to retrieve only the first resource matching this request. :return: Result instance, or `None` if there are no matching resour...
Set a dict of parameters to be passed to the API when invoking this request. :param params: (dict) query parameters. :return: this :class:`.RequestArray` instance for convenience. def where(self, params): """Set a dict of parameters to be passed to the API when invoking this request. ...
This function demonstrates a more complex usage of the require_condition function. It shows argument interpolation and handling a more complex boolean expression def complex_require_condition(): """ This function demonstrates a more complex usage of the require_condition function. It shows argument...
Highlight menu item based on url tag. Returns a css class if ``request.path`` is in given ``url``. :param url: Django url to be reversed. :param css: Css class to be returned for highlighting. Return active if none set. def active_url(context, urls, css=None): """ Highlig...
Highlight menu item based on path. Returns a css class if ``request.path`` is in given ``pattern``. :param pattern: Regex url pattern. :param css: Css class to be returned for highlighting. Return active if none set. def active_path(context, pattern, css=None): """ Highli...
Retrieve the value of an option. :param str item_name: The name of the option to retrieve. :return: The value of *item_name* in the configuration. def get(self, item_name): """ Retrieve the value of an option. :param str item_name: The name of the option to retrieve. :return: The value of *item_name* in ...
Retrieve the value of an option if it exists, otherwise return *default_value* instead of raising an error: :param str item_name: The name of the option to retrieve. :param default_value: The value to return if *item_name* does not exist. :return: The value of *item_name* in the configuration. def get_if_exis...
Check that an option exists. :param str option_name: The name of the option to check. :return: True of the option exists in the configuration. :rtype: bool def has_option(self, option_name): """ Check that an option exists. :param str option_name: The name of the option to check. :return: True of the o...
Checks that an option exists and that it contains sub options. :param str section_name: The name of the section to check. :return: True if the section exists. :rtype: dict def has_section(self, section_name): """ Checks that an option exists and that it contains sub options. :param str section_name: The ...
Sets the value of an option in the configuration. :param str item_name: The name of the option to set. :param item_value: The value of the option to set. def set(self, item_name, item_value): """ Sets the value of an option in the configuration. :param str item_name: The name of the option to set. :param...
Use a verification configuration which has a list of required options and their respective types. This information is used to identify missing and incompatible options in the loaded configuration. :param str verify_file: The file to load for verification data. :return: A dictionary of missing and incompatible ...
Save the current configuration to disk. def save(self): """ Save the current configuration to disk. """ with open(self.configuration_file, 'w') as file_h: file_h.write(self._serializer('dumps', self._storage))
Uses replacement handler to perform replacements on lines of text First we strip off all whitespace We run the replacement on a clean 'content' string Finally we replace the original content with the replaced version This ensures that we retain the correct whitespace from the original line def replace...
Writes version info into version file def write_targets(targets, **params): """Writes version info into version file""" handler = ReplacementHandler(**params) for target, regexer in regexer_for_targets(targets): with open(target) as fh: lines = fh.readlines() lines = replace_lin...
Pairs up target files with their correct regex def regexer_for_targets(targets): """Pairs up target files with their correct regex""" for target in targets: path, file_ext = os.path.splitext(target) regexer = config.regexers[file_ext] yield target, regexer
Given some lines of text, extract key-value pairs from them def extract_keypairs(lines, regexer): """Given some lines of text, extract key-value pairs from them""" updates = {} for line in lines: # for consistency we must match the replacer and strip whitespace / newlines match = regexer.ma...
Reads generic key-value pairs from input files def read_targets(targets): """Reads generic key-value pairs from input files""" results = {} for target, regexer in regexer_for_targets(targets): with open(target) as fh: results.update(extract_keypairs(fh.readlines(), regexer)) return ...
The existence of files matching configured globs will trigger a version bump def detect_file_triggers(trigger_patterns): """The existence of files matching configured globs will trigger a version bump""" triggers = set() for trigger, pattern in trigger_patterns.items(): matches = glob.glob(pattern)...
Aggregated set of significant figures to bump def get_all_triggers(bump, file_triggers): """Aggregated set of significant figures to bump""" triggers = set() if file_triggers: triggers = triggers.union(detect_file_triggers(config.trigger_patterns)) if bump: _LOG.debug("trigger: %s bump ...
Binary state lock protects from version increments if set def get_lock_behaviour(triggers, all_data, lock): """Binary state lock protects from version increments if set""" updates = {} lock_key = config._forward_aliases.get(Constants.VERSION_LOCK_FIELD) # if we are explicitly setting or locking the ver...
Generates update dictionary entries for the version string def get_final_version_string(release_mode, semver, commit_count=0): """Generates update dictionary entries for the version string""" version_string = ".".join(semver) maybe_dev_version_string = version_string updates = {} if release_mode: ...
Gets current repository info from git def get_dvcs_info(): """Gets current repository info from git""" cmd = "git rev-list --count HEAD" commit_count = str( int(subprocess.check_output(shlex.split(cmd)).decode("utf8").strip()) ) cmd = "git rev-parse HEAD" commit = str(subprocess.check_o...
Main workflow. Load config from cli and file Detect "bump triggers" - things that cause a version increment Find the current version Create a new version Write out new version and any other requested variables :param set_to: explicitly set semver to this version string :param set_patch_cou...
Main workflow. Load config from cli and file Detect "bump triggers" - things that cause a version increment Find the current version Create a new version Write out new version and any other requested variables def main_from_cli(): """Main workflow. Load config from cli and file Detect...
Log an analysis. CONFIG: MIP config file for an analysis def log_cmd(context, sampleinfo, sacct, quiet, config): """Log an analysis. CONFIG: MIP config file for an analysis """ log_analysis = LogAnalysis(context.obj['store']) try: new_run = log_analysis(config, sampleinfo=sampleinfo, ...
Start a new analysis. def start(context, mip_config, email, priority, dryrun, command, start_with, family): """Start a new analysis.""" mip_cli = MipCli(context.obj['script']) mip_config = mip_config or context.obj['mip_config'] email = email or environ_email() kwargs = dict(config=mip_config, fami...
Setup the database. def init(context, reset, force): """Setup the database.""" existing_tables = context.obj['store'].engine.table_names() if force or reset: if existing_tables and not force: message = f"Delete existing tables? [{', '.join(existing_tables)}]" click.confirm(c...
Scan a directory for analyses. def scan(context, root_dir): """Scan a directory for analyses.""" root_dir = root_dir or context.obj['root'] config_files = Path(root_dir).glob('*/analysis/*_config.yaml') for config_file in config_files: LOG.debug("found analysis config: %s", config_file) ...
Add a new or display information about an existing user. def user(context, name, email): """Add a new or display information about an existing user.""" existing_user = context.obj['store'].user(email) if existing_user: click.echo(existing_user.to_dict()) elif name: new_user = context.ob...
Cancel all jobs in a run. def cancel(context, jobs, analysis_id): """Cancel all jobs in a run.""" analysis_obj = context.obj['store'].analysis(analysis_id) if analysis_obj is None: click.echo('analysis not found') context.abort() elif analysis_obj.status != 'running': click.echo...
Get the address of the publisher for a given list of publisher *names* from the nameserver on *nameserver* (localhost by default). def get_pub_addresses(names=None, timeout=10, nameserver="localhost"): """Get the address of the publisher for a given list of publisher *names* from the nameserver on *nameser...
Get the address of the publisher for a given publisher *name* from the nameserver on *nameserver* (localhost by default). def get_pub_address(name, timeout=10, nameserver="localhost"): """Get the address of the publisher for a given publisher *name* from the nameserver on *nameserver* (localhost by default...
Get the addresses of the active modules for a given publisher *name*. def get_active_address(name, arec): """Get the addresses of the active modules for a given publisher *name*. """ addrs = arec.get(name) if addrs: return Message("/oper/ns", "info", addrs) else: return Message("/op...
Run the listener and answer to requests. def run(self, *args): """Run the listener and answer to requests. """ del args arec = AddressReceiver(max_age=self._max_age, multicast_enabled=self._multicast_enabled) arec.start() port = PORT ...
Stop the name server. def stop(self): """Stop the name server. """ self.listener.setsockopt(LINGER, 1) self.loop = False with nslock: self.listener.close()
Parse requirements for package information to determine if all requirements are met. The *requirements* argument can be a string to a requirements file, a file like object to be read, or a list of strings representing the package requirements. :param requirements: The file to parse. :type requirements: file obj, ...
reverses segments_to_numpy def segments_from_numpy(segments): """reverses segments_to_numpy""" segments = segments if SEGMENTS_DIRECTION == 0 else segments.tranpose() segments = [map(int, s) for s in segments] return segments
given a list of 4-element tuples, transforms it into a numpy array def segments_to_numpy(segments): """given a list of 4-element tuples, transforms it into a numpy array""" segments = numpy.array(segments, dtype=SEGMENT_DATATYPE, ndmin=2) # each segment in a row segments = segments if SEGMENTS_DIRECTION =...
given a segment (rectangle) and an image, returns it's corresponding subimage def region_from_segment(image, segment): """given a segment (rectangle) and an image, returns it's corresponding subimage""" x, y, w, h = segment return image[y:y + h, x:x + w]
*Ingest the ePESSTO Marshall transient stream into the catalogues database* The method first creates the tables for the various marshall feeder surveys in the sherlock-catalogues database (if they do not yet exist). Then the marshall database is queried for each transient survey and the results imported into t...
create a list of dictionaries containing all the rows in the marshall stream **Key Arguments:** - ``marshallQuery`` -- the query used to lift the required data from the marshall database. - ``marshallTable`` -- the name of the marshall table we are lifting the data from. **Retu...
Import the ned_d catalogue into the catalogues database The method first generates a list of python dictionaries from the ned_d datafile, imports this list of dictionaries into a database table and then generates the HTMIDs for that table. **Usage:** See class docstring for usage ...
create a list of dictionaries containing all the rows in the ned_d catalogue **Return:** - ``dictList`` - a list of dictionaries containing all the rows in the ned_d catalogue .. todo :: - update key arguments values and definitions with defaults - update return va...
clean up columns of the NED table .. todo :: - update key arguments values and definitions with defaults - update return values and definitions - update usage examples and text - update docstring text - check sublime snippet exists - clip...
get metadata for galaxies .. todo :: - update key arguments values and definitions with defaults - update return values and definitions - update usage examples and text - update docstring text - check sublime snippet exists - clip any use...
get 3000 galaxies needing metadata **Return:** - ``len(self.theseIds)`` -- the number of NED IDs returned .. todo :: - update key arguments values and definitions with defaults - update return values and definitions - update usage examples and text ...
query ned and add results to database **Key Arguments:** - ``batchCount`` - the index number of the batch sent to NED .. todo :: - update key arguments values and definitions with defaults - update return values and definitions - update usage examples a...
update sdss coverage .. todo :: - update key arguments values and definitions with defaults - update return values and definitions - update usage examples and text - update docstring text - check sublime snippet exists - clip any useful t...
Run a command on the remote host. This is just a wrapper around ``RemoteTask(self.hostname, ...)`` def run(self, command, **kwargs): """Run a command on the remote host. This is just a wrapper around ``RemoteTask(self.hostname, ...)`` """ return RemoteTask(self.hostname, comma...
Helper method to generate base rsync command. def _rsync_cmd(self): """Helper method to generate base rsync command.""" cmd = ['rsync'] if self._identity_file: cmd += ['-e', 'ssh -i ' + os.path.expanduser(self._identity_file)] return cmd
Send a file to a remote host with rsync. Args: file_name (str): The relative location of the file on the local host. remote_destination (str): The destination for the file on the remote host. If `None`, will be assumed to be the same as *...
Get a file from a remote host with rsync. Args: file_name (str): The relative location of the file on the remote host. local_destination (str): The destination for the file on the local host. If `None`, will be assumed to be the same as *...
Make a MIP config. def make_config(self, data: dict): """Make a MIP config.""" self.validate_config(data) config_data = self.prepare_config(data) return config_data
Convert to MIP config format. def validate_config(data: dict) -> dict: """Convert to MIP config format.""" errors = ConfigSchema().validate(data) if errors: for field, messages in errors.items(): if isinstance(messages, dict): for level, sample_er...
Prepare the config data. def prepare_config(data: dict) -> dict: """Prepare the config data.""" data_copy = deepcopy(data) # handle single sample cases with 'unknown' phenotype if len(data_copy['samples']) == 1: if data_copy['samples'][0]['phenotype'] == 'unknown': ...
Save a config to the expected location. def save_config(self, data: dict) -> Path: """Save a config to the expected location.""" out_dir = Path(self.families_dir) / data['family'] out_dir.mkdir(parents=True, exist_ok=True) out_path = out_dir / 'pedigree.yaml' dump = ruamel.yaml....
To be used exclusively by create_broadcast. A broadcast function gets an attribute on the src_processor and sets it (possibly under a different name) on dest_processors def _broadcast(src_processor, src_atr_name, dest_processors, dest_atr_name, transform_function): """ To be used exclusively by create_...
This method creates a function, intended to be called as a Processor posthook, that copies some of the processor's attributes to other processors def create_broadcast(src_atr_name, dest_processors, dest_atr_name=None, transform_function=lambda x: x): """ This method creates a function, intended to be c...
returns a dictionary with the processor's stored parameters def get_parameters(self): """returns a dictionary with the processor's stored parameters""" parameter_names = self.PARAMETERS.keys() # TODO: Unresolved reference for processor parameter_values = [getattr(processor, n) for n in ...
sets the processor stored parameters def set_parameters(self, **args): """sets the processor stored parameters""" for k, v in self.PARAMETERS.items(): new_value = args.get(k) if new_value != None: if not _same_type(new_value, v): raise Excepti...
gets from all wrapped processors def get_parameters(self): """gets from all wrapped processors""" d = {} for p in self.processors: parameter_names = list(p.PARAMETERS.keys()) parameter_values = [getattr(p, n) for n in parameter_names] d.update(dict(zip(parame...