def delete_case(self, case_id=None, institute_id=None, display_name=None):
    query = {}
    if case_id:
        query['_id'] = case_id
        LOG.info('Deleting case %s', case_id)
    else:
        if (not (institute_id and display_name)):
            raise ValueError('Have to provide both institute_id and display_name')
        LOG.info('Deleting case %s institute %s', display_name, institute_id)
        query['owner'] = institute_id
        query['display_name'] = display_name
    result = self.case_collection.delete_one(query)
    return result

Delete a single case from database

Args:
        institute_id(str)
        case_id(str)

Returns:
        case_obj(dict): The case that was deleted


def Acf(poly, dist, N=None, **kws):
    if (N is None):
        N = ((len(poly) / 2) + 1)
    corr = Corr(poly, dist, **kws)
    out = numpy.empty(N)
    for n in range(N):
        out[n] = numpy.mean(corr.diagonal(n), 0)
    return out

Auto-correlation function.

Args:
        poly (Poly):
            Polynomial of interest. Must have ``len(poly) > N``.
        dist (Dist):
            Defines the space the correlation is taken on.
        N (int):
            The number of time steps appart included. If omited set to
            ``len(poly)/2+1``.

Returns:
        (numpy.ndarray) :
            Auto-correlation of ``poly`` with shape ``(N,)``. Note that by
            definition ``Q[0]=1``.

Example:
        >>> poly = chaospy.prange(10)[1:]
        >>> Z = chaospy.Uniform()
        >>> print(numpy.around(chaospy.Acf(poly, Z, 5), 4))
        [1.     0.9915 0.9722 0.9457 0.9127]


def sia(transition, direction=Direction.BIDIRECTIONAL):
    validate.direction(direction, allow_bi=True)
    log.info('Calculating big-alpha for %s...', transition)
    if (not transition):
        log.info('Transition %s is empty; returning null SIA immediately.', transition)
        return _null_ac_sia(transition, direction)
    if (not connectivity.is_weak(transition.network.cm, transition.node_indices)):
        log.info('%s is not strongly/weakly connected; returning null SIA immediately.', transition)
        return _null_ac_sia(transition, direction)
    log.debug('Finding unpartitioned account...')
    unpartitioned_account = account(transition, direction)
    log.debug('Found unpartitioned account.')
    if (not unpartitioned_account):
        log.info('Empty unpartitioned account; returning null AC SIA immediately.')
        return _null_ac_sia(transition, direction)
    cuts = _get_cuts(transition, direction)
    engine = ComputeACSystemIrreducibility(cuts, transition, direction, unpartitioned_account)
    result = engine.run_sequential()
    log.info('Finished calculating big-ac-phi data for %s.', transition)
    log.debug('RESULT: \n%s', result)
    return result

Return the minimal information partition of a transition in a specific
    direction.

Args:
        transition (Transition): The candidate system.

Returns:
        AcSystemIrreducibilityAnalysis: A nested structure containing all the
        data from the intermediate calculations. The top level contains the
        basic irreducibility information for the given subsystem.


def list(self, **kwargs):
    resp = self.client.api.secrets(**kwargs)
    return [self.prepare_model(obj) for obj in resp]

List secrets. Similar to the ``docker secret ls`` command.

Args:
        filters (dict): Server-side list filtering options.

Returns:
        (list of :py:class:`Secret`): The secrets.

Raises:
        :py:class:`docker.errors.APIError`
            If the server returns an error.


def create_ondemand_streaming_locator(access_token, encoded_asset_id, pid, starttime=None):
    path = '/Locators'
    endpoint = ''.join([ams_rest_endpoint, path])
    if (starttime is None):
        body = (((('{ \t\t\t"AccessPolicyId":"' + pid) + '", \t\t\t"AssetId":"') + encoded_asset_id) + '", \t\t\t"Type": "2"     }')
    else:
        body = (((((('{ \t\t\t"AccessPolicyId":"' + pid) + '", \t\t\t"AssetId":"') + encoded_asset_id) + '", \t\t\t"StartTime":"') + str(starttime)) + '", \t\t\t"Type": "2" \t\t}')
    return do_ams_post(endpoint, path, body, access_token, 'json_only')

Create Media Service OnDemand Streaming Locator.

Args:
        access_token (str): A valid Azure authentication token.
        encoded_asset_id (str): A Media Service Encoded Asset ID.
        pid (str): A Media Service Encoded PID.
        starttime (str): A Media Service Starttime.

Returns:
        HTTP response. JSON body.


def get_membership(self, uuid=None):
    group_id = self.get_group_id(uuid=uuid)
    uri = 'group/{group_id}/member'
    mbr_data = self.get(uri.format(group_id=group_id), params=None)
    return mbr_data

Get membership data based on uuid.

Args:
        uuid (str): optional uuid. defaults to self.cuuid

Raises:
        PyLmodUnexpectedData: No data was returned.
        requests.RequestException: Exception connection error

Returns:
        dict: membership json


def earliest_date(dates, full_date=False):
    min_date = min((PartialDate.loads(date) for date in dates))
    if ((not min_date.month) and full_date):
        min_date.month = 1
    if ((not min_date.day) and full_date):
        min_date.day = 1
    return min_date.dumps()

Return the earliest among the schema-compliant dates.

    This is a convenience wrapper around :ref:`PartialDate`, which should be
    used instead if more features are needed.

Args:
        dates(list): List of dates from which oldest/earliest one will be returned
        full_date(bool): Adds month and/or day as "01" if they are missing

Returns:
        str: Earliest date from provided list


def create(options, timer=None, use_deque=True):
    if (options is None):
        return None
    if (not isinstance(options, (CheckOptions, QuotaOptions, ReportOptions))):
        _logger.error(u'make_cache(): bad options %s', options)
        raise ValueError(u'Invalid options')
    if (options.num_entries <= 0):
        _logger.debug(u'did not create cache, options was %s', options)
        return None
    _logger.debug(u'creating a cache from %s', options)
    if (options.flush_interval > ZERO_INTERVAL):
        ttl = getattr(options, u'expiration', options.flush_interval)
        cache_cls = (DequeOutTTLCache if use_deque else cachetools.TTLCache)
        return LockedObject(cache_cls(options.num_entries, ttl=ttl.total_seconds(), timer=to_cache_timer(timer)))
    cache_cls = (DequeOutLRUCache if use_deque else cachetools.LRUCache)
    return LockedObject(cache_cls(options.num_entries))

Create a cache specified by ``options``

    ``options`` is an instance of either
    :class:`endpoints_management.control.caches.CheckOptions` or
    :class:`endpoints_management.control.caches.ReportOptions`

    The returned cache is wrapped in a :class:`LockedObject`, requiring it to
    be accessed in a with statement that gives synchronized access

Example:
        >>> options = CheckOptions()
        >>> synced_cache = make_cache(options)
        >>> with synced_cache as cache:  #  acquire the lock
        ...    cache['a_key'] = 'a_value'

Args:
        options (object): an instance of either of the options classes

Returns:
        :class:`cachetools.Cache`: the cache implementation specified by options
        or None: if options is ``None`` or if options.num_entries < 0

Raises:
        ValueError: if options is not a support type


def _run(self, cmd):
    if isinstance(cmd, six.string_types):
        cmd = salt.utils.args.shlex_split(cmd)
    try:
        log.debug(cmd)
        p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        return p.communicate()
    except (OSError, IOError) as exc:
        log.debug('Command Failed: %s', ' '.join(cmd))
        log.debug('Error: %s', exc)
        raise CommandExecutionError(exc)

Internal function for running commands. Used by the uninstall function.

Args:
        cmd (str, list): The command to run

Returns:
        str: The stdout of the command


def read_from(fpath, verbose=None, aslines=False, strict=True, n=None, errors='replace'):
    if (n is None):
        n = __READ_TAIL_N__
    verbose = _rectify_verb_read(verbose)
    if verbose:
        print(('[util_io] * Reading text file: %r ' % util_path.tail(fpath, n=n)))
    try:
        if (not util_path.checkpath(fpath, verbose=verbose, n=n)):
            raise IOError('[io] * FILE DOES NOT EXIST!')
        with open(fpath, 'rb') as file_:
            if aslines:
                if six.PY2:
                    text = [line.decode('utf8', errors=errors) for line in file_.readlines()]
                else:
                    text = [line.decode('utf8', errors=errors) for line in file_.readlines()]
            elif six.PY2:
                text = file_.read().decode('utf8', errors=errors)
            else:
                text = file_.read().decode('utf8', errors=errors)
        return text
    except IOError as ex:
        from utool import util_dbg
        if (verbose or strict):
            util_dbg.printex(ex, (' * Error reading fpath=%r' % util_path.tail(fpath, n=n)), '[io]')
        if strict:
            raise

r""" Reads text from a file. Automatically returns utf8.

Args:
        fpath (str): file path
        aslines (bool): if True returns list of lines
        verbose (bool): verbosity flag

Returns:
        str: text from fpath (this is unicode)

    Ignore:
        x = b'''/whaleshark_003_fors\xc3\xb8g.wmv" />\r\n'''
        ut.writeto('foo.txt', x)
        y = ut.readfrom('foo.txt')
        y.encode('utf8') == x


def get_cluster(self, label):
    for cluster in self._clusters:
        if (label == cluster['label']):
            return self._get_connection(cluster)
    raise AttributeError(('No such cluster %s.' % label))

Returns a connection to a mongo-clusters.

Args:
        label (string): the label of a cluster.

Returns:
        A connection to the cluster labeld with label.

Raises:
        AttributeError: there is no cluster with the given label in the
            config


def load_kegg(self, kegg_id, kegg_organism_code=None, kegg_seq_file=None, kegg_metadata_file=None, set_as_representative=False, download=False, outdir=None, force_rerun=False):
    if download:
        if (not outdir):
            outdir = self.sequence_dir
            if (not outdir):
                raise ValueError('Output directory must be specified')
    if kegg_organism_code:
        kegg_id = ((kegg_organism_code + ':') + kegg_id)
    if self.sequences.has_id(kegg_id):
        if force_rerun:
            existing = self.sequences.get_by_id(kegg_id)
            self.sequences.remove(existing)
        else:
            log.debug('{}: KEGG ID already present in list of sequences'.format(kegg_id))
            kegg_prop = self.sequences.get_by_id(kegg_id)
    if (not self.sequences.has_id(kegg_id)):
        kegg_prop = KEGGProp(id=kegg_id, seq=None, fasta_path=kegg_seq_file, txt_path=kegg_metadata_file)
        if download:
            kegg_prop.download_seq_file(outdir, force_rerun)
            kegg_prop.download_metadata_file(outdir, force_rerun)
        if self.representative_sequence:
            if (not self.representative_sequence.uniprot):
                if kegg_prop.equal_to(self.representative_sequence):
                    self.representative_sequence.update(kegg_prop.get_dict(), only_keys=['sequence_path', 'metadata_path', 'kegg', 'description', 'taxonomy', 'id', 'pdbs', 'uniprot', 'seq_record', 'gene_name', 'refseq'])
                else:
                    log.warning('{}: representative sequence does not match mapped KEGG sequence.'.format(self.id))
        self.sequences.append(kegg_prop)
    if set_as_representative:
        self.representative_sequence = kegg_prop
    return self.sequences.get_by_id(kegg_id)

Load a KEGG ID, sequence, and metadata files into the sequences attribute.

Args:
        kegg_id (str): KEGG ID
        kegg_organism_code (str): KEGG organism code to prepend to the kegg_id if not part of it already.
            Example: ``eco:b1244``, ``eco`` is the organism code
        kegg_seq_file (str): Path to KEGG FASTA file
        kegg_metadata_file (str): Path to KEGG metadata file (raw KEGG format)
        set_as_representative (bool): If this KEGG ID should be set as the representative sequence
        download (bool): If the KEGG sequence and metadata files should be downloaded if not provided
        outdir (str): Where the sequence and metadata files should be downloaded to
        force_rerun (bool): If ID should be reloaded and files redownloaded

Returns:
        KEGGProp: object contained in the sequences attribute


def libravatar_url(email=None, openid=None, size=64, default='retro'):
    params = collections.OrderedDict([('s', size), ('d', default)])
    query = parse.urlencode(params)
    if email:
        value = email
    elif openid:
        value = openid
    else:
        raise ValueError('You must provide either the email or the openid.')
    idhash = sha256(value.encode('utf-8')).hexdigest()
    return ('https://seccdn.libravatar.org/avatar/%s?%s' % (idhash, query))

Get the URL to an avatar from libravatar.

    Either the user's email or openid must be provided.

    If you want to use Libravatar federation (through DNS), you should install
    and use the ``libravatar`` library instead. Check out the
    ``libravatar.libravatar_url()`` function.

Args:
        email (str): The user's email
        openid (str): The user's OpenID
        size (int): Size of the avatar in pixels (it's a square).
        default (str): Default avatar to return if not found.

Returns:
        str: The URL to the avatar image.

Raises:
        ValueError: If neither email nor openid are provided.


def product_name(self):
    buf = (ctypes.c_char * self.MAX_BUF_SIZE)()
    self._dll.JLINKARM_EMU_GetProductName(buf, self.MAX_BUF_SIZE)
    return ctypes.string_at(buf).decode()

Returns the product name of the connected J-Link.

Args:
        self (JLink): the ``JLink`` instance

Returns:
        Product name.


def top(self, **kwargs):
    return self.client.api.top(self.id, **kwargs)

Display the running processes of the container.

Args:
        ps_args (str): An optional arguments passed to ps (e.g. ``aux``)

Returns:
        (str): The output of the top

Raises:
        :py:class:`docker.errors.APIError`
            If the server returns an error.


def _clone_and_score_clusterer(clf, X, n_clusters):
    start = time.time()
    clf = clone(clf)
    setattr(clf, 'n_clusters', n_clusters)
    return (clf.fit(X).score(X), (time.time() - start))

Clones and scores clusterer instance.

Args:
        clf: Clusterer instance that implements ``fit``,``fit_predict``, and
            ``score`` methods, and an ``n_clusters`` hyperparameter.
            e.g. :class:`sklearn.cluster.KMeans` instance

        X (array-like, shape (n_samples, n_features)):
            Data to cluster, where n_samples is the number of samples and
            n_features is the number of features.

        n_clusters (int): Number of clusters

Returns:
        score: Score of clusters

        time: Number of seconds it took to fit cluster


def generate_nb_data(P, R, n_cells, assignments=None):
    (genes, clusters) = P.shape
    output = np.zeros((genes, n_cells))
    if (assignments is None):
        cluster_probs = (np.ones(clusters) / clusters)
    labels = []
    for i in range(n_cells):
        if (assignments is None):
            c = np.random.choice(range(clusters), p=cluster_probs)
        else:
            c = assignments[i]
        labels.append(c)
        output[(:, i)] = np.random.negative_binomial(R[(:, c)], (1.0 - P[(:, c)]))
    return (output, np.array(labels))

Generates negative binomial data

Args:
        P (array): genes x clusters
        R (array): genes x clusters
        n_cells (int): number of cells
        assignments (list): cluster assignment of each cell. Default:
            random uniform

Returns:
        data array with shape genes x cells
        labels - array of cluster labels


def logs(self, **kwargs):
    return self.client.api.logs(self.id, **kwargs)

Get logs from this container. Similar to the ``docker logs`` command.

    The ``stream`` parameter makes the ``logs`` function return a blocking
    generator you can iterate over to retrieve log output as it happens.

Args:
        stdout (bool): Get ``STDOUT``. Default ``True``
        stderr (bool): Get ``STDERR``. Default ``True``
        stream (bool): Stream the response. Default ``False``
        timestamps (bool): Show timestamps. Default ``False``
        tail (str or int): Output specified number of lines at the end of
            logs. Either an integer of number of lines or the string
            ``all``. Default ``all``
        since (datetime or int): Show logs since a given datetime or
            integer epoch (in seconds)
        follow (bool): Follow log output. Default ``False``
        until (datetime or int): Show logs that occurred before the given
            datetime or integer epoch (in seconds)

Returns:
        (generator or str): Logs from the container.

Raises:
        :py:class:`docker.errors.APIError`
            If the server returns an error.


def Analyze(self, hashes):
    hash_analyses = []
    for digest in hashes:
        json_response = self._QueryHash(digest)
        hash_analysis = interface.HashAnalysis(digest, json_response)
        hash_analyses.append(hash_analysis)
    return hash_analyses

Looks up hashes in Viper using the Viper HTTP API.

Args:
        hashes (list[str]): hashes to look up.

Returns:
        list[HashAnalysis]: hash analysis.

Raises:
        RuntimeError: If no host has been set for Viper.


def _FormatHumanReadableSize(self, size):
    magnitude_1000 = 0
    size_1000 = float(size)
    while (size_1000 >= 1000):
        size_1000 /= 1000
        magnitude_1000 += 1
    magnitude_1024 = 0
    size_1024 = float(size)
    while (size_1024 >= 1024):
        size_1024 /= 1024
        magnitude_1024 += 1
    size_string_1000 = None
    if (0 < magnitude_1000 <= 7):
        size_string_1000 = '{0:.1f}{1:s}'.format(size_1000, self._UNITS_1000[magnitude_1000])
    size_string_1024 = None
    if (0 < magnitude_1024 <= 7):
        size_string_1024 = '{0:.1f}{1:s}'.format(size_1024, self._UNITS_1024[magnitude_1024])
    if ((not size_string_1000) or (not size_string_1024)):
        return '{0:d} B'.format(size)
    return '{0:s} / {1:s} ({2:d} B)'.format(size_string_1024, size_string_1000, size)

Represents a number of bytes as a human readable string.

Args:
        size (int): size in bytes.

Returns:
        str: human readable string of the size.


def merge_and_average(self, platform, expression_column, group_by_column, force=False, merge_on_column=None, gsm_on=None, gpl_on=None):
    if isinstance(platform, str):
        gpl = self.gpls[platform]
    elif isinstance(platform, GPL):
        gpl = platform
    else:
        raise ValueError('Platform has to be of type GPL or string with key for platform in GSE')
    data = []
    for gsm in self.gsms.values():
        if (gpl.name == gsm.metadata['platform_id'][0]):
            data.append(gsm.annotate_and_average(gpl=gpl, merge_on_column=merge_on_column, expression_column=expression_column, group_by_column=group_by_column, force=force, gpl_on=gpl_on, gsm_on=gsm_on))
    if (len(data) == 0):
        logger.warning('No samples for the platform were found\n')
        return None
    elif (len(data) == 1):
        return data[0]
    else:
        return data[0].join(data[1:])

Merge and average GSE samples.

    For given platform prepare the DataFrame with all the samples present in
    the GSE annotated with given column from platform and averaged over
    the column.

Args:
        platform (:obj:`str` or :obj:`GEOparse.GPL`): GPL platform to use.
        expression_column (:obj:`str`): Column name in which "expressions"
            are represented
        group_by_column (:obj:`str`): The data will be grouped and averaged
            over this column and only this column will be kept
        force (:obj:`bool`): If the name of the GPL does not match the
            platform name in GSM proceed anyway
        merge_on_column (:obj:`str`): Column to merge the data on - should
            be present in both GSM and GPL
        gsm_on (:obj:`str`): In the case columns to merge are different in
            GSM and GPL use this column in GSM
        gpl_on (:obj:`str`): In the case columns to merge are different in
            GSM and GPL use this column in GPL

Returns:
        :obj:`pandas.DataFrame`: Merged and averaged table of results.


def get_oauth_access_token(url, client_id, client_secret, token_type='jwt', grant_type='client_credentials', refresh_token=None):
    now = datetime.datetime.utcnow()
    data = {'grant_type': grant_type, 'client_id': client_id, 'client_secret': client_secret, 'token_type': token_type}
    if refresh_token:
        data['refresh_token'] = refresh_token
    else:
        assert (grant_type != 'refresh_token'), 'refresh_token parameter required'
    response = requests.post(url, data=data, headers={'User-Agent': USER_AGENT})
    data = response.json()
    try:
        access_token = data['access_token']
        expires_in = data['expires_in']
    except KeyError:
        raise requests.RequestException(response=response)
    expires_at = (now + datetime.timedelta(seconds=expires_in))
    return (access_token, expires_at)

Retrieves OAuth 2.0 access token using the given grant type.

Args:
        url (str): Oauth2 access token endpoint
        client_id (str): client ID
        client_secret (str): client secret
    Kwargs:
        token_type (str): Type of token to return. Options include bearer and jwt.
        grant_type (str): One of 'client_credentials' or 'refresh_token'
        refresh_token (str): The previous access token (for grant_type=refresh_token)

Returns:
        tuple: Tuple containing access token string and expiration datetime.


def update(self, resource, timeout=(- 1)):
    return self._client.update(resource, timeout=timeout, default_values=self.DEFAULT_VALUES, uri=self.URI)

Updates a User.

Args:
        resource (dict): Object to update.
        timeout:
            Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
            in OneView, just stop waiting for its completion.

Returns:
        dict: Updated resource.


def split_by_proportionally_distribute_labels(self, proportions={}, use_lengths=True):
    identifiers = {}
    for utterance in self.corpus.utterances.values():
        if use_lengths:
            identifiers[utterance.idx] = {l: int((d * 100)) for (l, d) in utterance.label_total_duration().items()}
        else:
            identifiers[utterance.idx] = utterance.label_count()
    splits = utils.get_identifiers_splitted_by_weights(identifiers, proportions)
    return self._subviews_from_utterance_splits(splits)

Split the corpus into subsets, so the occurrence of the labels is distributed amongst the
    subsets according to the given proportions.

Args:
        proportions (dict): A dictionary containing the relative size of the target subsets.
                            The key is an identifier for the subset.
        use_lengths (bool): If True the lengths of the labels are considered for splitting proportionally,
                            otherwise only the number of occurrences is taken into account.

Returns:
        (dict): A dictionary containing the subsets with the identifier from the input as key.


def to(self, fmt=None, filename=None, **kwargs):
    filename = (filename or '')
    fmt = ('' if (fmt is None) else fmt.lower())
    fname = os.path.basename(filename)
    if ((fmt == 'cif') or fnmatch(fname.lower(), '*.cif*')):
        from pymatgen.io.cif import CifWriter
        writer = CifWriter(self, **kwargs)
    elif ((fmt == 'mcif') or fnmatch(fname.lower(), '*.mcif*')):
        from pymatgen.io.cif import CifWriter
        writer = CifWriter(self, write_magmoms=True, **kwargs)
    elif ((fmt == 'poscar') or fnmatch(fname, '*POSCAR*')):
        from pymatgen.io.vasp import Poscar
        writer = Poscar(self, **kwargs)
    elif ((fmt == 'cssr') or fnmatch(fname.lower(), '*.cssr*')):
        from pymatgen.io.cssr import Cssr
        writer = Cssr(self, **kwargs)
    elif ((fmt == 'json') or fnmatch(fname.lower(), '*.json')):
        s = json.dumps(self.as_dict())
        if filename:
            with zopen(filename, 'wt') as f:
                f.write(('%s' % s))
        return s
    elif ((fmt == 'xsf') or fnmatch(fname.lower(), '*.xsf*')):
        from pymatgen.io.xcrysden import XSF
        s = XSF(self).to_string()
        if filename:
            with zopen(fname, 'wt', encoding='utf8') as f:
                f.write(s)
        return s
    elif ((fmt == 'mcsqs') or fnmatch(fname, '*rndstr.in*') or fnmatch(fname, '*lat.in*') or fnmatch(fname, '*bestsqs*')):
        from pymatgen.io.atat import Mcsqs
        s = Mcsqs(self).to_string()
        if filename:
            with zopen(fname, 'wt', encoding='ascii') as f:
                f.write(s)
        return s
    else:
        import ruamel.yaml as yaml
        if filename:
            with zopen(filename, 'wt') as f:
                yaml.safe_dump(self.as_dict(), f)
            return
        else:
            return yaml.safe_dump(self.as_dict())
    if filename:
        writer.write_file(filename)
    else:
        return writer.__str__()

Outputs the structure to a file or string.

Args:
        fmt (str): Format to output to. Defaults to JSON unless filename
            is provided. If fmt is specifies, it overrides whatever the
            filename is. Options include "cif", "poscar", "cssr", "json".
            Non-case sensitive.
        filename (str): If provided, output will be written to a file. If
            fmt is not specified, the format is determined from the
            filename. Defaults is None, i.e. string output.
        \\*\\*kwargs: Kwargs passthru to relevant methods. E.g., This allows
            the passing of parameters like symprec to the
            CifWriter.__init__ method for generation of symmetric cifs.

Returns:
        (str) if filename is None. None otherwise.


def get_path(name, *default):
    global g_config
    value = get(name, *default)
    if (value is None):
        return None
    return proj_path(value)

Get config value as path relative to the project directory.

    This allows easily defining the project configuration within the fabfile
    as always relative to that fabfile.

Args:
        name (str):
            The name of the config value containing the path.
        *default (Any):
            If given and the key doesn't not exist, this will be returned
            instead. If it's not given and the config value does not exist,
            AttributeError will be raised

Returns:
        The requested config value. This is one of the global values defined
        in this file. If the value does not exist it will return `default` if
        give or raise `AttributeError`.

Raises:
        AttributeError: If the value does not exist and `default` was not given.


def PauliX(local_space, states=None):
    (local_space, states) = _get_pauli_args(local_space, states)
    (g, e) = states
    return (LocalSigma.create(g, e, hs=local_space) + LocalSigma.create(e, g, hs=local_space))

r"""Pauli-type X-operator

    .. math::

        \hat{\sigma}_x = \begin{pmatrix}
            0 & 1 \\
            1 & 0
        \end{pmatrix}

    on an arbitrary two-level system.

Args:
        local_space (str or int or .LocalSpace): Associated Hilbert space.
            If :class:`str` or :class:`int`, a :class:`LocalSpace` with a
            matching label will be created.
        states (None or tuple[int or str]): The labels for the basis states
            for the two levels on which the operator acts. If None, the two
            lowest levels are used.

Returns:
        Operator: Local X-operator as a linear combination of
        :class:`LocalSigma`


def region(self, start=0, end=None):
    if (end is None):
        end = len(self.sequence)
    return '>{}\n{}'.format(self.id, self.sequence[start:end])

Returns a region of ``Sequence.sequence``, in FASTA format.

    If called without kwargs, the entire sequence will be returned.

Args:
        start (int): Start position of the region to be returned. Default
            is 0.

        end (int): End position of the region to be returned. Negative values
            will function as they do when slicing strings.

Returns:
        str: A region of ``Sequence.sequence``, in FASTA format


def refs(self, type='all', **kwargs):
    path = ('%s/%s/refs' % (self.manager.path, self.get_id()))
    data = {'type': type}
    return self.manager.gitlab.http_get(path, query_data=data, **kwargs)

List the references the commit is pushed to.

Args:
        type (str): The scope of references ('branch', 'tag' or 'all')
        **kwargs: Extra options to send to the server (e.g. sudo)

Raises:
        GitlabAuthenticationError: If authentication is not correct
        GitlabGetError: If the references could not be retrieved

Returns:
        list: The references the commit is pushed to.


def download_file(self, path, target_path):
    self.__validate_storage_path(path)
    entity = self.api_client.get_entity_by_query(path=path)
    if (entity['entity_type'] != 'file'):
        raise StorageArgumentException('Only file entities can be downloaded')
    signed_url = self.api_client.get_signed_url(entity['uuid'])
    response = self.api_client.download_signed_url(signed_url)
    with open(target_path, 'wb') as output:
        for chunk in response.iter_content(chunk_size=1024):
            output.write(chunk)

Download a file from storage service to local disk.

    Existing files on the target path will be overwritten.
    The download is not recursive, as it only works on files.

Args:
        path (str): The path of the entity to be downloaded. Must start with a '/'.

Returns:
        None

Raises:
        StorageArgumentException: Invalid arguments
        StorageForbiddenException: Server response code 403
        StorageNotFoundException: Server response code 404
        StorageException: other 400-600 error codes


def requirements(requirements_file):
    return [str(pkg.req) for pkg in parse_requirements(requirements_file, session=pip_download.PipSession()) if (pkg.req is not None)]

Return packages mentioned in the given file.

Args:
        requirements_file (str): path to the requirements file to be parsed.

Returns:
        (list): 3rd-party package dependencies contained in the file.


def fprime(self, w, *args):
    x0 = args[0]
    x1 = args[1]
    n0 = x0.shape[0]
    n1 = x1.shape[0]
    n = (max(n0, n1) * 10)
    idx0 = np.random.choice(range(n0), size=n)
    idx1 = np.random.choice(range(n1), size=n)
    b = np.ones((n, 1))
    i1 = (self.i + 1)
    h = self.h
    h1 = (h + 1)
    w2 = w[(- h1):].reshape(h1, 1)
    w1 = w[:(- h1)].reshape(i1, h)
    if sparse.issparse(x0):
        x0 = x0.tocsr()[idx0]
        x1 = x1.tocsr()[idx1]
        xb0 = sparse.hstack((x0, b))
        xb1 = sparse.hstack((x1, b))
    else:
        x0 = x0[idx0]
        x1 = x1[idx1]
        xb0 = np.hstack((x0, b))
        xb1 = np.hstack((x1, b))
    z0 = np.hstack((sigm(xb0.dot(w1)), b))
    z1 = np.hstack((sigm(xb1.dot(w1)), b))
    y0 = z0.dot(w2)
    y1 = z1.dot(w2)
    e = (1 - (y1 - y0))
    dy = (e / n)
    dw1 = ((- (xb1.T.dot((dy.dot(w2[:(- 1)].reshape(1, h)) * dsigm(xb1.dot(w1)))) - xb0.T.dot((dy.dot(w2[:(- 1)].reshape(1, h)) * dsigm(xb0.dot(w1))))).reshape((i1 * h))) + ((self.l1 * w[:(- h1)]) / (i1 * h)))
    dw2 = ((- (z1 - z0).T.dot(dy).reshape(h1)) + ((self.l2 * w[(- h1):]) / h1))
    return np.append(dw1, dw2)

Return the derivatives of the cost function for predictions.

Args:
        w (array of float): weight vectors such that:
            w[:-h1] -- weights between the input and h layers
            w[-h1:] -- weights between the h and output layers
        args: features (args[0]) and target (args[1])

Returns:
        gradients of the cost function for predictions


def _build_key_wrapping_specification(self, value):
    if (value is None):
        return None
    if (not isinstance(value, dict)):
        raise TypeError('Key wrapping specification must be a dictionary.')
    encryption_key_info = self._build_encryption_key_information(value.get('encryption_key_information'))
    mac_signature_key_info = self._build_mac_signature_key_information(value.get('mac_signature_key_information'))
    key_wrapping_specification = cobjects.KeyWrappingSpecification(wrapping_method=value.get('wrapping_method'), encryption_key_information=encryption_key_info, mac_signature_key_information=mac_signature_key_info, attribute_names=value.get('attribute_names'), encoding_option=value.get('encoding_option'))
    return key_wrapping_specification

Build a KeyWrappingSpecification struct from a dictionary.

Args:
        value (dict): A dictionary containing the key/value pairs for a
            KeyWrappingSpecification struct.

Returns:
        KeyWrappingSpecification: a KeyWrappingSpecification struct

Raises:
        TypeError: if the input argument is invalid


def renderJsonReadsSince(self, timestamp, meter):
    result = ''
    try:
        connection = sqlite3.connect(self.m_connection_string)
        connection.row_factory = self.dict_factory
        select_cursor = connection.cursor()
        select_cursor.execute((((((((('select * from Meter_Reads where ' + Field.Time_Stamp) + ' > ') + str(timestamp)) + ' and ') + Field.Meter_Address) + "= '") + meter) + "';"))
        reads = select_cursor.fetchall()
        result = json.dumps(reads, indent=4)
    except:
        ekm_log(traceback.format_exc(sys.exc_info()))
    return result

Simple since Time_Stamp query returned as JSON records.

Args:
        timestamp (int): Epoch time in seconds.
        meter (str): 12 character meter address to query

Returns:
        str: JSON rendered read records.


def update(self, car_id=None, wake_if_asleep=False, force=False):
    cur_time = time.time()
    with self.__lock:
        last_update = self._last_attempted_update_time
        if (force or ((cur_time - last_update) > self.update_interval)):
            cars = self.get_vehicles()
            for car in cars:
                self.car_online[car['id']] = (car['state'] == 'online')
            self._last_attempted_update_time = cur_time
        update_succeeded = False
        for (id_, value) in self.car_online.items():
            if ((car_id is not None) and (car_id != id_)):
                continue
            if (value and ((id_ in self.__update) and self.__update[id_]) and (force or (id_ not in self._last_update_time) or ((cur_time - self._last_update_time[id_]) > self.update_interval))):
                try:
                    data = self.get(id_, 'data', wake_if_asleep)
                except TeslaException:
                    data = None
                if (data and data['response']):
                    response = data['response']
                    self.__climate[car_id] = response['climate_state']
                    self.__charging[car_id] = response['charge_state']
                    self.__state[car_id] = response['vehicle_state']
                    self.__driving[car_id] = response['drive_state']
                    self.__gui[car_id] = response['gui_settings']
                    self.car_online[car_id] = (response['state'] == 'online')
                    self._last_update_time[car_id] = time.time()
                    update_succeeded = True
        return update_succeeded

Update all vehicle attributes in the cache.

    This command will connect to the Tesla API and first update the list of
    online vehicles assuming no attempt for at least the [update_interval].
    It will then update all the cached values for cars that are awake
    assuming no update has occurred for at least the [update_interval].

Args:
    inst (Controller): The instance of a controller
    car_id (string): The vehicle to update. If None, all cars are updated.
    wake_if_asleep (bool): Keyword arg to force a vehicle awake. This is
                        processed by the wake_up decorator.
    force (bool): Keyword arg to force a vehicle update regardless of the
                update_interval

Returns:
    True if any update succeeded for any vehicle else false

    Throws:
    RetryLimitError


def get_language(self, text):
    files = {'text': text}
    (res, status_code) = self.post(self.language_service, files=files)
    if (status_code != 200):
        logger.debug('Language recognition failed.')
    return (self.decode(res), status_code)

Recognise the language of the text in input

Args:
        id (str): The text whose the language needs to be recognised

Returns:
        dict, int: A dict containing the recognised language and the
            confidence score.


def generate_password(length=32):
    return ''.join((random.SystemRandom().choice((string.ascii_letters + '!@#$+.,')) for _ in range(length)))

Generate a cryptographically secure random string to use for passwords

Args:
        length (int): Length of password, defaults to 32 characters

Returns:
        Randomly generated string


def add_region_location(self, region, locations=None, use_live=True):
    return self.add_country_locations(Country.get_countries_in_region(region, exception=HDXError, use_live=use_live), locations=locations)

Add all countries in a region. If a 3 digit UNStats M49 region code is not provided, value is parsed as a
    region name. If any country is already added, it is ignored.

Args:
        region (str): M49 region, intermediate region or subregion to add
        locations (Optional[List[str]]): Valid locations list. Defaults to list downloaded from HDX.
        use_live (bool): Try to get use latest country data from web rather than file in package. Defaults to True.

Returns:
        bool: True if all countries in region added or False if any already present.


def exists(self, path):
    self.__validate_storage_path(path)
    try:
        metadata = self.api_client.get_entity_by_query(path=path)
    except StorageNotFoundException:
        return False
    return (metadata and ('uuid' in metadata))

Check if a certain path exists in the storage service.

Args:
        path (str): The path to be checked

Returns:
        True if the path exists, False otherwise

Raises:
        StorageArgumentException: Invalid arguments
        StorageForbiddenException: Server response code 403
        StorageNotFoundException: Server response code 404
        StorageException: other 400-600 error codes


def controller_factory(cls, passes, options, **partial_controller):
    if (None in partial_controller.values()):
        raise TranspilerError('The controller needs a condition.')
    if partial_controller:
        for registered_controller in cls.registered_controllers.keys():
            if (registered_controller in partial_controller):
                return cls.registered_controllers[registered_controller](passes, options, **partial_controller)
        raise TranspilerError(('The controllers for %s are not registered' % partial_controller))
    else:
        return FlowControllerLinear(passes, options)

Constructs a flow controller based on the partially evaluated controller arguments.

Args:
        passes (list[BasePass]): passes to add to the flow controller.
        options (dict): PassManager options.
        **partial_controller (dict): Partially evaluated controller arguments in the form
            `{name:partial}`

Raises:
        TranspilerError: When partial_controller is not well-formed.

Returns:
        FlowController: A FlowController instance.


def create(self, resource):
    return self.service.create(resource, self.url_prefix, self.auth, self.session, self.session_send_opts)

Create the given resource.

Args:
        resource (intern.resource.boss.BossResource): Create a data model object with attributes matching those of the resource.

Returns:
        (intern.resource.boss.BossResource): Returns resource of type requested on success.

Raises:
        requests.HTTPError on failure.


def _BuildFindSpecsFromRegistrySourceKey(self, key_path):
    find_specs = []
    for key_path_glob in path_helper.PathHelper.ExpandRecursiveGlobs(key_path, '\\'):
        logger.debug('building find spec from key path glob: {0:s}'.format(key_path_glob))
        key_path_glob_upper = key_path_glob.upper()
        if key_path_glob_upper.startswith('HKEY_USERS\\%%USERS.SID%%'):
            key_path_glob = 'HKEY_CURRENT_USER{0:s}'.format(key_path_glob[26:])
        find_spec = registry_searcher.FindSpec(key_path_glob=key_path_glob)
        find_specs.append(find_spec)
    return find_specs

Build find specifications from a Windows Registry source type.

Args:
        key_path (str): Windows Registry key path defined by the source.

Returns:
        list[dfwinreg.FindSpec]: find specifications for the Windows Registry
        source type.


def xldate_as_datetime(xldate, datemode=0, option='to_datetime'):
    if (option == 'to_float'):
        d = ((xldate - 25589) * 86400.0)
    else:
        try:
            d = (datetime.datetime(1899, 12, 30) + datetime.timedelta(days=(xldate + (1462 * datemode))))
            if (option == 'to_string'):
                date_format = '%Y-%m-%d %H:%M:%S'
                d = d.strftime(date_format)
        except TypeError:
            logging.info(f'The date is not of correct type [{xldate}]')
            d = xldate
    return d

Converts a xls date stamp to a more sensible format.

Args:
        xldate (str): date stamp in Excel format.
        datemode (int): 0 for 1900-based, 1 for 1904-based.
        option (str): option in ("to_datetime", "to_float", "to_string"),
            return value

Returns:
        datetime (datetime object, float, or string).


def _generate_legacy_type_checks(types=()):
    types = dict(types)

    def gen_type_check(pytypes):
        pytypes = _utils.flatten(pytypes)

        def type_check(checker, instance):
            if isinstance(instance, bool):
                if (bool not in pytypes):
                    return False
            return isinstance(instance, pytypes)
        return type_check
    definitions = {}
    for (typename, pytypes) in iteritems(types):
        definitions[typename] = gen_type_check(pytypes)
    return definitions

Generate newer-style type checks out of JSON-type-name-to-type mappings.

Args:
        types (dict):

            A mapping of type names to their Python types

Returns:
        A dictionary of definitions to pass to `TypeChecker`


def _BuildFindSpecsFromFileSourcePath(self, source_path, path_separator, environment_variables, user_accounts):
    find_specs = []
    for path_glob in path_helper.PathHelper.ExpandRecursiveGlobs(source_path, path_separator):
        logger.debug('building find spec from path glob: {0:s}'.format(path_glob))
        for path in path_helper.PathHelper.ExpandUsersVariablePath(path_glob, path_separator, user_accounts):
            logger.debug('building find spec from path: {0:s}'.format(path))
            if ('%' in path):
                path = path_helper.PathHelper.ExpandWindowsPath(path, environment_variables)
                logger.debug('building find spec from expanded path: {0:s}'.format(path))
            if (not path.startswith(path_separator)):
                logger.warning('The path filter must be defined as an absolute path: "{0:s}"'.format(path))
                continue
            path_segments = path.split(path_separator)
            path_segments.pop(0)
            if (not path_segments[(- 1)]):
                logger.warning('Empty last path segment in path filter: "{0:s}"'.format(path))
                path_segments.pop((- 1))
            try:
                find_spec = file_system_searcher.FindSpec(location_glob=path_segments, case_sensitive=False)
            except ValueError as exception:
                logger.error('Unable to build find specification for path: "{0:s}" with error: {1!s}'.format(path, exception))
                continue
            find_specs.append(find_spec)
    return find_specs

Builds find specifications from a file source type.

Args:
        source_path (str): file system path defined by the source.
        path_separator (str): file system path segment separator.
        environment_variables (list[str]): environment variable attributes used to
        dynamically populate environment variables in key.
        user_accounts (list[str]): identified user accounts stored in the
        knowledge base.

Returns:
        list[dfvfs.FindSpec]: find specifications for the file source type.


def random_density_matrix(length, rank=None, method='Hilbert-Schmidt', seed=None):
    if (method == 'Hilbert-Schmidt'):
        return __random_density_hs(length, rank, seed)
    elif (method == 'Bures'):
        return __random_density_bures(length, rank, seed)
    else:
        raise QiskitError('Error: unrecognized method {}'.format(method))

Generate a random density matrix rho.

Args:
        length (int): the length of the density matrix.
        rank (int or None): the rank of the density matrix. The default
            value is full-rank.
        method (string): the method to use.
            'Hilbert-Schmidt': sample rho from the Hilbert-Schmidt metric.
            'Bures': sample rho from the Bures metric.
        seed (int): Optional. To set a random seed.

Returns:
        ndarray: rho (length, length) a density matrix.

Raises:
        QiskitError: if the method is not valid.


def write_content(self, content, destination):
    directory = os.path.dirname(destination)
    if (directory and (not os.path.exists(directory))):
        os.makedirs(directory)
    with io.open(destination, 'w', encoding='utf-8') as f:
        f.write(content)
    return destination

Write given content to destination path.

    It will create needed directory structure first if it contain some
    directories that does not allready exists.

Args:
        content (str): Content to write to target file.
        destination (str): Destination path for target file.

Returns:
        str: Path where target file has been written.


def has_no_title(self, title, **kwargs):
    try:
        self.assert_no_title(title, **kwargs)
        return True
    except ExpectationNotMet:
        return False

Checks if the page doesn't have the given title.

Args:
        title (str | RegexObject): The string that the title should include.
        **kwargs: Arbitrary keyword arguments for :class:`TitleQuery`.

Returns:
        bool: Whether it doesn't match.


def sample(self, size=None):
    self._recompute()
    if (size is None):
        n = np.random.randn(len(self._t))
    else:
        n = np.random.randn(len(self._t), size)
    n = self.solver.dot_L(n)
    if (size is None):
        return (self.mean.get_value(self._t) + n[(:, 0)])
    return (self.mean.get_value(self._t)[(None, :)] + n.T)

Sample from the prior distribution over datasets

Args:
        size (Optional[int]): The number of samples to draw.

Returns:
        array[n] or array[size, n]: The samples from the prior
        distribution over datasets.


def cartesian(shape):
    n = len(shape)
    idx = [slice(0, s) for s in shape]
    g = rollaxis(mgrid[idx], 0, (n + 1))
    return g.reshape((prod(shape), n))

r"""Cartesian indexing.

    Returns a sequence of n-tuples indexing each element of a hypothetical
    matrix of the given shape.

Args:
        shape (tuple): tuple of dimensions.

Returns:
        array_like: indices.

    Example
    -------

    .. doctest::

        >>> from numpy_sugar import cartesian
        >>> print(cartesian((2, 3)))
        [[0 0]
        [0 1]
        [0 2]
        [1 0]
        [1 1]
        [1 2]]

    Reference:

    [1] http://stackoverflow.com/a/27286794


def get_parents_graph(self, item_ids, language=None):

    def _parents(item_ids):
        if (item_ids is None):
            items = Item.objects.filter(active=True).prefetch_related('parents')
        else:
            item_ids = [ii for iis in item_ids.values() for ii in iis]
            items = Item.objects.filter(id__in=item_ids, active=True).prefetch_related('parents')
        return {item.id: sorted([_item.id for _item in item.parents.all()]) for item in items}
    return self._reachable_graph(item_ids, _parents, language=language)
    if (item_ids is None):
        return self._reachable_graph(None, _parents, language=language)
    else:
        graph = self.get_parents_graph(None, language)
        return self._subset_graph(graph, item_ids)

Get a subgraph of items reachable from the given set of items through
    the 'parent' relation.

Args:
        item_ids (list): items which are taken as roots for the reachability
        language (str): if specified, filter out items which are not
            available in the given language

Returns:
        dict: item id -> list of items (parent items), root items are
        referenced by None key


def _abort_workflow(pb: ProcessingBlock, workflow_stage_dict: dict, docker: DockerSwarmClient):
    _abort_flag = False
    if _abort_flag:
        for workflow_stage in pb.workflow_stages:
            for (service_id, _) in workflow_stage_dict[workflow_stage.id]['services'].items():
                docker.delete_service(service_id)
                LOG.info('Deleted Service Id %s', service_id)
        return True
    return False

Abort the workflow.

    TODO(BMo): This function currently does nothing as the abort flag
        is hardcoded to False!

    This function is used by `execute_processing_block`.

Args:
        pb (ProcessingBlock): Configuration database Processing block object.
        workflow_stage_dict (dict): Workflow stage metadata dictionary.
        docker (DockerClient): Docker Swarm Client object.

Returns:
        bool, True if the stage is aborted, otherwise False.


def block_start(self, previous_block):
    previous_header_bytes = previous_block.header
    previous_header = BlockHeader()
    previous_header.ParseFromString(previous_header_bytes)
    block_info = BlockInfo(block_num=previous_header.block_num, previous_block_id=previous_header.previous_block_id, signer_public_key=previous_header.signer_public_key, header_signature=previous_block.header_signature, timestamp=int(time.time()))
    return [self.create_batch(block_info)]

Returns an ordered list of batches to inject at the beginning of the
    block. Can also return None if no batches should be injected.

Args:
        previous_block (Block): The previous block.

Returns:
        A list of batches to inject.


def _get_kernel_data(self, nmr_samples, thinning, return_output):
    kernel_data = {'data': self._data, 'method_data': self._get_mcmc_method_kernel_data(), 'nmr_iterations': Scalar((nmr_samples * thinning), ctype='ulong'), 'iteration_offset': Scalar(self._sampling_index, ctype='ulong'), 'rng_state': Array(self._rng_state, 'uint', mode='rw', ensure_zero_copy=True), 'current_chain_position': Array(self._current_chain_position, 'mot_float_type', mode='rw', ensure_zero_copy=True), 'current_log_likelihood': Array(self._current_log_likelihood, 'mot_float_type', mode='rw', ensure_zero_copy=True), 'current_log_prior': Array(self._current_log_prior, 'mot_float_type', mode='rw', ensure_zero_copy=True)}
    if return_output:
        kernel_data.update({'samples': Zeros((self._nmr_problems, self._nmr_params, nmr_samples), ctype='mot_float_type'), 'log_likelihoods': Zeros((self._nmr_problems, nmr_samples), ctype='mot_float_type'), 'log_priors': Zeros((self._nmr_problems, nmr_samples), ctype='mot_float_type')})
    return kernel_data

Get the kernel data we will input to the MCMC sampler.

    This sets the items:

    * data: the pointer to the user provided data
    * method_data: the data specific to the MCMC method
    * nmr_iterations: the number of iterations to sample
    * iteration_offset: the current sample index, that is, the offset to the given number of iterations
    * rng_state: the random number generator state
    * current_chain_position: the current position of the sampled chain
    * current_log_likelihood: the log likelihood of the current position on the chain
    * current_log_prior: the log prior of the current position on the chain

    Additionally, if ``return_output`` is True, we add to that the arrays:

    * samples: for the samples
    * log_likelihoods: for storing the log likelihoods
    * log_priors: for storing the priors

Args:
        nmr_samples (int): the number of samples we will draw
        thinning (int): the thinning factor we want to use
        return_output (boolean): if the kernel should return output

Returns:
        dict[str: mot.lib.utils.KernelData]: the kernel input data


def most_exposes(python_type):
    _exposes = set()
    try:
        do_not_expose = set((python_type.__dir__(object) + ['__slots__', '__module__', '__weakref__']))
        empty = python_type.__new__(python_type)
    except AttributeError:
        try:
            _exposes = python_type.__slots__
        except AttributeError:
            pass
    except TypeError:
        for _workaround in storable_workarounds:
            try:
                _exposes = _workaround(python_type)
            except (SystemExit, KeyboardInterrupt):
                raise
            except:
                pass
            else:
                break
    else:
        all_members = empty.__dir__()
        for attr in all_members:
            if (attr in do_not_expose):
                continue
            try:
                getattr(empty, attr)
            except AttributeError as e:
                if e.args:
                    msg = e.args[0]
                    if ((msg == attr) or msg.endswith("' object has no attribute '{}'".format(attr))):
                        _exposes.add(attr)
            except (SystemExit, KeyboardInterrupt):
                raise
            except:
                pass
        for attr in ('__dict__',):
            if (attr in all_members):
                _exposes.add(attr)
    return list(_exposes)

Core engine for the automatic generation of storable instances.

    Finds the attributes exposed by the objects of a given type.

    Mostly Python3-only.
    Does not handle types which `__new__` method requires extra arguments either.

Args:
        python_type (type): object type.

Returns:
        list: attributes exposed.


def request(self, path, data=None, headers=None, method=None):
    if isinstance(data, str):
        data = data.encode('utf-8')
    response = urlopen(self._request(path, data=data, headers=headers, method=method))
    self._set_session_cookie(response)
    return response

Performs a HTTP request to the Go server

Args:
        path (str): The full path on the Go server to request.
        This includes any query string attributes.
        data (str, dict, bool, optional): If any data is present this
        request will become a POST request.
        headers (dict, optional): Headers to set for this particular
        request

Raises:
        HTTPError: when the HTTP request fails.

Returns:
        file like object: The response from a
        :func:`urllib2.urlopen` call


def response_data_to_model_instance(self, response_data):
    response_data['datetime_created'] = dateutil.parser.parse(response_data['datetime_created'])
    if response_data['datetime_finished']:
        response_data['datetime_finished'] = dateutil.parser.parse(response_data['datetime_finished'])
    return super(BaseTaskInstanceManager, self).response_data_to_model_instance(response_data)

Convert response data to a task instance model.

Args:
        response_data (dict): The data from the request's response.

Returns:
        :class:`saltant.models.base_task_instance.BaseTaskInstance`:
            A task instance model instance representing the task
            instance from the reponse data.


def read_var_bytes(self, max_size=sys.maxsize) -> bytes:
    length = self.read_var_int(max_size)
    return self.read_bytes(length)

Read a variable length of bytes from the stream.

Args:
        max_size (int): (Optional) maximum number of bytes to read.

Returns:
        bytes:


def _init_index(root_dir, schema, index_name):
    index_dir = os.path.join(root_dir, index_name)
    try:
        if (not os.path.exists(index_dir)):
            os.makedirs(index_dir)
            return (create_in(index_dir, schema), index_dir)
        else:
            return (open_dir(index_dir), index_dir)
    except Exception as e:
        logger.error("Init error: failed to open search index at: '{}': {} ".format(index_dir, e))
        raise

Creates new index or opens existing.

Args:
        root_dir (str): root dir where to find or create index.
        schema (whoosh.fields.Schema): schema of the index to create or open.
        index_name (str): name of the index.

Returns:
        tuple ((whoosh.index.FileIndex, str)): first element is index, second is index directory.


def execute(self, asm_instr):
    self.ir_emulator.registers[self.ip] = (asm_instr.address + asm_instr.size)
    if self.arch_info.instr_is_syscall(asm_instr):
        raise Syscall()
    return self.__execute(asm_instr)

Execute an assembler instruction.

Args:
        asm_instr (X86Instruction): A instruction to execute.

Returns:
        A int. The address of the next instruction to execute.


def contains(self, rect):
    return ((rect.y >= self.y) and (rect.x >= self.x) and ((rect.y + rect.height) <= (self.y + self.height)) and ((rect.x + rect.width) <= (self.x + self.width)))

Tests if another rectangle is contained by this one

Args:
        rect (Rectangle): The other rectangle

Returns:
        bool: True if it is container, False otherwise


def delete_folder(self, folder_id, recursive=True):
    return self.__request('DELETE', ('folders/%s' % (folder_id,)), querystring={'recursive': unicode(recursive).lower()})

Delete an existing folder

Args:
        folder_id (int): ID of the folder to delete.
        recursive (bool): Delete all subfolder if True.

Returns:
        dict. Response from Box.

Raises:
        BoxError: An error response is returned from Box (status_code >= 400).

        BoxHttpResponseError: Response from Box is malformed.

        requests.exceptions.*: Any connection related problem.


def sparse_segment(cords):
    cords = (np.array(cords) + 1)
    slices = []
    for cord in cords:
        slices.append(slice(1, ((2 ** cord) + 1), 2))
    grid = np.mgrid[slices]
    indices = grid.reshape(len(cords), np.prod(grid.shape[1:])).T
    sgrid = (indices * (2.0 ** (- cords)))
    return sgrid

r"""
    Create a segment of a sparse grid.

    Convert a ol-index to sparse grid coordinates on ``[0, 1]^N`` hyper-cube.
    A sparse grid of order ``D`` coencide with the set of sparse_segments where
    ``||cords||_1 <= D``.

    More specifically, a segment of:

    .. math::
        \cup_{cords \in C} sparse_segment(cords) == sparse_grid(M)

    where:

    .. math::
        C = {cords: M=sum(cords)}

Args:
        cords (numpy.ndarray):
            The segment to extract. ``cord`` must consist of non-negative
            integers.

Returns:
        Q (numpy.ndarray):
            Sparse segment where ``Q.shape==(K, sum(M))`` and ``K`` is segment
            specific.

Example:
        >>> print(cp.bertran.sparse_segment([0, 2]))
        [[0.5   0.125]
        [0.5   0.375]
        [0.5   0.625]
        [0.5   0.875]]
        >>> print(cp.bertran.sparse_segment([0, 1, 0, 0]))
        [[0.5  0.25 0.5  0.5 ]
        [0.5  0.75 0.5  0.5 ]]


def filter(self, limit=None, to=None, category=None):
    if (category and (not to)):
        msg_slice = itertools.islice((x for x in self.store if (x[2] == category)), limit)
    elif (to and (not category)):
        to = JID.fromstr(to)
        msg_slice = itertools.islice((x for x in self.store if _agent_in_msg(to, x[1])), limit)
    elif (to and category):
        to = JID.fromstr(to)
        msg_slice = itertools.islice((x for x in self.store if (_agent_in_msg(to, x[1]) and (x[2] == category))), limit)
    else:
        msg_slice = self.all(limit=limit)
        return msg_slice
    return list(msg_slice)[::(- 1)]

Returns the events that match the filters

Args:
        limit (int, optional): the max length of the events to return (Default value = None)
        to (str, optional): only events that have been sent or received by 'to' (Default value = None)
        category (str, optional): only events belonging to the category (Default value = None)

Returns:
        list: a list of filtered events


def remove_redistribution(self, protocol):
    protocols = ['bgp', 'rip', 'static', 'connected']
    if (protocol not in protocols):
        raise ValueError('redistributed protocol must bebgp, connected, rip or static')
    cmd = 'no redistribute {}'.format(protocol)
    return self.configure_ospf(cmd)

Removes a protocol redistribution to OSPF

Args:
        protocol (str):  protocol to redistribute
        route_map_name (str): route-map to be used to
                            filter the protocols

Returns:
        bool: True if the command completes successfully
    Exception:
        ValueError:  This will be raised if the protocol pass is not one
                    of the following: [rip, bgp, static, connected]


def _copy_delpoy_scripts(self, scripts):
    if (not os.path.exists(self.paths.scripts())):
        os.makedirs(self.paths.scripts())
    new_scripts = []
    for script in scripts:
        script = os.path.expandvars(script)
        if (not os.path.exists(script)):
            raise RuntimeError(('Script %s does not exist' % script))
        sanitized_name = script.replace('/', '_')
        new_script_cur_path = os.path.expandvars(self.paths.scripts(sanitized_name))
        shutil.copy(script, new_script_cur_path)
        new_script_init_path = os.path.join('$LAGO_PREFIX_PATH', os.path.basename(self.paths.scripts()), sanitized_name)
        new_scripts.append(new_script_init_path)
    return new_scripts

Copy the given deploy scripts to the scripts dir in the prefix

Args:
        scripts(list of str): list of paths of the scripts to copy to the
            prefix

Returns:
        list of str: list with the paths to the copied scripts, with a
            prefixed with $LAGO_PREFIX_PATH so the full path is not
            hardcoded


def get_student_by_email(self, email, students=None):
    if (students is None):
        students = self.get_students()
    email = email.lower()
    for student in students:
        if (student['accountEmail'].lower() == email):
            return (student['studentId'], student)
    return (None, None)

Get a student based on an email address.

    Calls ``self.get_students()`` to get list of all students,
    if not passed as the ``students`` parameter.

Args:
        email (str): student email
        students (list): dictionary of students to search, default: None
            When ``students`` is unspecified, all students in gradebook
            are retrieved.

Raises:
        requests.RequestException: Exception connection error
        ValueError: Unable to decode response content

Returns:
        tuple: tuple of student id and student dictionary.


def get_vulnerability(source, sink, triggers, lattice, cfg, interactive, blackbox_mapping):
    nodes_in_constraint = [secondary for secondary in reversed(source.secondary_nodes) if lattice.in_constraint(secondary, sink.cfg_node)]
    nodes_in_constraint.append(source.cfg_node)
    if sink.trigger.all_arguments_propagate_taint:
        sink_args = get_sink_args(sink.cfg_node)
    else:
        sink_args = get_sink_args_which_propagate(sink, sink.cfg_node.ast_node)
    tainted_node_in_sink_arg = get_tainted_node_in_sink_args(sink_args, nodes_in_constraint)
    if tainted_node_in_sink_arg:
        vuln_deets = {'source': source.cfg_node, 'source_trigger_word': source.trigger_word, 'sink': sink.cfg_node, 'sink_trigger_word': sink.trigger_word}
        sanitiser_nodes = set()
        potential_sanitiser = None
        if sink.sanitisers:
            for sanitiser in sink.sanitisers:
                for cfg_node in triggers.sanitiser_dict[sanitiser]:
                    if isinstance(cfg_node, AssignmentNode):
                        sanitiser_nodes.add(cfg_node)
                    elif isinstance(cfg_node, IfNode):
                        potential_sanitiser = cfg_node
        def_use = build_def_use_chain(cfg.nodes, lattice)
        for chain in get_vulnerability_chains(source.cfg_node, sink.cfg_node, def_use):
            (vulnerability_type, interactive) = how_vulnerable(chain, blackbox_mapping, sanitiser_nodes, potential_sanitiser, cfg.blackbox_assignments, interactive, vuln_deets)
            if (vulnerability_type == VulnerabilityType.FALSE):
                continue
            vuln_deets['reassignment_nodes'] = chain
            return (vuln_factory(vulnerability_type)(**vuln_deets), interactive)
    return (None, interactive)

Get vulnerability between source and sink if it exists.

    Uses triggers to find sanitisers.

    Note: When a secondary node is in_constraint with the sink
            but not the source, the secondary is a save_N_LHS
            node made in process_function in expr_visitor.

Args:
        source(TriggerNode): TriggerNode of the source.
        sink(TriggerNode): TriggerNode of the sink.
        triggers(Triggers): Triggers of the CFG.
        lattice(Lattice): the lattice we're analysing.
        cfg(CFG): .blackbox_assignments used in is_unknown, .nodes used in build_def_use_chain
        interactive(bool): determines if we ask the user about blackbox functions not in the mapping file.
        blackbox_mapping(dict): A map of blackbox functions containing whether or not they propagate taint.

Returns:
        A Vulnerability if it exists, else None


def enable(self, information, id_or_uri, timeout=(- 1)):
    uri = self._client.build_uri(id_or_uri)
    return self._client.update(information, uri, timeout=timeout)

Enables or disables a range.

Args:
        information (dict): Information to update.
        id_or_uri: ID or URI of range.
        timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
            in OneView; it just stops waiting for its completion.

Returns:
        dict: Updated resource.


def get_lattice_type(number):
    f = (lambda i, j: (i <= number <= j))
    cs = {'triclinic': (1, 2), 'monoclinic': (3, 15), 'orthorhombic': (16, 74), 'tetragonal': (75, 142), 'trigonal': (143, 167), 'hexagonal': (168, 194), 'cubic': (195, 230)}
    crystal_system = None
    for (k, v) in cs.items():
        if f(*v):
            crystal_system = k
            break
    if (number in [146, 148, 155, 160, 161, 166, 167]):
        return 'rhombohedral'
    elif (crystal_system == 'trigonal'):
        return 'hexagonal'
    else:
        return crystal_system

Return the lattice crystal system.

    Hexagonal cells are differentiated into rhombohedral and hexagonal
    lattices.

Args:
        number (int): The international space group number.

Returns:
        str: The lattice crystal system.


def set_matrix(self, matrix):
    matrix = (c_float * 6)(*matrix)
    return self._libinput.libinput_device_config_calibration_set_matrix(self._handle, matrix)

Apply the 3x3 transformation matrix to absolute device coordinates.

    This matrix has no effect on relative events.

    Given a 6-element array [a, b, c, d, e, f], the matrix is applied as
    ::

    [ a  b  c ]   [ x ]
    [ d  e  f ] * [ y ]
    [ 0  0  1 ]   [ 1 ]

    The translation component (c, f) is expected to be normalized to
    the device coordinate range. For example, the matrix
    ::

    [ 1 0  1 ]
    [ 0 1 -1 ]
    [ 0 0  1 ]

    moves all coordinates by 1 device-width to the right and
    1 device-height up.

    The rotation matrix for rotation around the origin is defined as
    ::

    [ cos(a) -sin(a) 0 ]
    [ sin(a)  cos(a) 0 ]
    [   0      0     1 ]

    Note that any rotation requires an additional translation component
    to translate the rotated coordinates back into the original device
    space. The rotation matrixes for 90, 180 and 270 degrees clockwise are::

    90 deg cw:              180 deg cw:             270 deg cw:
    [ 0 -1 1]               [ -1  0 1]              [  0 1 0 ]
    [ 1  0 0]               [  0 -1 1]              [ -1 0 1 ]
    [ 0  0 1]               [  0  0 1]              [  0 0 1 ]

Args:
    matrix (iterable): An array representing the first two rows of
        a 3x3 matrix as described above.

Returns:
    ~libinput.constant.ConfigStatus: A config status code.


def longest_one_seg_prefix(self, word):
    match = self.seg_regex.match(word)
    if match:
        return match.group(0)
    else:
        return ''

Return longest IPA Unicode prefix of `word`

Args:
        word (unicode): word as IPA string

Returns:
        unicode: longest single-segment prefix of `word`


def filterbanks(num_filter, coefficients, sampling_freq, low_freq=None, high_freq=None):
    high_freq = (high_freq or (sampling_freq / 2))
    low_freq = (low_freq or 300)
    s = 'High frequency cannot be greater than half of the sampling frequency!'
    assert (high_freq <= (sampling_freq / 2)), s
    assert (low_freq >= 0), 'low frequency cannot be less than zero!'
    mels = np.linspace(functions.frequency_to_mel(low_freq), functions.frequency_to_mel(high_freq), (num_filter + 2))
    hertz = functions.mel_to_frequency(mels)
    freq_index = np.floor((((coefficients + 1) * hertz) / sampling_freq)).astype(int)
    filterbank = np.zeros([num_filter, coefficients])
    for i in range(0, num_filter):
        left = int(freq_index[i])
        middle = int(freq_index[(i + 1)])
        right = int(freq_index[(i + 2)])
        z = np.linspace(left, right, num=((right - left) + 1))
        filterbank[(i, left:(right + 1))] = functions.triangle(z, left=left, middle=middle, right=right)
    return filterbank

Compute the Mel-filterbanks. Each filter will be stored in one rows.
    The columns correspond to fft bins.

Args:
        num_filter (int): the number of filters in the filterbank, default 20.
        coefficients (int): (fftpoints//2 + 1). Default is 257.
        sampling_freq (float): the samplerate of the signal we are working
            with. It affects mel spacing.
        low_freq (float): lowest band edge of mel filters, default 0 Hz
        high_freq (float): highest band edge of mel filters,
            default samplerate/2

Returns:
        array: A numpy array of size num_filter x (fftpoints//2 + 1)
            which are filterbank


def _send_offset_fetch_request(self, partitions):
    assert (self.config['api_version'] >= (0, 8, 1)), 'Unsupported Broker API'
    assert all(map((lambda k: isinstance(k, TopicPartition)), partitions))
    if (not partitions):
        return Future().success({})
    node_id = self.coordinator()
    if (node_id is None):
        return Future().failure(Errors.GroupCoordinatorNotAvailableError)
    if (not self._client.ready(node_id)):
        log.debug('Node %s not ready -- failing offset fetch request', node_id)
        return Future().failure(Errors.NodeNotReadyError)
    log.debug('Group %s fetching committed offsets for partitions: %s', self.group_id, partitions)
    topic_partitions = collections.defaultdict(set)
    for tp in partitions:
        topic_partitions[tp.topic].add(tp.partition)
    if (self.config['api_version'] >= (0, 8, 2)):
        request = OffsetFetchRequest[1](self.group_id, list(topic_partitions.items()))
    else:
        request = OffsetFetchRequest[0](self.group_id, list(topic_partitions.items()))
    future = Future()
    _f = self._client.send(node_id, request)
    _f.add_callback(self._handle_offset_fetch_response, future)
    _f.add_errback(self._failed_request, node_id, request, future)
    return future

Fetch the committed offsets for a set of partitions.

    This is a non-blocking call. The returned future can be polled to get
    the actual offsets returned from the broker.

Args:
        partitions (list of TopicPartition): the partitions to fetch

Returns:
        Future: resolves to dict of offsets: {TopicPartition: int}


def pkg_version_list(self, pkg_id):
    pkg_data = self.__reg_software.get(pkg_id, None)
    if (not pkg_data):
        return []
    if isinstance(pkg_data, list):
        return pkg_data
    installed_versions = list(pkg_data.get('version').keys())
    return sorted(installed_versions, key=cmp_to_key(self.__oldest_to_latest_version))

Returns information on a package.

Args:
        pkg_id (str): Package Id of the software/component.

Returns:
        list: List of version numbers installed.


def get_bin_edges_from_axis(axis) -> np.ndarray:
    bins = range(1, (axis.GetNbins() + 1))
    bin_edges = np.empty((len(bins) + 1))
    bin_edges[:(- 1)] = [axis.GetBinLowEdge(i) for i in bins]
    bin_edges[(- 1)] = axis.GetBinUpEdge(axis.GetNbins())
    return bin_edges

Get bin edges from a ROOT hist axis.

Note:
        Doesn't include over- or underflow bins!

Args:
        axis (ROOT.TAxis): Axis from which the bin edges should be extracted.

Returns:
        Array containing the bin edges.


def inflate_plugin(self, identifier, definition=None, cls=None):
    cls = self.get_plugin(identifier, cls)
    return cls(**(definition or {}))

Inflate a plugin thanks to it's identifier, definition and class.

Args:
        identifier (str): the plugin identifier.
        definition (dict): the kwargs to instantiate the plugin with.
        cls (str): "provider", "checker", or None.

Returns:
        Provider/Checker: instance of plugin.


def build_parameter(name, properties):
    p = Parameter(name, Type=properties.get('type'))
    for (name, attr) in PARAMETER_PROPERTIES.items():
        if (name in properties):
            setattr(p, attr, properties[name])
    return p

Builds a troposphere Parameter with the given properties.

Args:
        name (string): The name of the parameter.
        properties (dict): Contains the properties that will be applied to the
            parameter. See:
            http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html

Returns:
        :class:`troposphere.Parameter`: The created parameter object.


def getHostCaPath(self, name):
    cert = self.getHostCert(name)
    if (cert is None):
        return None
    return self._getCaPath(cert)

Gets the path to the CA certificate that issued a given host keypair.

Args:
        name (str): The name of the host keypair.

Example:
        Get the path to the CA cert which issue the cert for "myhost":

            mypath = cdir.getHostCaPath('myhost')

Returns:
        str: The path if exists.


def polymorph_response(response, poly, bqm, penalty_strength=None, keep_penalty_variables=True, discard_unsatisfied=False):
    record = response.record
    penalty_vector = penalty_satisfaction(response, bqm)
    original_variables = bqm.variables
    if discard_unsatisfied:
        samples_to_keep = list(map(bool, list(penalty_vector)))
        penalty_vector = np.array(([True] * np.sum(samples_to_keep)))
    else:
        samples_to_keep = list(map(bool, ([1] * len(record.sample))))
    samples = record.sample[samples_to_keep]
    energy_vector = poly.energies((samples, response.variables))
    if (not keep_penalty_variables):
        original_variables = poly.variables
        idxs = [response.variables.index[v] for v in original_variables]
        samples = np.asarray(samples[(:, idxs)])
    (num_samples, num_variables) = np.shape(samples)
    datatypes = [('sample', np.dtype(np.int8), (num_variables,)), ('energy', energy_vector.dtype), ('penalty_satisfaction', penalty_vector.dtype)]
    datatypes.extend(((name, record[name].dtype, record[name].shape[1:]) for name in record.dtype.names if (name not in {'sample', 'energy'})))
    data = np.rec.array(np.empty(num_samples, dtype=datatypes))
    data.sample = samples
    data.energy = energy_vector
    for name in record.dtype.names:
        if (name not in {'sample', 'energy'}):
            data[name] = record[name][samples_to_keep]
    data['penalty_satisfaction'] = penalty_vector
    response.info['reduction'] = bqm.info['reduction']
    if (penalty_strength is not None):
        response.info['penalty_strength'] = penalty_strength
    return SampleSet(data, original_variables, response.info, response.vartype)

Transforms the sampleset for the higher order problem.

    Given a response of a penalized HUBO, this function creates a new sampleset
    object, taking into account penalty information and calculates the
    energies of samples for the higherorder problem.

Args:
        response (:obj:`.SampleSet`): response for a penalized hubo.

        poly (:obj:`.BinaryPolynomial`):
            A binary polynomial.

        bqm (:obj:`dimod.BinaryQuadraticModel`): Binary quadratic model of the
            reduced problem.

        penalty_strength (float, optional): default is None, if provided,
            will be added to the info field of the returned sampleSet object.

        keep_penalty_variables (bool, optional): default is True. if False
            will remove the variables used for penalty from the samples

        discard_unsatisfied (bool, optional): default is False. If True
            will discard samples that do not satisfy the penalty conditions.

Returns:
        (:obj:`.SampleSet'): A sampleSet object that has additional penalty
            information. The energies of samples are calculated for the HUBO
            ignoring the penalty variables.


def readSchedules(self, tableset):
    self.setContext('readSchedules')
    try:
        req_table = binascii.hexlify(str(tableset).zfill(1))
        req_str = (('01523102303037' + req_table) + '282903')
        self.request(False)
        req_crc = self.calc_crc16(req_str[2:].decode('hex'))
        req_str += req_crc
        self.m_serial_port.write(req_str.decode('hex'))
        raw_ret = self.m_serial_port.getResponse(self.getContext())
        self.serialPostEnd()
        return_crc = self.calc_crc16(raw_ret[1:(- 2)])
        if (tableset == ReadSchedules.Schedules_1_To_4):
            unpacked_read = self.unpackStruct(raw_ret, self.m_schd_1_to_4)
            self.convertData(unpacked_read, self.m_schd_1_to_4, self.m_kwh_precision)
            if (str(return_crc) == str(self.m_schd_1_to_4['crc16'][MeterData.StringValue])):
                ekm_log('Schedules 1 to 4 CRC success (06 return')
                self.setContext('')
                return True
        elif (tableset == ReadSchedules.Schedules_5_To_6):
            unpacked_read = self.unpackStruct(raw_ret, self.m_schd_5_to_6)
            self.convertData(unpacked_read, self.m_schd_5_to_6, self.m_kwh_precision)
            if (str(return_crc) == str(self.m_schd_5_to_6['crc16'][MeterData.StringValue])):
                ekm_log('Schedules 5 to 8 CRC success (06 return)')
                self.setContext('')
                return True
    except:
        ekm_log(traceback.format_exc(sys.exc_info()))
    self.setContext('')
    return False

Serial call to read schedule tariffs buffer

Args:
        tableset (int): :class:`~ekmmeters.ReadSchedules` buffer to return.

Returns:
        bool: True on completion and ACK.


def trace_format(self):
    cmd = enums.JLinkTraceCommand.GET_FORMAT
    data = ctypes.c_uint32(0)
    res = self._dll.JLINKARM_TRACE_Control(cmd, ctypes.byref(data))
    if (res == 1):
        raise errors.JLinkException('Failed to get trace format.')
    return data.value

Retrieves the current format the trace buffer is using.

Args:
        self (JLink): the ``JLink`` instance.

Returns:
        The current format the trace buffer is using.  This is one of the
        attributes of ``JLinkTraceFormat``.


def to(self, fmt=None, filename=None):
    from pymatgen.io.xyz import XYZ
    from pymatgen.io.gaussian import GaussianInput
    from pymatgen.io.babel import BabelMolAdaptor
    fmt = ('' if (fmt is None) else fmt.lower())
    fname = os.path.basename((filename or ''))
    if ((fmt == 'xyz') or fnmatch(fname.lower(), '*.xyz*')):
        writer = XYZ(self)
    elif any([((fmt == r) or fnmatch(fname.lower(), '*.{}*'.format(r))) for r in ['gjf', 'g03', 'g09', 'com', 'inp']]):
        writer = GaussianInput(self)
    elif ((fmt == 'json') or fnmatch(fname, '*.json*') or fnmatch(fname, '*.mson*')):
        if filename:
            with zopen(filename, 'wt', encoding='utf8') as f:
                return json.dump(self.as_dict(), f)
        else:
            return json.dumps(self.as_dict())
    elif ((fmt == 'yaml') or fnmatch(fname, '*.yaml*')):
        import ruamel.yaml as yaml
        if filename:
            with zopen(fname, 'wt', encoding='utf8') as f:
                return yaml.safe_dump(self.as_dict(), f)
        else:
            return yaml.safe_dump(self.as_dict())
    else:
        m = re.search('\\.(pdb|mol|mdl|sdf|sd|ml2|sy2|mol2|cml|mrv)', fname.lower())
        if ((not fmt) and m):
            fmt = m.group(1)
        writer = BabelMolAdaptor(self)
        return writer.write_file(filename, file_format=fmt)
    if filename:
        writer.write_file(filename)
    else:
        return str(writer)

Outputs the molecule to a file or string.

Args:
        fmt (str): Format to output to. Defaults to JSON unless filename
            is provided. If fmt is specifies, it overrides whatever the
            filename is. Options include "xyz", "gjf", "g03", "json". If
            you have OpenBabel installed, any of the formats supported by
            OpenBabel. Non-case sensitive.
        filename (str): If provided, output will be written to a file. If
            fmt is not specified, the format is determined from the
            filename. Defaults is None, i.e. string output.

Returns:
        (str) if filename is None. None otherwise.


def cumprod(vari, axis=None):
    if isinstance(vari, Poly):
        if (np.prod(vari.shape) == 1):
            return vari.copy()
        if (axis is None):
            vari = chaospy.poly.shaping.flatten(vari)
            axis = 0
        vari = chaospy.poly.shaping.rollaxis(vari, axis)
        out = [vari[0]]
        for poly in vari[1:]:
            out.append((out[(- 1)] * poly))
        return Poly(out, vari.dim, vari.shape, vari.dtype)
    return np.cumprod(vari, axis)

Perform the cumulative product of a shapeable quantity over a given axis.

Args:
        vari (chaospy.poly.base.Poly, numpy.ndarray):
            Input data.
        axis (int):
            Axis over which the sum is taken. By default ``axis`` is None, and
            all elements are summed.

Returns:
        (chaospy.poly.base.Poly):
            An array shaped as ``vari`` but with the specified axis removed.

Example:
        >>> vari = cp.prange(4)
        >>> print(vari)
        [1, q0, q0^2, q0^3]
        >>> print(cp.cumprod(vari))
        [1, q0, q0^3, q0^6]


def generate_html(store):
    spline = {'version': VERSION, 'url': 'https://github.com/Nachtfeuer/pipeline', 'generated': datetime.now().strftime('%A, %d. %B %Y - %I:%M:%S %p')}
    html_template_file = os.path.join(os.path.dirname(__file__), 'templates/report.html.j2')
    with open(html_template_file) as handle:
        html_template = handle.read()
        return render(html_template, spline=spline, store=store)

Generating HTML report.

Args:
        store (Store): report data.

Returns:
        str: rendered HTML template.


def status(self, order_id):
    self.logger.debug(('Get status of order ' + order_id))
    url = ('%(base_url)s/order/%(order_id)s' % {'base_url': self.base_url, 'order_id': order_id})
    r = self.gbdx_connection.get(url)
    r.raise_for_status()
    return r.json().get('acquisitions', {})

Checks imagery order status. There can be more than one image per
    order and this function returns the status of all images
    within the order.

Args:
        order_id (str): The id of the order placed.

Returns:
        List of dictionaries, one per image. Each dictionary consists
        of the keys 'acquisition_id', 'location' and 'state'.


def _ParseCommon2003CachedEntry(self, value_data, cached_entry_offset):
    data_type_map = self._GetDataTypeMap('appcompatcache_cached_entry_2003_common')
    try:
        cached_entry = self._ReadStructureFromByteStream(value_data[cached_entry_offset:], cached_entry_offset, data_type_map)
    except (ValueError, errors.ParseError) as exception:
        raise errors.ParseError('Unable to parse cached entry value with error: {0!s}'.format(exception))
    if (cached_entry.path_size > cached_entry.maximum_path_size):
        raise errors.ParseError('Path size value out of bounds.')
    path_end_of_string_size = (cached_entry.maximum_path_size - cached_entry.path_size)
    if ((cached_entry.path_size == 0) or (path_end_of_string_size != 2)):
        raise errors.ParseError('Unsupported path size values.')
    return cached_entry

Parses the cached entry structure common for Windows 2003, Vista and 7.

Args:
        value_data (bytes): value data.
        cached_entry_offset (int): offset of the first cached entry data
        relative to the start of the value data.

Returns:
        appcompatcache_cached_entry_2003_common: cached entry structure common
        for Windows 2003, Windows Vista and Windows 7.

Raises:
        ParseError: if the value data could not be parsed.


def update(self, resource, id_or_uri):
    return self._client.update(resource=resource, uri=id_or_uri)

Updates a registered Device Manager.

Args:
        resource (dict): Object to update.
        id_or_uri: Can be either the Device manager ID or URI.

Returns:
        dict: The device manager resource.


def to_insert(table, d):
    columns = []
    args = []
    for (key, val) in d.items():
        columns.append('"{}"'.format(key))
        args.append(val)
    stmt = 'insert into {table} ({columns}) values ({params})'.format(table=table, columns=', '.join(columns), params=', '.join((['?'] * len(columns))))
    return (stmt, args)

Generate an insert statement using the given table and dictionary.

Args:
        table (str): table name
        d (dict): dictionary with column names as keys and values as values.

Returns:
        tuple of statement and arguments

    >>> to_insert('doc.foobar', {'name': 'Marvin'})
    ('insert into doc.foobar ("name") values (?)', ['Marvin'])


def delete(self, url, params=None, **kwargs):
    return self.call_api('DELETE', url, params=params, **kwargs)

Call the API with a DELETE request.

Args:
        url (str): Resource location relative to the base URL.
        params (dict or None): Query-string parameters.

Returns:
        ResultParser or ErrorParser.


def update(self, properties=None, description=None):
    cv = ApplicationConfiguration._props(properties=properties, description=description)
    res = self.rest_client.session.patch(self.rest_self, headers={'Accept': 'application/json', 'Content-Type': 'application/json'}, json=cv)
    _handle_http_errors(res)
    self.json_rep = res.json()
    return self

Update this application configuration.

    To create or update a property provide its key-value
    pair in `properties`.

    To delete a property provide its key with the value ``None``
    in properties.

Args:
        properties (dict): Property values to be updated. If ``None`` the properties are unchanged.
        description (str): Description for the configuration. If ``None`` the description is unchanged.

Returns:
        ApplicationConfiguration: self


def overlay_gateway_type(self, **kwargs):
    callback = kwargs.pop('callback', self._callback)
    get_config = kwargs.pop('get', False)
    if (not get_config):
        gw_name = kwargs.pop('gw_name')
        gw_type = kwargs.pop('gw_type')
        gw_args = dict(name=gw_name, gw_type=gw_type)
        overlay_gw = getattr(self._tunnels, 'overlay_gateway_gw_type')
        config = overlay_gw(**gw_args)
    if get_config:
        overlay_gw = getattr(self._tunnels, 'overlay_gateway_gw_type')
        config = overlay_gw(name='', gw_type='')
        output = callback(config, handler='get_config')
        if (output.data.find('.//{*}name') is not None):
            gwtype = output.data.find('.//{*}gw-type').text
            return gwtype
        else:
            return None
    return callback(config)

Configure Overlay Gateway Type on vdx switches

Args:
        gw_name: Name of Overlay Gateway
        gw_type: Type of Overlay Gateway(hardware-vtep/
                layer2-extension/nsx)
        get (bool): Get config instead of editing config. (True, False)
        delete (bool): True, delete the overlay gateway type.
                    (True, False)
        callback (function): A function executed upon completion of the
            method.  The only parameter passed to `callback` will be the
            ``ElementTree`` `config`.

Returns:
        Return value of `callback`.

Raises:
        KeyError: if `gw_name`, 'gw_type' is not passed.
        ValueError: if `gw_name`, 'gw_type' is invalid.

Example:
        >>> import pynos.device
        >>> conn = ('10.24.39.211', '22')
        >>> auth = ('admin', 'password')
        >>> with pynos.device.Device(conn=conn, auth=auth) as dev:
        ...     output = dev.interface.overlay_gateway_type(gw_name='Leaf',
        ...              gw_type='layer2-extension')
        ...     output = dev.interface.overlay_gateway_name(get=True)


def hardware_info(self, mask=4294967295):
    buf = (ctypes.c_uint32 * 32)()
    res = self._dll.JLINKARM_GetHWInfo(mask, ctypes.byref(buf))
    if (res != 0):
        raise errors.JLinkException(res)
    return list(buf)

Returns a list of 32 integer values corresponding to the bitfields
    specifying the power consumption of the target.

    The values returned by this function only have significance if the
    J-Link is powering the target.

    The words, indexed, have the following significance:
        0. If ``1``, target is powered via J-Link.
        1. Overcurrent bitfield:
        0: No overcurrent.
        1: Overcurrent happened.  2ms @ 3000mA
        2: Overcurrent happened.  10ms @ 1000mA
        3: Overcurrent happened.  40ms @ 400mA
        2. Power consumption of target (mA).
        3. Peak of target power consumption (mA).
        4. Peak of target power consumption during J-Link operation (mA).

Args:
        self (JLink): the ``JLink`` instance
        mask (int): bit mask to decide which hardware information words are
        returned (defaults to all the words).

Returns:
        List of bitfields specifying different states based on their index
        within the list and their value.

Raises:
        JLinkException: on hardware error.


def candidates(self, word):
    if self.known([word]):
        return {word}
    res = [x for x in self.edit_distance_1(word)]
    tmp = self.known(res)
    if tmp:
        return tmp
    if (self._distance == 2):
        tmp = self.known([x for x in self.__edit_distance_alt(res)])
        if tmp:
            return tmp
    return {word}

Generate possible spelling corrections for the provided word up to
    an edit distance of two, if and only when needed

Args:
        word (str): The word for which to calculate candidate spellings

Returns:
        set: The set of words that are possible candidates


def userhome(username=None):
    if (username is None):
        if ('HOME' in os.environ):
            userhome_dpath = os.environ['HOME']
        elif sys.platform.startswith('win32'):
            if ('USERPROFILE' in os.environ):
                userhome_dpath = os.environ['USERPROFILE']
            elif ('HOMEPATH' in os.environ):
                drive = os.environ.get('HOMEDRIVE', '')
                userhome_dpath = join(drive, os.environ['HOMEPATH'])
            else:
                raise OSError("Cannot determine the user's home directory")
        else:
            import pwd
            userhome_dpath = pwd.getpwuid(os.getuid()).pw_dir
    elif sys.platform.startswith('win32'):
        c_users = dirname(userhome())
        userhome_dpath = join(c_users, username)
        if (not exists(userhome_dpath)):
            raise KeyError('Unknown user: {}'.format(username))
    else:
        import pwd
        try:
            pwent = pwd.getpwnam(username)
        except KeyError:
            raise KeyError('Unknown user: {}'.format(username))
        userhome_dpath = pwent.pw_dir
    return userhome_dpath

Returns the user's home directory.
    If `username` is None, this is the directory for the current user.

Args:
        username (str): name of a user on the system

Returns:
        PathLike: userhome_dpath: path to the home directory

Example:
        >>> import getpass
        >>> username = getpass.getuser()
        >>> assert userhome() == expanduser('~')
        >>> assert userhome(username) == expanduser('~')


def confinterval(array, conf=0.95, normal_threshold=30, error_only=False, array_mean=None):
    n = len(array)
    if (n < 1):
        (array_mean, c0, c1) = (0, 0, 0)
    elif (n == 1):
        (array_mean, c0, c1) = (array[0], array[0], array[0])
    else:
        scale = (stdev(array) / sqrt(n))
        values_all_same = all(((x == array[0]) for x in array[1:]))
        if values_all_same:
            (array_mean, c0, c1) = (array[0], array[0], array[0])
        else:
            if (array_mean is None):
                array_mean = mean(array)
            if (n < normal_threshold):
                (c0, c1) = stats.t.interval(conf, (n - 1), loc=array_mean, scale=scale)
            else:
                (c0, c1) = stats.norm.interval(conf, loc=array_mean, scale=scale)
    if error_only:
        return (c1 - array_mean)
    else:
        return (c0, c1)

Return the confidence interval of a list for a given confidence.

Args:
        array (list): Sequence of numbers.
        conf (float): Confidence interval, in range 0 <= ci <= 1
        normal_threshold (int): The number of elements in the array is
        < normal_threshold, use a T-distribution. If the number of
        elements in the array is >= normal_threshold, use a normal
        distribution.
        error_only (bool, optional): If true, return only the size of
        symmetrical confidence interval, equal to ci_upper - mean.
        array_mean (float, optional): Optimisation trick for if you
        already know the arithmetic mean of the array to prevent
        this function from re-calculating.

Returns:
        (float, float): Lower and upper bounds on confidence interval,
        respectively.


def transfer(self, transfer_payload=None, *, from_user, to_user):
    if (self.persist_id is None):
        raise EntityNotYetPersistedError('Entities cannot be transferred until they have been persisted')
    return self.plugin.transfer(self.persist_id, transfer_payload, from_user=from_user, to_user=to_user)

Transfer this entity to another owner on the backing
    persistence layer

Args:
        transfer_payload (dict): Payload for the transfer
        from_user (any): A user based on the model specified by the
            persistence layer
        to_user (any): A user based on the model specified by the
            persistence layer

Returns:
        str: Id of the resulting transfer action on the persistence
        layer

Raises:
        :exc:`~.EntityNotYetPersistedError`: If the entity being
            transferred is not associated with an id on the
            persistence layer (:attr:`~Entity.persist_id`) yet
        :exc:`~.EntityNotFoundError`: If the entity could not be
            found on the persistence layer
        :exc:`~.EntityTransferError`: If the entity fails to be
            transferred on the persistence layer
        :exc:`~.PersistenceError`: If any other unhandled error
            in the plugin occurred


def convert_snapshot(self, shift, instruction):
    command_dict = {'name': 'snapshot', 't0': (shift + instruction.start_time), 'label': instruction.name, 'type': instruction.type}
    return self._qobj_model(**command_dict)

Return converted `Snapshot`.

Args:
        shift(int): Offset time.
        instruction (Snapshot): snapshot instruction.

Returns:
        dict: Dictionary of required parameters.


def automatic_density_by_vol(structure, kppvol, force_gamma=False):
    vol = structure.lattice.reciprocal_lattice.volume
    kppa = ((kppvol * vol) * structure.num_sites)
    return Kpoints.automatic_density(structure, kppa, force_gamma=force_gamma)

Returns an automatic Kpoint object based on a structure and a kpoint
    density per inverse Angstrom^3 of reciprocal cell.

    Algorithm:
        Same as automatic_density()

Args:
        structure (Structure): Input structure
        kppvol (int): Grid density per Angstrom^(-3) of reciprocal cell
        force_gamma (bool): Force a gamma centered mesh

Returns:
        Kpoints


def render(self, tmpl_name, request_env):
    return super(WebApplication, self).render(tmpl_name, request_env)

Render the specified template and return the output.

Args:
        tmpl_name (str): file name of the template
        request_env (dict): request environment

Returns:
        str - the rendered template


def GetMessage(self, log_source, lcid, message_identifier):
    event_log_provider_key = self._GetEventLogProviderKey(log_source)
    if (not event_log_provider_key):
        return None
    generator = self._GetMessageFileKeys(event_log_provider_key)
    if (not generator):
        return None
    message_string = None
    for message_file_key in generator:
        message_string = self._GetMessage(message_file_key, lcid, message_identifier)
        if message_string:
            break
    if (self._string_format == 'wrc'):
        message_string = self._ReformatMessageString(message_string)
    return message_string

Retrieves a specific message for a specific Event Log source.

Args:
        log_source (str): Event Log source.
        lcid (int): language code identifier (LCID).
        message_identifier (int): message identifier.

Returns:
        str: message string or None if not available.


def hflip(img):
    if (not _is_pil_image(img)):
        raise TypeError('img should be PIL Image. Got {}'.format(type(img)))
    return img.transpose(Image.FLIP_LEFT_RIGHT)

Horizontally flip the given PIL Image.

Args:
        img (PIL Image): Image to be flipped.

Returns:
        PIL Image:  Horizontall flipped image.