def cluster_total_volume(adj, c, cluster_num, dict_bool):
    """Determines the volume of a community.

    Parameters
    ----------
    adj : SciPy sparse matrix (csr or csc)
        The N x N rescaled Adjacency matrix constructed from
        N x N adjacency matrix of the graph and scale r.
    c : Integer array
        Array of community labels for the nodes in the graph as ordered
        by the adjacency matrix.
    cluster_num : Integer
        Label of the community of interest.
    dict_bool : dictionary
        Tracks the nodes in each community, with cluster labels as dictionary-
        keys, and the corresponding boolean arrays (c == label) as values.

    Returns
    -------
    float
        Total volume of all nodes in the rescaled topology of
        cluster 'cluster_num'.

    """
    return adj[dict_bool[cluster_num]].sum()


@classmethod
def from_str(cls, string):
    """
        Parse string and return an :class:`OrgDate` objects.

        >>> OrgDate.from_str('2012-02-10 Fri')
        OrgDate((2012, 2, 10))
        >>> OrgDate.from_str('2012-02-10 Fri 12:05')
        OrgDate((2012, 2, 10, 12, 5, 0))

        """
    match = cls._from_str_re.match(string)
    if match:
        mdict = match.groupdict()
        return cls(cls._datetuple_from_groupdict(mdict), active=cls.
            _active_default)
    else:
        return cls(None)


def lambd_NH3_Mg_CB89(T, P):
    """n-c: ammonia magnesium [CB89]."""
    lambd = -0.21
    valid = T == 298.15
    return lambd, valid


def di(data):
    """
    Delete imaginary from data

    Parameters
    ----------
    data : ndarray
        Array of NMR data.

    Returns
    -------
    ndata : ndarray
        Array of NMR data without imaginaries.

    """
    return data.real


def get_association_indices(associations):
    """
    Given a list of associations, determines the indices that will be plotted.
    If n_associations > 3, this is the first, middle, and last associations,
    otherwise it's all of them.

    :param associations: All of the associations for this STIS spectrum.

    :type associations: list

    :returns: list -- The indices of the list that will be plotted.
    """
    n_associations = len(associations)
    if n_associations <= 3:
        subplot_indices = list(range(n_associations))
    else:
        midindex = int(round(n_associations / 2.0))
        subplot_indices = [0, midindex, n_associations - 1]
    return subplot_indices


def multipart_upload_lister(bucket, key_marker='', upload_id_marker='',
    headers=None, encoding_type=None):
    """
    A generator function for listing multipart uploads in a bucket.
    """
    more_results = True
    k = None
    while more_results:
        rs = bucket.get_all_multipart_uploads(key_marker=key_marker,
            upload_id_marker=upload_id_marker, headers=headers,
            encoding_type=encoding_type)
        for k in rs:
            yield k
        key_marker = rs.next_key_marker
        upload_id_marker = rs.next_upload_id_marker
        more_results = rs.is_truncated


def cols_to_drop(df, columns):
    """Drop selected columns and return dataframe.

    Args:
        df: Pandas dataframe.
        columns: List of columns to drop.

    Returns:
        Original dataframe without dropped columns.
    """
    for col in columns:
        df.drop([col], axis=1, inplace=True)
    return df


@classmethod
def _dump_elf(cls, buf):
    """
        Dump the symbol table of an ELF file.
        Needs pyelftools (https://github.com/eliben/pyelftools)
        """
    from elftools.elf.elffile import ELFFile
    from elftools.elf import descriptions
    from io import BytesIO
    f = ELFFile(BytesIO(buf))
    print('ELF file:')
    for sec in f.iter_sections():
        if sec['sh_type'] == 'SHT_SYMTAB':
            symbols = sorted(sec.iter_symbols(), key=lambda sym: sym.name)
            print('    symbols:')
            for sym in symbols:
                if not sym.name:
                    continue
                print('    - %r: size=%d, value=0x%x, type=%s, bind=%s' % (
                    sym.name.decode(), sym['st_size'], sym['st_value'],
                    descriptions.describe_symbol_type(sym['st_info']['type'
                    ]), descriptions.describe_symbol_bind(sym['st_info'][
                    'bind'])))
    print()


@staticmethod
def p_if_data_module_unsupported_element(p):
    """if_data_module_unsupported_element : generic_parameter_list"""


def optimiseCorrection(feature, optimise):
    """
	Optimise the window function my mimising the output of `optimise(data)`
	"""
    pass


@staticmethod
def speed_to_str(speed):
    """
        Convert speed to formated string with the appropriate units.
        """
    if speed < 1000:
        return '{:>4}K/s'.format(round(speed))
    else:
        return '{:4.1f}M/s'.format(round(speed / 1000))


def _get_floppy_image_name(node):
    """Returns the floppy image name for a given node.

    :param node: the node for which image name is to be provided.
    """
    return 'image-%s' % node.uuid


@staticmethod
def p_function_optional(p):
    """function_optional : annotation
                             | def_characteristic
                             | ref_characteristic
                             | in_measurement
                             | out_measurement
                             | loc_measurement
                             | sub_function
                             | function_version"""
    p[0] = p.slice[1].type, p[1]


def disassociate_node(ServerName=None, NodeName=None, EngineAttributes=None):
    """
    Disassociates a node from a Chef server, and removes the node from the Chef server's managed nodes. After a node is disassociated, the node key pair is no longer valid for accessing the Chef API. For more information about how to associate a node, see  AssociateNode .
    A node can can only be disassociated from a server that is in a HEALTHY state. Otherwise, an InvalidStateException is thrown. A ResourceNotFoundException is thrown when the server does not exist. A ValidationException is raised when parameters of the request are not valid.
    See also: AWS API Documentation

    :example: response = client.disassociate_node(
        ServerName='string',
        NodeName='string',
        EngineAttributes=[
            {
                'Name': 'string',
                'Value': 'string'
            },
        ]
    )

    :type ServerName: string
    :param ServerName: [REQUIRED]
            The name of the server from which to disassociate the node.

    :type NodeName: string
    :param NodeName: [REQUIRED]
            The name of the Chef client node.

    :type EngineAttributes: list
    :param EngineAttributes: Engine attributes used for disassociating the node.
            Attributes accepted in a DisassociateNode request:
            CHEF_ORGANIZATION : The Chef organization with which the node was associated. By default only one organization named default can exist.
            (dict) --A name and value pair that is specific to the engine of the server.
            Name (string) --The name of the engine attribute.
            Value (string) --The value of the engine attribute.

    :rtype: dict
    :return: {
        'NodeAssociationStatusToken': 'string'
    }

    """
    pass


@staticmethod
def _set_widget_background_color(widget, color):
    """
        Changes the base color of a widget (background).
        :param widget: widget to modify
        :param color: the color to apply
        """
    pal = widget.palette()
    pal.setColor(pal.Base, color)
    widget.setPalette(pal)


@classmethod
def parse_args(cls, subparsers):
    """Create the `files` subparser for the `backup` command.
        :param subparsers: Main argument parser
        """
    fs_parser = subparsers.add_parser(cls.command, description=cls.__doc__)
    fs_parser.add_argument('-o', '--output', required=True, help=
        'output gzipped file path')


def get_deepnet_options(defaults=None):
    """Adding arguments for the deepnet subcommand

    """
    if defaults is None:
        defaults = {}
    options = {'--deepnet-fields': {'action': 'store', 'dest':
        'deepnet_fields', 'default': defaults.get('deepnet_fields', None),
        'help':
        'Comma-separated list of input fields (predictors) to create the deepnet.'
        }, '--deepnet': {'action': 'store', 'dest': 'deepnet', 'default':
        defaults.get('deepnet', None), 'help': 'BigML deepnet Id.'},
        '--deepnets': {'action': 'store', 'dest': 'deepnets', 'default':
        defaults.get('deepnets', None), 'help':
        'Path to a file containing deepnets/ids. One deepnet per line (e.g., deepnet/50a206a8035d0706dc000376).'
        }, '--deepnet-file': {'action': 'store', 'dest': 'deepnet_file',
        'default': defaults.get('deepnet_file', None), 'help':
        'BigML deepnet JSON structure file.'}, '--batch-normalization': {
        'action': 'store_true', 'dest': 'batch_normalization', 'default':
        defaults.get('batch_normalization', None), 'help':
        'Specifies whether to normalize the outputs of a network before being passed to the activation function or not.'
        }, '--default-numeric-value': {'action': 'store', 'dest':
        'default_numeric_value', 'default': defaults.get(
        'default_numeric_value', None), 'choices': ['mean', 'median',
        'minimum', 'maximum', 'zero'], 'help':
        "It accepts any of the following strings to substitute missing numeric values across all the numeric fields in the dataset: 'mean', 'median', 'minimum', 'maximum', 'zero'."
        }, '--dropout-rate': {'action': 'store', 'dest': 'dropout_rate',
        'type': float, 'default': defaults.get('dropout_rate', None),
        'help':
        'A number between 0 and 1 specifying the rate at which to drop weights during training to control overfitting'
        }, '--hidden-layers': {'action': 'store', 'dest': 'hidden_layers',
        'default': defaults.get('hidden_layers', None), 'help':
        'A JSON file that contains a list of maps describing the number and type of layers in the network (other than the output layer, which is determined by the type of learning problem).'
        }, '--learn-residuals': {'action': 'store_true', 'dest':
        'learn_residuals', 'default': defaults.get('learn_residuals', None),
        'help':
        'Specifies whether alternate layers should learn a representation of the residuals for a given layer rather than the layer itself or not.'
        }, '--learning-rate': {'action': 'store', 'dest': 'learning_rate',
        'type': float, 'default': defaults.get('learning_rate', None),
        'help': 'A number between 0 and 1 specifying the learning rate.'},
        '--max-iterations': {'action': 'store', 'dest': 'max_iterations',
        'type': int, 'default': defaults.get('max_iterations', None),
        'help':
        'A number between 100 and 100000 for the maximum number of gradient steps to take during the optimization.'
        }, '--max-training-time': {'action': 'store', 'dest':
        'max_training_time', 'type': int, 'default': defaults.get(
        'max_training_time', None), 'help':
        'The maximum wall-clock training time, in seconds, for which to train the network. '
        }, '--number-of-hidden-layers': {'action': 'store', 'dest':
        'number_of_hidden_layers', 'type': int, 'default': defaults.get(
        'number_of_hidden_layers', None), 'help':
        'The number of hidden layers to use in the network. If the number is greater than the length of the list of hidden_layers, the list is cycled until the desired number is reached. If the number is smaller than the length of the list of hidden_layers, the list is shortened. '
        }, '--number-of-model-candidates': {'action': 'store', 'dest':
        'number_of_model_candidates', 'type': int, 'default': defaults.get(
        'number_of_model_candidates', None), 'help':
        'An  integer specifying the number of models to try during the model search. '
        }, '--search': {'action': 'store', 'dest': 'search', 'default':
        defaults.get('search', None), 'help':
        'During the deepnet creation, BigML trains and evaluates over all possible network configurations, returning the best networks found for the problem. The final deepnet returned by the search is a compromise between the top n networks found in the search. Since this option builds several networks, it may be significantly slower than the suggest_structure technique.'
        }, '--suggest-structure': {'action': 'store_true', 'dest':
        'suggest_structure', 'default': defaults.get('suggest_structure',
        None), 'help':
        'An alternative to the search technique that is usually a more efficient way to quickly train and iterate deepnets and it can reach similar results. BigML has learned some general rules about what makes one network structure better than another for a given dataset. Given your dataset, BigML will automatically suggest a structure and a set of parameter values that are likely to perform well for your dataset. This option only builds one network.'
        }, '--missing-numerics': {'action': 'store_true', 'dest':
        'missing_numerics', 'default': defaults.get('missing_numerics',
        True), 'help':
        'Whether to create an additional binary predictor each numeric field which denotes a missing value. If false, these predictors are not created, and rows containing missing numeric values are dropped. '
        }, '--no-missing-numerics': {'action': 'store_false', 'dest':
        'missing_numerics', 'default': defaults.get('missing_numerics',
        True), 'help':
        'Whether to create an additional binary predictor each numeric field which denotes a missing value. If true, these predictors are not created, and rows containing missing numeric values are dropped. '
        }, '--tree-embedding': {'action': 'store_true', 'dest':
        'tree_embedding', 'default': defaults.get('tree_embedding', None),
        'help':
        'Specify whether to learn a tree-based representation of the data as engineered features along with the raw features, essentially by learning trees over slices of the input space and a small amount of the training data. The theory is that these engineered features will linearize obvious non-linear dependencies before training begins, and so make learning proceed more quickly. '
        }, '--no-balance-fields': {'action': 'store_false', 'dest':
        'balance_fields', 'default': defaults.get('balance_fields', True),
        'help': 'Do not balance fields.'}, '--no-deepnet': {'action':
        'store_true', 'dest': 'no_deepnet', 'default': defaults.get(
        'no_deepnet', False), 'help': 'Do not create a deepnet.'},
        '--deepnet-attributes': {'action': 'store', 'dest':
        'deepnet_attributes', 'default': defaults.get('deepnet_attributes',
        None), 'help': 'Path to a json file describing deepnet attributes.'
        }, '--no-no-depnet': {'action': 'store_false', 'dest': 'no_deepnet',
        'default': defaults.get('no_deepnet', False), 'help':
        'Create a deepnet.'}}
    return options


def render_git_describe(pieces):
    """TAG[-DISTANCE-gHEX][-dirty].

    Like 'git describe --tags --dirty --always'.

    Exceptions:
    1: no tags. HEX[-dirty]  (note: no 'g' prefix)
    """
    if pieces['closest-tag']:
        rendered = pieces['closest-tag']
        if pieces['distance']:
            rendered += '-%d-g%s' % (pieces['distance'], pieces['short'])
    else:
        rendered = pieces['short']
    if pieces['dirty']:
        rendered += '-dirty'
    return rendered


def get_file_size(fp):
    """Get size of the file or length of a bytes object"""
    fp.seek(0, 2)
    size = fp.tell()
    fp.seek(0, 0)
    return size


def textfile_to_int_set(filename):
    """
    读取文本文件，每行一个数据，返回集合
    :param filename:
    :return:
    """
    data = set()
    with open(filename, 'r') as f:
        for line in f.readlines():
            n = len(line)
            if n > 0 and line[n - 1] == '\n':
                line = line[:n - 1]
                n -= 1
            if n == 8:
                data.add(int(line))
    return data


def zerocopy_from_numpy(np_array):
    """Create a tensor that shares the numpy array.

    Parameters
    ----------
    np_array : numpy.ndarray
        The numpy ndarray.

    Returns
    -------
    Tensor
        A framework-specific tensor.
    """
    pass


def no_log_warn(logical_line):
    """Disallow 'LOG.warn('

    Deprecated LOG.warn(), instead use LOG.warning
    https://bugs.launchpad.net/magnum/+bug/1508442

    M352
    """
    msg = 'M352: LOG.warn is deprecated, please use LOG.warning!'
    if 'LOG.warn(' in logical_line:
        yield 0, msg


@staticmethod
def _was_exp_claim_rejected_due_to_clock_skew(network_response):
    """
        Determine whether the network response indicates that the authorization request was rejected because of
        the exp claim. This can happen if the current system time is too different from the Box server time.

        Returns True if the status code is 400, the error code is invalid_grant, and the error description indicates
        a problem with the exp claim; False, otherwise.

        :param network_response:
        :type network_response:
            :class:`Response`
        :rtype:
            `bool`
        """
    status_code = network_response.status_code
    try:
        json_response = network_response.json()
    except ValueError:
        return False
    error_code = json_response.get('error', '')
    error_description = json_response.get('error_description', '')
    return (status_code == 400 and error_code == 'invalid_grant' and 'exp' in
        error_description)


def green(s):
    """
    Return the given string (``s``) surrounded by the ANSI escape codes to
    print it in green.
    :param s: string to console-color green
    :type s: str
    :returns: s surrounded by ANSI color escapes for green text
    :rtype: str
    """
    return '\x1b[0;32m' + s + '\x1b[0m'


def strip_decorator(text, pre_decor='"', post_decor='"'):
    """
    Strip initial and final character sequences (decorators) from a string.

    Args:
        text (str): The text input string.
        pre_decor (str): initial string decorator.
        post_decor (str): final string decorator.

    Returns:
        text (str): the text without the specified decorators.

    Examples:
        >>> strip_decorator('"test"')
        'test'
        >>> strip_decorator('"test')
        'test'
        >>> strip_decorator('<test>', '<', '>')
        'test'
    """
    begin = len(pre_decor) if text.startswith(pre_decor) else None
    end = -len(post_decor) if text.endswith(post_decor) else None
    return text[begin:end]


@classmethod
def index_to_speed(cls, index):
    """
            Convert an index among allowed speeds to its corresponding speed
        :param index: the speed index []
        :return: the corresponding speed [m/s]
        """
    if cls.SPEED_COUNT > 1:
        return cls.SPEED_MIN + index * (cls.SPEED_MAX - cls.SPEED_MIN) / (cls
            .SPEED_COUNT - 1)
    else:
        return cls.SPEED_MIN


def _enumerate(query):
    """Enumerate VDS service queries."""
    while True:
        unk, avail = query.Next(1)
        if not avail:
            return
        yield unk


@property
def fclk1_mhz(cls):
    """The getter method for PL clock 1.

        This method will read the register values, do the calculation,
        and return the current clock rate.

        Returns
        -------
        float
            The returned clock rate measured in MHz.

        """
    return cls.get_pl_clk(1)


def grant_permission_to_role(permission_id, role_id):
    """Bind the permission to the role.
        """


def draw_stroke(snap: bool=False):
    """Start to draw a sketch stroke

    :param snap: Snap
    :type snap: bool
    """
    pass


def _parse_cal_product(cal_product):
    """Split `cal_product` into `cal_stream` and `product_type` parts."""
    fields = cal_product.rsplit('.', 1)
    if len(fields) != 2:
        raise ValueError(
            'Calibration product {} is not in the format <cal_stream>.<product_type>'
            .format(cal_product))
    return fields[0], fields[1]


def decode_response(client_message, to_object=None):
    """ Decode response from client message"""
    parameters = dict(response=None)
    parameters['response'] = client_message.read_bool()
    return parameters


def floor(data=None, out=None, name=None, **kwargs):
    """Returns element-wise floor of the input.

    The floor of the scalar x is the largest integer i, such that i <= x.

    Example::

       floor([-2.1, -1.9, 1.5, 1.9, 2.1]) = [-3., -2.,  1.,  1.,  2.]

    The storage type of ``floor`` output depends upon the input storage type:

       - floor(default) = default
       - floor(row_sparse) = row_sparse
       - floor(csr) = csr

    Defined in src/operator/tensor/elemwise_unary_op_basic.cc:L837

    Parameters
    ----------
    data : NDArray
        The input array.

    out : NDArray, optional
        The output NDArray to hold the result.

    Returns
    -------
    out : NDArray or list of NDArrays
        The output of this function.
    """
    return 0,


def is_iterable(item):
    """ Checks whether an item is an iterable or a singleton.
    >>> is_iterable("hello")
    False
    >>> is_iterable(["hello"])
    True
    >>> is_iterable(2)
    False
    >>> is_iterable([2,])
    True
    >>> print(is_not_iterable(2) == (not is_iterable(2)))
    True
    """
    return isinstance(item, str) is False and hasattr(item, '__iter__')


def validateMCMCKwargs(ap, samplerKwargs, mcmcKwargs, verbose=False):
    """
    Validates emcee.EnsembleSampler parameters/kwargs.

    Parameters
    ----------
    ap : approxposterior.ApproxPosterior
            Initialized ApproxPosterior object
    samplerKwargs : dict
        dictionary containing parameters intended for emcee.EnsembleSampler
        object
    mcmcKwargs : dict
        dictionary containing parameters intended for
        emcee.EnsembleSampler.run_mcmc/.sample object
    verbose : bool (optional)
        verboisty level. Defaults to False (no output)

    Returns
    -------
    samplerKwargs : dict
        Sanitized dictionary containing parameters intended for
        emcee.EnsembleSampler object
    mcmcKwargs : dict
        Sanitized dictionary containing parameters intended for
        emcee.EnsembleSampler.run_mcmc/.sample object
    """
    if samplerKwargs is None:
        samplerKwargs = dict()
        samplerKwargs['ndim'] = ap.theta.shape[-1]
        samplerKwargs['nwalkers'] = 20 * samplerKwargs['dim']
        samplerKwargs['log_prob_fn'] = ap._gpll
    else:
        samplerKwargs.pop('ndim', None)
        samplerKwargs['ndim'] = ap.theta.shape[-1]
        try:
            nwalkers = samplerKwargs['nwalkers']
        except KeyError:
            print(
                'WARNING: samplerKwargs provided but nwalkers not in samplerKwargs'
                )
            print('Defaulting to nwalkers = 20 per dimension.')
            samplerKwargs['nwalkers'] = 20 * samplerKwargs['ndim']
        if 'backend' in samplerKwargs.keys():
            print(
                'WARNING: backend in samplerKwargs. approxposterior creates its own!'
                )
            print(
                'with filename = apRun.h5. Disregarding user-supplied backend.'
                )
        if 'log_prob_fn' in samplerKwargs.keys():
            samplerKwargs.pop('log_prob_fn', None)
        samplerKwargs.pop('backend', None)
        samplerKwargs['log_prob_fn'] = ap._gpll
    if mcmcKwargs is None:
        mcmcKwargs = dict()
        mcmcKwargs['iterations'] = 10000
        mcmcKwargs['initial_state'] = ap.priorSample(samplerKwargs['nwalkers'])
    else:
        try:
            nsteps = mcmcKwargs['iterations']
        except KeyError:
            mcmcKwargs['iterations'] = 10000
            if verbose:
                print(
                    'WARNING: mcmcKwargs provided, but iterations not in mcmcKwargs.'
                    )
                print('Defaulting to iterations = 10000.')
        try:
            p0 = mcmcKwargs['initial_state']
        except KeyError:
            mcmcKwargs['initial_state'] = ap.priorSample(samplerKwargs[
                'nwalkers'])
            if verbose:
                print(
                    'WARNING: mcmcKwargs provided, but initial_state not in mcmcKwargs.'
                    )
                print('Defaulting to nwalkers samples from priorSample.')
    return samplerKwargs, mcmcKwargs


def parameters_ui(layout, params):
    """ Create the ui for the rig parameters."""
    r = layout.row()
    r.prop(params, 'rotation_axis')
    if 'auto' not in params.rotation_axis.lower():
        r = layout.row()
        text = 'Auto align Hand'
        r.prop(params, 'auto_align_extremity', text=text)
    r = layout.row()
    r.prop(params, 'segments')
    r = layout.row()
    r.prop(params, 'bbones')
    for layer in ['fk', 'tweak']:
        r = layout.row()
        r.prop(params, layer + '_extra_layers')
        r.active = params.tweak_extra_layers
        col = r.column(align=True)
        row = col.row(align=True)
        for i in range(8):
            row.prop(params, layer + '_layers', index=i, toggle=True, text='')
        row = col.row(align=True)
        for i in range(16, 24):
            row.prop(params, layer + '_layers', index=i, toggle=True, text='')
        col = r.column(align=True)
        row = col.row(align=True)
        for i in range(8, 16):
            row.prop(params, layer + '_layers', index=i, toggle=True, text='')
        row = col.row(align=True)
        for i in range(24, 32):
            row.prop(params, layer + '_layers', index=i, toggle=True, text='')


def singleline(inp):
    """Join everything to a single line"""
    return inp.replace('\n', '')


@classmethod
def mongo_config_for_collection(cls, collection_name: str=None):
    """
        Return a configuration object of MongoDBManager for given collection_name
        If collection_name in any configuration file then use the configured collection_name
        Else use the given collection_name instead
        """
    if collection_name is None:
        collection_name = cls.COLLECTION_NAME
    if not getattr(cls, collection_name, False):
        collection_name = collection_name
    else:
        collection_name = getattr(cls, collection_name)
    return {'MONGODB_URI': cls.MONGODB_URI, 'DB_NAME': cls.DB_NAME,
        'COLLECTION_NAME': collection_name}


def _to_multipart(name, value, multipart=False):
    """ Update the given :class:`~parameters` with a new inputs using the appropriate form based on `multipart`.
    """
    if multipart:
        return 'tmp_file_%s' % name, value
    else:
        return value


def _calc_video_bitrate(options):
    """
    Calculate video bitrate in kilobits.
    """
    limit_kbits = options.l * 8 * 1024
    vb = limit_kbits / options.outduration - options.ab
    vb = int(vb * 10) / 10
    if vb < 0.001:
        raise Exception(
            """

Unable to calculate video bitrate for the given limit.
Either limit is too low, duration of the video is too long
or audio bitrate is too high.
Consider fixing one of this or just set bitrate manually."""
            )
    return vb


def __init__(A):
    """LocalInstrumentCode - a model defined in Swagger"""
    A.discriminator = None


def FromBytes(p):
    """FromBytes digests the input and returns a Digest.
    """
    from .algorithm import Canonical
    return Canonical.fromBytes(p)


def _auth_plugin_available(ext):
    """Read the value of available for whether to load this plugin."""
    return ext.obj.available


def get_bonds_of_molecule(molecule):
    """
    It returns the atom's indexes for all bonds of a molecule.
    :param molecule: Mol object with the ligand (Rdkit)
    :return: list of tuples with the indexes for each bond
    """
    bonding_idx = []
    for bond in molecule.GetBonds():
        bonding_idx.append((bond.GetEndAtomIdx() + 1, bond.GetBeginAtomIdx(
            ) + 1))
    return bonding_idx


def _content_type_is_json(kwargs):
    """Check whether the content-type in ``kwargs`` is 'application/json'.

    :param kwargs: A ``dict``. The keyword args supplied to :func:`request` or
        one of the convenience functions like it.
    :returns: ``True`` or ``False``

    """
    if 'headers' in kwargs and 'content-type' in kwargs['headers']:
        return kwargs['headers']['content-type'].lower() == 'application/json'
    else:
        return False


def _check_substep(step, step_num, mrc):
    """Raise :py:class:`NotImplementedError` if the given substep
    (e.g. ``'mapper'``) runs subprocesses."""
    substep = step.get(mrc)
    if not substep:
        return
    if substep.get('type') != 'script':
        raise NotImplementedError("step %d's %s has unexpected type: %r" %
            (step_num, mrc, substep.get('type')))
    if substep.get('pre_filter'):
        raise NotImplementedError(
            "step %d's %s has pre-filter, which is unsupported" % (step_num,
            mrc))


def stroke_split():
    """Split selected points as new stroke on same frame

    """
    pass


def __iter__():
    """Iterate over the form fields
        """


@classmethod
def make(cls, testcase, **kw):
    """
        Instantiate, install and add a cleanup for a :class:`LogCapture`.

        :param testcase: This must be an instance of :class:`twisted.trial.unittest.TestCase`.
        :param kw: Any other parameters are passed directly to the :class:`LogCapture` constructor.
        :return: The :class:`LogCapture` instantiated by this method.
        """
    capture = cls(**kw)
    capture.install()
    testcase.addCleanup(capture.uninstall)
    return capture


def p_base_variable_with_function_calls(p):
    """base_variable_with_function_calls : base_variable
                                         | function_call"""
    p[0] = p[1]


@classmethod
def get_version(cls):
    """Cached getting of version."""
    if cls._version is None:
        cls._version = cls._get_version()
    return cls._version


def crop(img, box):
    """
    Crop a numpy image with bounding box (x, y, w, h)
    """
    x, y, w, h = box
    return img[y:y + h, x:x + w]


def properties_context_change(context: str=''):
    """Jump to a different tab inside the properties editor

    :param context: Context
    :type context: str
    """
    pass


def build_query_from_table(name):
    """ Create a query given the table name

    Args:
        name: Table name

    Returns:
        query string
    """
    return 'SELECT * FROM {0}'.format(name)


def plus_or_dot(pieces):
    """Return a + if we don't already have one, else return a ."""
    if '+' in pieces.get('closest-tag', ''):
        return '.'
    return '+'


def refresh_token(client):
    """OneDriveClient->OneDriveClient

    Refresh token of the client.

    The default expire time of one token is 3600 secs.
    """
    client.auth_provider.refresh_token()
    return


def findConfigByID(url):
    """Find an IFeedConfig in IFeedConfigs by its ID.
        """


def _check_api_rate_exceeded(r, exit_loop=False):
    """
    Internal function for catching api exceeded error.

    Parameters
    ----------
    r: dict
        response.json() returned from the Petfinder API.

    Returns
    -------
    None
        raises an error and terminates the program

    """
    if isinstance(r, dict):
        if 'status' in r.keys() and r['status'] == 429:
            if exit_loop:
                print(r['title'])
                return True
            else:
                raise RuntimeError(r['title'])


def fit_into_bounds(image_width, image_height, frame_width, frame_height,
    only_shrink=False):
    """
    Given the w+h of the image and the w+h of the frame,
    return new w+h that fits the image into the frame
    while maintaining the aspect ratio.

    (1920, 1080, 400, 400) -> (400, 225)
    """
    width_ratio = frame_width / image_width
    height_ratio = frame_height / image_height
    ratio = min(width_ratio, height_ratio)
    new_width = int(image_width * ratio)
    new_height = int(image_height * ratio)
    if only_shrink and (new_width > image_width or new_height > image_height):
        return image_width, image_height
    return new_width, new_height


@staticmethod
def get_elastic_mappings(es_major):
    """Get Elasticsearch mapping.

        geopoints type is not created in dynamic mapping

        :param es_major: major version of Elasticsearch, as string
        :returns: dictionary with a key, 'items', with the mapping
        """
    mapping = """
        {
            "properties": {
               "main_description_analyzed": {
                 "type": "text",
                 "index": true
               },
               "releases": {
                 "type": "keyword"
               },
               "body": {
                 "type": "text",
                 "index": true
               }
            }
        }
        """
    return {'items': mapping}


def clean_url(url):
    """Convert user input URL to clean URL."""
    if url.endswith('/api/'):
        url = url[:-5]
    elif url.endswith('/api'):
        url = url[:-4]
    elif url.endswith('/'):
        url = url[:-1]
    return url


def outcome_machine_learner(xdata, ydata, all_a, none_a, ml_model,
    continuous, print_results=True):
    """Function to fit machine learning predictions. Used by TMLE to generate predicted probabilities of outcome
    (i.e. Pr(Y=1 | A=1, L) and Pr(Y=1 | A=0, L)). Future update will include continuous Y functionality (i.e. E(Y))
    """
    try:
        fm = ml_model.fit(X=xdata, y=ydata)
    except TypeError:
        raise TypeError(
            "Currently custom_model must have the 'fit' function with arguments 'X', 'y'. This covers both sklearn and supylearner. If there is a predictive model you would like to use, please open an issue at https://github.com/pzivich/zepid and I can work on adding support"
            )
    if print_results and hasattr(fm, 'summarize'):
        fm.summarize()
    if continuous:
        if hasattr(fm, 'predict'):
            qa1 = fm.predict(all_a)
            qa0 = fm.predict(none_a)
            return qa1, qa0
        else:
            raise ValueError(
                "Currently custom_model must have 'predict' or 'predict_proba' attribute"
                )
    elif hasattr(fm, 'predict_proba'):
        qa1 = fm.predict_proba(all_a)
        qa0 = fm.predict_proba(none_a)
        if qa1.ndim == 1 and qa0.ndim == 1:
            return qa1, qa0
        else:
            return qa1[:, (1)], qa0[:, (1)]
    elif hasattr(fm, 'predict'):
        qa1 = fm.predict(all_a)
        qa0 = fm.predict(none_a)
        return qa1, qa0
    else:
        raise ValueError(
            "Currently custom_model must have 'predict' or 'predict_proba' attribute"
            )


@staticmethod
def get_algorithm(algorithms, algorithm_id):
    """
        From the list of algorithm classes provided, it tries to return an instance of the algorithm at algorithm_id
        :param algorithms: the list of algorithm classes
        :param algorithm: the position of the algorithm class in the list
        :return: instance of the algorithm or falls back to the first algorithm in the list
        """
    if algorithm_id < len(algorithms):
        return algorithms[algorithm_id]()
    return algorithms[0]()


def _dist_wrapper(dist_func, dist_matrix, slice_, *args, **kwargs):
    """Write in-place to a slice of a distance matrix"""
    dist_matrix[:, (slice_)] = dist_func(*args, **kwargs)


@staticmethod
def interface_roles_dont_change_and_tree_transitions_from_active_to_unsure_and_best_upstream_neighbor_is_not_null(
    interface: 'TreeInterfaceDownstream'):
    """
        Tree transitions from Active to Unsure state AND
        BestUpstream neighbor is not null
        """
    interface.logger.debug(
        'interface_roles_dont_change_and_tree_transitions_from_active_to_unsure_and_best_upstream_neighbor_is_not_null'
        )
    interface.send_i_am_no_longer_upstream()
    interface.send_no_interest()


def _is_key_file_encrypted(key_file):
    """Detects if a key file is encrypted or not."""
    with open(key_file, 'r') as f:
        for line in f:
            if 'ENCRYPTED' in line:
                return True
    return False


def round_to(value: float, target: float) ->float:
    """
    Round price to price tick value.
    """
    return int(round(value / target)) * target


@classmethod
def parse_file(cls, filename: str) ->bytes:
    """
            Parse JSON file, return content as string

            :param filename: JSON file path
        """
    with open(filename, 'rb') as f:
        return f.read()


def encode_with(string, encoding):
    """Encoding ``string`` with ``encoding`` if necessary.

    :param str string: If string is a bytes object, it will not encode it.
        Otherwise, this function will encode it with the provided encoding.
    :param str encoding: The encoding with which to encode string.
    :returns: encoded bytes object
    """
    if not (string is None or isinstance(string, bytes)):
        return string.encode(encoding)
    return string


def tan(data=None, name=None, attr=None, out=None, **kwargs):
    """Computes the element-wise tangent of the input array.

    The input should be in radians (:math:`2\\pi` rad equals 360 degrees).

    .. math::
       tan([0, \\pi/4, \\pi/2]) = [0, 1, -inf]

    The storage type of ``tan`` output depends upon the input storage type:

       - tan(default) = default
       - tan(row_sparse) = row_sparse
       - tan(csr) = csr

    Defined in src/operator/tensor/elemwise_unary_op_trig.cc:L140

    Parameters
    ----------
    data : Symbol
        The input array.

    name : string, optional.
        Name of the resulting symbol.

    Returns
    -------
    Symbol
        The result symbol.
    """
    return 0,


def define(zelf, *args, **kwargs):
    """ set a attribute on this ding. """
    name = args[0]
    value = args[1]
    zelf[name] = value


def is_number(string):
    """ Tests if a string is valid float. """
    try:
        float(string)
        return True
    except ValueError:
        return False


def transition_info(content, from_state=None):
    """ Return sequence of dictionaries representing the
        transition information for content (from_state defaults to the
        object's current state).  Each dictionary has the keys
        ``transition_id``, ``from_state``, ``to_state`` as well as any
        keywords passed in to the ``add`` method for this transition."""


def _itemsize(t, item=0):
    """Get non-zero itemsize of type.
    """
    return getattr(t, '__itemsize__', 0) or item


@classmethod
def _get_version(cls):
    """Return VCS program version."""
    return cls._popen(['--version'], merge_err=False)


def bool_encode(d):
    """ Encodes a boolean. """
    return d and '1' or '0'


@classmethod
def _head(cls) ->str:
    """ Return a tsv/csv header """
    cls._io_stream.seek(0)
    cls._io_stream.truncate(0)
    cls._csv_writer.writerow(cls._keys)
    return cls._io_stream.getvalue()


@staticmethod
def int_to_bytestring(i, padding=8):
    """
        Turns an integer to the OATH specified
        bytestring, which is fed to the HMAC
        along with the secret
        """
    result = bytearray()
    while i != 0:
        result.append(i & 255)
        i >>= 8
    return bytes(bytearray(reversed(result)).rjust(padding, b'\x00'))


@staticmethod
def list(filters=None, limit=None, offset=None, order_by=None):
    """
        List dataset parameter records in parameter set.
        """


def tube_inertia(l, m, ro, ri):
    """Calculate the moment of inertia for a tube (or rod) where the x axis is
    aligned with the tube's axis.

    Parameters
    ----------
    l : float
        The length of the tube.
    m : float
        The mass of the tube.
    ro : float
        The outer radius of the tube.
    ri : float
        The inner radius of the tube. Set this to zero if it is a rod instead
        of a tube.

    Returns
    -------
    Ix : float
        Moment of inertia about tube axis.
    Iy, Iz : float
        Moment of inertia about normal axis.

    """
    Ix = m / 2.0 * (ro ** 2 + ri ** 2)
    Iy = m / 12.0 * (3 * ro ** 2 + 3 * ri ** 2 + l ** 2)
    Iz = Iy
    return Ix, Iy, Iz


def atom_total_num_H(atom):
    """Get the total number of Hs of an atom.

    Parameters
    ----------
    atom : rdkit.Chem.rdchem.Atom
        RDKit atom instance.

    Returns
    -------
    list
        List containing one int only.
    """
    return [atom.GetTotalNumHs()]


def getLeaf(work, path):
    """get leaf/branch at *path*."""
    for x in path:
        try:
            work = work[x]
        except KeyError:
            work = None
            break
        except TypeError:
            work = None
            break
    return work


def resolve_name(name):
    """Resolve a name like ``module.object`` to an object and return it.

    Raise `ImportError` if the module or name is not found.
    """
    parts = name.split('.')
    cursor = len(parts) - 1
    module_name = parts[:cursor]
    attr_name = parts[-1]
    while cursor > 0:
        try:
            ret = __import__('.'.join(module_name), fromlist=[attr_name])
            break
        except ImportError:
            if cursor == 0:
                raise
            cursor -= 1
            module_name = parts[:cursor]
            attr_name = parts[cursor]
            ret = ''
    for part in parts[cursor:]:
        try:
            ret = getattr(ret, part)
        except AttributeError:
            raise ImportError(name)
    return ret


def read_viewlayers():
    """Read all the current scene’s view layers from cache, as needed

    """
    pass


def GetGPXtreeItemId(G2frame, parentId, itemText):
    """Find the tree item that matches the text in itemText starting with parentId

    :param wx.Frame G2frame: Data tree frame object
    :param wx.TreeItemId parentId: tree item to start search with
    :param str itemText: text for tree item
    """
    item, cookie = G2frame.GPXtree.GetFirstChild(parentId)
    while item:
        if G2frame.GPXtree.GetItemText(item) == itemText:
            return item
        item, cookie = G2frame.GPXtree.GetNextChild(parentId, cookie)
    return 0


def parse_file_dict(file_dict):
    """
    Return a dictionary with file as keys and content as values.
    """
    result = {}
    for section in file_dict:
        result.update(file_dict[section])
    return result


@classmethod
def match(cls, filename):
    """
        Return True if the current parser should be able to handle that type of
        file
        """
    re_match = cls._filename_re.match(filename)
    return re_match is not None


def question(text: str) ->str:
    """Get text prefixed with a question emoji.

    Returns
    -------
    str
        The new message.

    """
    return '❓ {}'.format(text)


def _get_challenger_module(challenger_name):
    """
    Return given challenger's module, importing it as necessary.
    """
    try:
        imported_module = __import__('tiddlyweb.web.challengers.%s' %
            challenger_name, {}, {}, ['Challenger'])
    except ImportError:
        imported_module = __import__(challenger_name, {}, {}, ['Challenger'])
    return imported_module.Challenger()


def author_last(author_str):
    """ Return the last name of the author """
    return author_str.split(',')[0]


def plus_or_dot(pieces):
    """Return a + if we don't already have one, else return a ."""
    if '+' in pieces.get('closest-tag', ''):
        return '.'
    return '+'


@staticmethod
def indent_block(s: str, spaces=4):
    """Indent a block of code `s`."""
    lines = s.split('\n')
    lines = map(lambda line: ' ' * spaces + line, lines)
    return '\n'.join(lines)


@classmethod
def store(cls, server_url, association):
    """Create an Association instance"""
    raise NotImplementedError('Implement in subclass')


def valid_state(state: str) ->bool:
    """Test if a state is valid."""
    return len(state) < 256


@classmethod
def shared_content_remove_link_password_details(cls, val):
    """
        Create an instance of this class set to the
        ``shared_content_remove_link_password_details`` tag with value ``val``.

        :param SharedContentRemoveLinkPasswordDetails val:
        :rtype: EventDetails
        """
    return cls('shared_content_remove_link_password_details', val)


def my_callback(file_path):
    """Callback for new file"""
    print('New File Created: {:s}'.format(file_path))


def shutdown(isamAppliance, check_mode=False, force=False):
    """
    Shutdown the appliance
    """
    if check_mode is True:
        return isamAppliance.create_return_object(changed=True)
    else:
        return isamAppliance.invoke_post('Shutting down appliance',
            '/diagnostics/restart_shutdown/shutdown', {})


@classmethod
def get(cls, value):
    """
        Lookup an enum by value
        :param value: the value
        """
    if not value in cls.values:
        raise ValueError('There is no enum for value %d' % (value,))
    return cls.values[value]


def ddot(d, mtx, left=True):
    """Multiply a full matrix by a diagonal matrix.
    This function should always be faster than dot.

    Input:
      d -- 1D (N,) array (contains the diagonal elements)
      mtx -- 2D (N,N) array
      left: is the diagonal matrix on the left or on the right of the product?

    Output:
      ddot(d, mts, left=True) == dot(diag(d), mtx)
      ddot(d, mts, left=False) == dot(mtx, diag(d))
    """
    if left:
        return (d * mtx.T).T
    else:
        return d * mtx


def register_interface(interface, omit=(), prefix=None):
    """Create a set of records based on the given interface. For each
        schema field in the interface, a record will be inserted with a
        name like `${interface.__identifier__}.${field.__name__}`, and a
        value equal to default value of that field. Any field with a name
        listed in `omit`, or with the `readonly` property set to True, will
        be ignored. Supply an alternative identifier with `prefix`.
        """


def cache_set(key, value, expires=None, cache=None):
    """Sets the specified key value.

    :param str|unicode key:

    :param str|unicode value:

    :param int expires: Expire timeout (seconds).

    :param str|unicode cache: Cache name with optional address (if @-syntax is used).

    :rtype: bool
    """
    return False


def scan_setup_py():
    """Validate the contents of setup.py against Versioneer's expectations."""
    found = set()
    setters = False
    errors = 0
    with open('setup.py', 'r') as f:
        for line in f.readlines():
            if 'import versioneer' in line:
                found.add('import')
            if 'versioneer.get_cmdclass()' in line:
                found.add('cmdclass')
            if 'versioneer.get_version()' in line:
                found.add('get_version')
            if 'versioneer.VCS' in line:
                setters = True
            if 'versioneer.versionfile_source' in line:
                setters = True
    if len(found) != 3:
        print('')
        print('Your setup.py appears to be missing some important items')
        print('(but I might be wrong). Please make sure it has something')
        print('roughly like the following:')
        print('')
        print(' import versioneer')
        print(' setup( version=versioneer.get_version(),')
        print('        cmdclass=versioneer.get_cmdclass(),  ...)')
        print('')
        errors += 1
    if setters:
        print("You should remove lines like 'versioneer.VCS = ' and")
        print("'versioneer.versionfile_source = ' . This configuration")
        print('now lives in setup.cfg, and should be removed from setup.py')
        print('')
        errors += 1
    return errors


def DeleteContentCb(sender, instance, **_kwargs):
    """
        Connect if content can be deleted without AssignedContent
        beeing deleted.
    """
    instance.associated.delete()


@staticmethod
def read_partition(fs, piece, columns, index, **kwargs):
    """ Read a single piece of a Parquet dataset into a Pandas DataFrame

        This function is called many times in individual tasks

        Parameters
        ----------
        fs: FileSystem
        piece: object
            This is some token that is returned by Engine.read_metadata.
            Typically it represents a row group in a Parquet dataset
        columns: List[str]
            List of column names to pull out of that row group
        index: str, List[str], or False
            The index name(s).
        **kwargs:
            Includes `"kwargs"` values stored within the `parts` output
            of `engine.read_metadata`. May also include arguments to be
            passed to the backend (if stored under a top-level `"read"` key).

        Returns
        -------
        A Pandas DataFrame
        """
    raise NotImplementedError()


@classmethod
def map_get_object_params(cls, request_params, cli_params):
    """Map CLI params to GetObject request params"""
    cls._set_sse_c_request_params(request_params, cli_params)
    cls._set_request_payer_param(request_params, cli_params)


def update_gateway_software_now(GatewayARN=None):
    """
    Updates the gateway virtual machine (VM) software. The request immediately triggers the software update.
    See also: AWS API Documentation

    Examples
    Updates the gateway virtual machine (VM) software. The request immediately triggers the software update.
    Expected Output:

    :example: response = client.update_gateway_software_now(
        GatewayARN='string'
    )

    :type GatewayARN: string
    :param GatewayARN: [REQUIRED]
            The Amazon Resource Name (ARN) of the gateway. Use the ListGateways operation to return a list of gateways for your account and region.

    :rtype: dict
    :return: {
        'GatewayARN': 'string'
    }

    """
    pass


def default_watchlist():
    """If they click "Watchlist View" but are not logged in
    give them a default watchlist"""
    return ','.join(['1288776', '1018724', '1065280', '1467858'])


def instrument(client):
    """
    Auto-instruments code to get nice spans
    """
    from elasticapm.instrumentation.control import instrument
    instrument()
    try:
        import celery
        from elasticapm.contrib.celery import register_instrumentation
        register_instrumentation(client)
    except ImportError:
        client.logger.debug("Not instrumenting Celery, couldn't import")


def results():
    """Get the list of recently modified items"""


def build_absolute_uri(host_url, path=None):
    """Build absolute URI with given (optional) path"""
    path = path or ''
    if path.startswith('http://') or path.startswith('https://'):
        return path
    if host_url.endswith('/') and path.startswith('/'):
        path = path[1:]
    return host_url + path


def fill_element_0index(lhs=None, mhs=None, rhs=None, out=None, name=None,
    **kwargs):
    """Fill one element of each line(row for python, column for R/Julia) in lhs according to index indicated by rhs and values indicated by mhs. This function assume rhs uses 0-based index.

    Parameters
    ----------
    lhs : NDArray
        Left operand to the function.
    mhs : NDArray
        Middle operand to the function.
    rhs : NDArray
        Right operand to the function.

    out : NDArray, optional
        The output NDArray to hold the result.

    Returns
    -------
    out : NDArray or list of NDArrays
        The output of this function.
    """
    return 0,


def box(w=3, h=2):
    """ Create flowchart block

        Parameters
        ----------
        w: float
            Width of box
        h: float
            Height of box

        Anchors: N, S, E, W
    """
    elem = {'name': 'FLOWBOX', 'extend': False, 'lblloc': 'center',
        'lblofst': 0, 'theta': -90}
    elem['paths'] = [[[0, 0], [0, w / 2], [h, w / 2], [h, -w / 2], [0, -w /
        2], [0, 0]]]
    elem['anchors'] = {'W': [h / 2, -w / 2], 'E': [h / 2, w / 2], 'S': [h,
        0], 'N': [0, 0]}
    elem['drop'] = [h, 0]
    return elem


def __new__(cls, string, namespace):
    """
        Constructs a TemplateString.
        This method is required to inherit ``str`` because ``str`` accepts
        only one argument.

        Parameters
        ----------
        string : str
            The contents of TemplateString.
        namespace : dict
            Namespace to be used to render.

        Returns
        -------
        tstr : TemplateString
            Constructed TemplateString.
        """
    return super().__new__(cls, string)


def unquote_header_value(value, is_filename=False):
    """Unquotes a header value.  (Reversal of :func:`quote_header_value`).
    This does not use the real unquoting but what browsers are actually
    using for quoting.

    :param value: the header value to unquote.
    """
    if value and value[0] == value[-1] == '"':
        value = value[1:-1]
        if not is_filename or value[:2] != '\\\\':
            return value.replace('\\\\', '\\').replace('\\"', '"')
    return value


def split_camel_name(name, fall=False):
    """Split camel formated names:

    GenerateURLs => [Generate, URLs]
    generateURLsLite => [generate, URLs, Lite]
    """
    if not name:
        return []
    lastest_upper = name[0].isupper()
    idx_list = []
    for idx, char in enumerate(name):
        upper = char.isupper()
        if upper and not lastest_upper:
            idx_list.append(idx)
        elif fall and not upper and lastest_upper:
            idx_list.append(idx - 1)
        lastest_upper = upper
    l_idx = 0
    name_items = []
    for r_idx in idx_list:
        name_items.append(name[l_idx:r_idx])
        l_idx = r_idx
    name_items.append(name[l_idx:])
    return name_items


def _islinetype(line, testchar):
    """Checks for various kinds of line types based on line head"""
    return line.strip().startswith(testchar)


def get_profiles_by_ids(session, profile_ids):
    """Get storage profiles by IDs.

    :param session: VMwareAPISession instance
    :param profile_ids: profile IDs
    :return: profile objects
    """
    profiles = []
    if profile_ids:
        pbm = session.pbm
        profile_manager = pbm.service_content.profileManager
        profiles = session.invoke_api(pbm, 'PbmRetrieveContent',
            profile_manager, profileIds=profile_ids)
    return profiles


def _rnl_daily(tmax, tmin, ea, fcd):
    """Daily net long-wave radiation  (Eq. 17)

    Parameters
    ----------
    tmax : ee.Image or ee.Number
        Daily maximum air temperature [C].
    tmin : ee.Image or ee.Number
        Daily minimum air temperature [C].
    ea : ee.Image or ee.Number
        Actual vapor pressure [kPa].
    fcd : ee.Image or ee.Number
        cloudiness fraction.

    Returns
    -------
    ee.Image or ee.Number
        Daily net long-wave radiation [MJ m-2 d-1].
        Output data type will match "tmax" data type.

    Notes
    -----
    rnl = 4.901E-9 * fcd * (0.34 - 0.14 * sqrt(ea)) *
          0.5 * ((tmax + 273.16) ** 4 + (tmin + 273.16) ** 4))

    """
    return tmax.add(273.16).pow(4).add(tmin.add(273.16).pow(4)).multiply(0.5
        ).multiply(ea.sqrt().multiply(-0.14).add(0.34)).multiply(fcd).multiply(
        4.901e-09)


def nfa_determinization(nfa: dict) ->dict:
    """ Returns a DFA that reads the same language of the input NFA.

    Let A be an NFA, then there exists a DFA :math:`A_d` such
    that :math:`L(A_d) = L(A)`. Intuitively, :math:`A_d`
    collapses all possible runs of A on a given input word into
    one run over a larger state set.
    :math:`A_d` is defined as:

    :math:`A_d = (Σ, 2^S , s_0 , ρ_d , F_d )`

    where:

    • :math:`2^S` , i.e., the state set of :math:`A_d` , consists
      of all sets of states S in A;
    • :math:`s_0 = S^0` , i.e., the single initial state of
      :math:`A_d` is the set :math:`S_0` of initial states of A;
    • :math:`F_d = \\{Q | Q ∩ F ≠ ∅\\}`, i.e., the collection of
      sets of states that intersect F nontrivially;
    • :math:`ρ_d(Q, a) = \\{s' | (s,a, s' ) ∈ ρ\\ for\\ some\\ s ∈ Q\\}`.

    :param dict nfa: input NFA.
    :return: *(dict)* representing a DFA
    """
    dfa = {'alphabet': nfa['alphabet'].copy(), 'initial_state': None,
        'states': set(), 'accepting_states': set(), 'transitions': dict()}
    if len(nfa['initial_states']) > 0:
        dfa['initial_state'] = str(nfa['initial_states'])
        dfa['states'].add(str(nfa['initial_states']))
    sets_states = list()
    sets_queue = list()
    sets_queue.append(nfa['initial_states'])
    sets_states.append(nfa['initial_states'])
    if len(sets_states[0].intersection(nfa['accepting_states'])) > 0:
        dfa['accepting_states'].add(str(sets_states[0]))
    while sets_queue:
        current_set = sets_queue.pop(0)
        for a in dfa['alphabet']:
            next_set = set()
            for state in current_set:
                if (state, a) in nfa['transitions']:
                    for next_state in nfa['transitions'][state, a]:
                        next_set.add(next_state)
            if len(next_set) == 0:
                continue
            if next_set not in sets_states:
                sets_states.append(next_set)
                sets_queue.append(next_set)
                dfa['states'].add(str(next_set))
                if next_set.intersection(nfa['accepting_states']):
                    dfa['accepting_states'].add(str(next_set))
            dfa['transitions'][str(current_set), a] = str(next_set)
    return dfa


def wien_law(x: float) ->float:
    """Implements Wien's displacement law.

    Parameters
    ----------
    x: float
        Temperature or peak wavelength

    Returns
    -------
    float
    """
    b = 0.002897771955
    return b / x


def gen_file_edit(sig_dic):
    """
    for editing file.
    """
    _ = sig_dic
    view_html = """

    上传图片：

 png,jpg,gif,jpeg格式！大小不得超过500KB

    <input class="pure-button" type="file" name="mymps_img" id="mymps_img1">
    <input class="pure-button" type="file" name="mymps_img" id="mymps_img2">
    <input class="pure-button" type="file" name="mymps_img" id="mymps_img3">
    <input class="pure-button" type="file" name="mymps_img" id="mymps_img4">

    """
    return view_html


def report_info(frame, extrainfo):
    """
    Report on the __traceback_info__ extension.
    """
    f_locals = frame.f_locals
    tb_info = f_locals.get('__traceback_info__', None)
    if tb_info:
        tb_info = str(tb_info)
        extrainfo.add_frame_section(section='Info', style='extension.info',
            content=[tb_info])


def add_global_colorbar(axes_colorbars, figure):
    """
    Add a global colorbar to a figure.

    Parameters
    ----------
    axes_colorbars : dict
    figure : syfigure.Figure
    """
    for ax_id, colorbars in axes_colorbars.items():
        for artist_type, artists in colorbars.items():
            if artists:
                for artist, colorbar_params in artists:
                    if colorbar_params.pop('show', False):
                        figure.colorbar(artist, **colorbar_params)
                        break


def get(isamAppliance, check_mode=False, force=False):
    """
    Retrieve existing fixpacks.
    """
    return isamAppliance.invoke_get('Retrieving fixpacks', '/fixpacks')


@classmethod
def create_from_other(Class, other, values=None):
    """
        Create a new Matrix with attributes taken from `other` but with the
        values taken from `values` if provided
        """
    m = Class()
    m.alphabet = other.alphabet
    m.sorted_alphabet = other.sorted_alphabet
    m.char_to_index = other.char_to_index
    if values is not None:
        m.values = values
    else:
        m.values = other.values
    return m


def _upgrade_state_dict(state):
    """Helper for upgrading old model checkpoints."""
    if 'optimizer_history' not in state:
        state['optimizer_history'] = [{'criterion_name':
            'CrossEntropyCriterion', 'best_loss': state['best_loss']}]
        state['last_optimizer_state'] = state['optimizer']
        del state['optimizer']
        del state['best_loss']
    if 'epoch' in state and 'extra_state' not in state:
        state['extra_state'] = {'epoch': state['epoch'], 'batch_offset':
            state['batch_offset'], 'val_loss': state['val_loss']}
        del state['epoch']
        del state['batch_offset']
        del state['val_loss']
    if 'optimizer' in state['optimizer_history'][-1]:
        state['last_optimizer_state'] = state['optimizer_history'][-1][
            'optimizer']
        for optim_hist in state['optimizer_history']:
            del optim_hist['optimizer']
    if 'optimizer_name' not in state['optimizer_history'][-1]:
        state['optimizer_history'][-1]['optimizer_name'] = 'FairseqNAG'
    if 'lr_scheduler_state' not in state['optimizer_history'][-1]:
        state['optimizer_history'][-1]['lr_scheduler_state'] = {'best':
            state['optimizer_history'][-1]['best_loss']}
        del state['optimizer_history'][-1]['best_loss']
    if 'num_updates' not in state['optimizer_history'][-1]:
        state['optimizer_history'][-1]['num_updates'] = 0
    if hasattr(state['args'], 'max_positions') and not hasattr(state['args'
        ], 'max_source_positions'):
        state['args'].max_source_positions = state['args'].max_positions
        state['args'].max_target_positions = state['args'].max_positions
    if 'train_iterator' not in state['extra_state']:
        state['extra_state']['train_iterator'] = {'epoch': state[
            'extra_state']['epoch'], 'iterations_in_epoch': state[
            'extra_state'].get('batch_offset', 0)}
    return state


def _build_simple_row(padded_cells, rowfmt):
    """Format row according to DataRow format without padding."""
    begin, sep, end = rowfmt
    return (begin + sep.join(padded_cells) + end).rstrip()


def object_add_grid_scale(context):
    """
    Return scale which should be applied on object
    data to align it to grid scale
    """
    space_data = context.space_data
    if space_data and space_data.type == 'VIEW_3D':
        return space_data.grid_scale_unit
    return 1.0


@classmethod
def from_data(cls, data):
    """Construct a mesh from structured data.

        Parameters
        ----------
        data : dict
            The data dictionary.

        Returns
        -------
        object
            An object of the type of ``cls``.

        Note
        ----
        This constructor method is meant to be used in conjuction with the
        corresponding *to_data* method.

        """
    mesh = cls()
    mesh.data = data
    return mesh


def apply_policy(policy, r, name, sub):
    """
    Apply the list of policies to name.r,sub

    Parameters
    ----------
    policy
        List of functions that map a L{Variable} to a string,
        or a single such function.
    r: L{Variable}

    Returns
    -------
    object
        C{policy[0](r) + policy[1](r) + ...}.

    """
    if isinstance(policy, (list, tuple)):
        ret = ''
        for sub_policy in policy:
            ret += sub_policy(r, name, sub)
        return ret
    return policy(r, name, sub)


def binance_interval(interval):
    """ Return the time interval in the specific format allowed by Binance.

    Parameters
    ----------
    interval : int
        Must be in seconds as 60, 180, 300, 900, 1800, 3600, 7200, 14400,
        21600, 28800, 43200, 86400, 259200, 604800, 2592000.

    Returns
    -------
    form : str
        Specific format allowed by Binance.

    Examples
    --------
    >>> binance_interval(7200)
    '2h'

    """
    if interval / 60 in [1, 3, 5, 15, 30]:
        return '{}m'.format(int(interval / 60))
    elif interval / 3600 in [1, 2, 4, 6, 8, 12]:
        return '{}h'.format(int(interval / 3600))
    elif interval / 86400 in [1, 3]:
        return '{}d'.format(int(interval / 86400))
    elif interval == 604800:
        return '1w'
    elif interval == 2592000:
        return '1M'
    else:
        print('No format allowed.')


def update_avg_rating():
    """ update avg rating on catalog """


@classmethod
def num_channels(cls, tensor, data_format='channels_last'):
    """ Return number of channels in the input tensor

        Parameters
        ----------
        tensor : tf.Tensor

        Returns
        -------
        shape : tuple of ints
        """
    shape = tensor.get_shape().as_list()
    axis = cls.channels_axis(data_format)
    return shape[axis]


def get_watch(folder, watches):
    """
    Check if a folder already has a scheduled watch. If so, return it.
    Else return None.
    """
    for watched_folder, watch in watches.items():
        if folder.startswith(watched_folder):
            return watched_folder, watch
    return None, None


def Ntubes_VDI(DBundle=None, Ntp=None, Do=None, pitch=None, angle=30.0):
    """A rough equation presented in the VDI Heat Atlas for estimating
    the number of tubes in a tube bundle of differing geometries and tube
    sizes. No accuracy estimation given.

    Parameters
    ----------
    DBundle : float
        Outer diameter of tube bundle, [m]
    Ntp : float
        Number of tube passes, [-]
    Do : float
        Tube outer diameter, [m]
    pitch : float
        Pitch; distance between two orthogonal tube centers, [m]
    angle : float
        The angle the tubes are positioned; 30, 45, 60 or 90, [degrees]

    Returns
    -------
    N : float
        Number of tubes, [-]

    Notes
    -----
    No coefficients for this method with Ntp=6 are available in [1]_. For
    consistency, estimated values were added to support 6 tube passes, f2 = 90..
    This equation is a rearranged form of that presented in [1]_.
    The calculated tube count is rounded down to an integer.

    Examples
    --------
    >>> Ntubes_VDI(DBundle=1.184, Ntp=2, Do=.028, pitch=.036, angle=30)
    966

    References
    ----------
    .. [1] Gesellschaft, V. D. I., ed. VDI Heat Atlas. 2nd edition.
       Berlin; New York:: Springer, 2010.
    """
    if Ntp == 1:
        f2 = 0.0
    elif Ntp == 2:
        f2 = 22.0
    elif Ntp == 4:
        f2 = 70.0
    elif Ntp == 8:
        f2 = 105.0
    elif Ntp == 6:
        f2 = 90.0
    else:
        raise Exception('Only 1, 2, 4 and 8 passes are supported')
    if angle == 30 or angle == 60:
        f1 = 1.1
    elif angle == 45 or angle == 90:
        f1 = 1.3
    else:
        raise Exception('Only 30, 60, 45 and 90 degree layouts are supported')
    DBundle, Do, pitch = DBundle * 1000, Do * 1000, pitch * 1000
    t = pitch
    Ntubes = (-(-4 * f1 * t ** 4 * f2 ** 2 * Do + 4 * f1 * t ** 4 * f2 ** 2 *
        DBundle ** 2 + t ** 4 * f2 ** 4) ** 0.5 - 2 * f1 * t ** 2 * Do + 2 *
        f1 * t ** 2 * DBundle ** 2 + t ** 2 * f2 ** 2) / (2 * f1 ** 2 * t ** 4)
    return int(Ntubes)


def get_k(count=20):
    """ Calcula o coeficiente multiplicador."""
    return round(2 / (count + 1), 3)


@classmethod
def has_archiving(cls):
    """Returns whether it supports archiving items on the fetch process.

        :returns: this backend supports items archive
        """
    return True


def available_name(domain, template):
    """Return the next available variable name (from template) that is not
    already taken in domain"""
    for i in range(100000):
        name = '{}{}'.format(template, '_' + str(i) if i else '')
        if name not in domain:
            return name


def generate_presigned_url(ClientMethod=None, Params=None, ExpiresIn=None,
    HttpMethod=None):
    """
    Generate a presigned url given a client, its method, and arguments

    :type ClientMethod: string
    :param ClientMethod: The client method to presign for

    :type Params: dict
    :param Params: The parameters normally passed to
            ClientMethod.

    :type ExpiresIn: int
    :param ExpiresIn: The number of seconds the presigned url is valid
            for. By default it expires in an hour (3600 seconds)

    :type HttpMethod: string
    :param HttpMethod: The http method to use on the generated url. By
            default, the http method is whatever is used in the method's model.

    """
    pass


def purge(requestor, service, nodeIdentifier):
    """
        Called when a node purge request has been received.

        @param requestor: The entity the request originated from.
        @type requestor: L{JID<twisted.words.protocols.jabber.jid.JID>}
        @param service: The entity the request was addressed to.
        @type service: L{JID<twisted.words.protocols.jabber.jid.JID>}
        @param nodeIdentifier: The identifier of the node to be purged.
        @type nodeIdentifier: C{unicode}
        """


def serialize_milestone(milestone):
    """
    Milestone object-to-dict serialization
    """
    return {'id': milestone.id, 'name': milestone.name, 'display_name':
        milestone.display_name, 'namespace': milestone.namespace,
        'description': milestone.description}


def bake():
    """Bake dynamic paint image sequence surface

    """
    pass


def zeller(year, month, day):
    """ Calculates the weekday.

    :param year: e.g. 2018
    :param month: 1..12
    :param day: 1..31
    :return: the ISO week date Day-of-Week d (1 = Monday to 7 = Sunday)
    """
    y = year - 1 if month < 3 else year
    q = day
    m = month + 12 if month < 3 else month
    k = y % 100
    j = y // 100
    h = (q + 13 * (m + 1) // 5 + k + k // 4 + j // 4 + 5 * j) % 7
    return (h + 5) % 7 + 1


def p_track_flag_two_channels(t):
    """track_flag : TWO_CHANNEL_AUDIO"""
    from audiotools.toc import TOCFlag_CHANNELS
    t[0] = TOCFlag_CHANNELS(2)


def affine_to_str(transform):
    """ Return a string representatin of an affine.Affine transform
    """
    return ','.join(map(str, transform[:6]))


def get_bytes_per_data_block(header):
    """Calculates the number of bytes in each 60 or 128 sample datablock."""
    bytes_per_block = header['num_samples_per_data_block'] * 4
    bytes_per_block = bytes_per_block + header['num_samples_per_data_block'
        ] * 2 * header['num_amplifier_channels']
    bytes_per_block = bytes_per_block + header['num_samples_per_data_block'
        ] / 4 * 2 * header['num_aux_input_channels']
    bytes_per_block = bytes_per_block + 1 * 2 * header[
        'num_supply_voltage_channels']
    bytes_per_block = bytes_per_block + header['num_samples_per_data_block'
        ] * 2 * header['num_board_adc_channels']
    if header['num_board_dig_in_channels'] > 0:
        bytes_per_block = bytes_per_block + header['num_samples_per_data_block'
            ] * 2
    if header['num_board_dig_out_channels'] > 0:
        bytes_per_block = bytes_per_block + header['num_samples_per_data_block'
            ] * 2
    if header['num_temp_sensor_channels'] > 0:
        bytes_per_block = bytes_per_block + 1 * 2 * header[
            'num_temp_sensor_channels']
    return bytes_per_block


def _nearest_ancestor_table(element):
    """
    Given a BeautifulSoup element, returns the nearest ancestor
    <table> of that element, not including the supplied element
    itself.
    """
    for ancestor in element.parents:
        if ancestor.name == 'table':
            return ancestor
    raise ValueError('Element has no <table> ancestor!')


def addInspectorActionsToMenu(inspectorMenu, execInspectorDialogAction,
    inspectorActionGroup):
    """ Adds menu items to the inpsectorMenu for the given set-inspector actions.

        :param inspectorMenu: inspector menu that will be modified
        :param execInspectorDialogAction: the "Browse Inspectors..." actions
        :param inspectorActionGroup: action group with actions for selecting a new inspector
        :return: the inspectorMenu, which has been modified.
    """
    inspectorMenu.addAction(execInspectorDialogAction)
    inspectorMenu.addSeparator()
    for action in inspectorActionGroup.actions():
        inspectorMenu.addAction(action)
    return inspectorMenu


def prepareImageSignal(button, label, type_, col, row, x, y, xPixel, yPixel):
    """See Plot documentation for content of events"""
    return {'event': 'imageClicked', 'button': button, 'label': label,
        'type': type_, 'col': col, 'row': row, 'x': x, 'y': y, 'xpixel':
        xPixel, 'ypixel': yPixel}


@classmethod
def section_space(cls, text):
    """ After a section sign, insert a non-breaking space. """
    return cls.SECTION_NUMBER_REGEX.sub('\\1 ', text)


def _file_iter_range(fp, offset, bytes, maxread=1024 * 1024):
    """ Yield chunks from a range in a file. No chunk is bigger than maxread."""
    fp.seek(offset)
    while bytes > 0:
        part = fp.read(min(bytes, maxread))
        if not part:
            break
        bytes -= len(part)
        yield part


def closest_points_in_cloud_numpy(points, cloud, threshold=10 ** 7,
    distances=True, num_nbrs=1):
    """Find the closest points in a point cloud to a set of sample points.

    Parameters
    ----------
    points : array, list
        The sample points (n,).
    cloud : array, list
        The cloud points to compare to (n,).
    threshold : float
        Points are checked within this distance.
    distances : bool
        Return distance matrix.

    Returns
    -------
    list
        Indices of the closest points in the cloud per point in points.
    array
        Distances between points and closest points in cloud (n x n).

    Notes
    -----
    Items in cloud further from items in points than threshold return zero
    distance and will affect the indices returned if not set suitably high.

    Examples
    --------
    >>> a = np.random.rand(4, 3)
    >>> b = np.random.rand(4, 3)
    >>> indices, distances = closest_points(a, b, distances=True)
    [1, 2, 0, 3]
    array([[ 1.03821946,  0.66226402,  0.67964346,  0.98877891],
           [ 0.4650432 ,  0.54484186,  0.36158995,  0.60385484],
           [ 0.19562088,  0.73240154,  0.50235761,  0.51439644],
           [ 0.84680233,  0.85390316,  0.72154983,  0.50432293]])

    """
    from numpy import asarray
    from numpy import argmin
    from numpy import argpartition
    from scipy.spatial import distance_matrix
    points = asarray(points).reshape((-1, 3))
    cloud = asarray(cloud).reshape((-1, 3))
    d_matrix = distance_matrix(points, cloud, threshold=threshold)
    if num_nbrs == 1:
        indices = argmin(d_matrix, axis=1)
    else:
        indices = argpartition(d_matrix, num_nbrs, axis=1)
    if distances:
        return indices, d_matrix
    return indices


def get_position_size(insert, risk_per_unit):
    """Returns number of items you can buy with the given insert at the
    given risk.

    Example:
    If you have an max insert to 10$ which you can afford to loose and
    the risk per unit (calculated from the current unit price and its
    stop loss price) is 1$ you can buy 10 units.

    :insert: Max amount of money you set at risk to loose.
    :risk_per_unit: Amount the buy/sell price can raise/fall per unit.
    :returns: Number of units you can buy.
    """
    return insert / risk_per_unit


@classmethod
def from_xml(cls, xml):
    """Returns a new Hangup verb from the given ElementTree object"""
    return cls()


def ignore(_validator, *args):
    """A validator which performs no validation. Used to `ignore` some schema
    fields during validation.
    """
    return


def find_all2(ol, test_func, *args):
    """
        from elist.elist import *
        from elist.jprint import pobj
        def test_func(ele,index,x):
            cond1 = (ele > x)
            cond2 = (index %2 == 0)
            cond = (cond1 & cond2)
            return(cond)

        ol = [1,2,3,4,5,6,7]
        rslt = find_all2(ol,test_func,3)
        pobj(rslt)
    """
    rslt = []
    length = ol.__len__()
    for i in range(0, length):
        cond = test_func(ol[i], i, *args)
        if cond:
            rslt.append({'index': i, 'value': ol[i]})
        else:
            pass
    return rslt


def get_private_command_line(args):
    """ private means don't show password """
    SECRET_PARAMS = ['password', 'command']
    GLOBAL_PARAMS = ['host', 'port', 'login']
    global_options_list = []
    for p in GLOBAL_PARAMS:
        v = getattr(args, p)
        if v:
            global_options_list.append('--%s=%s' % (p, v))
    params = set(vars(args)) - set(SECRET_PARAMS + GLOBAL_PARAMS)
    options_list = []
    for p in params:
        v = getattr(args, p)
        if v:
            options_list.append('--%s=%s' % (p, v))
    params = {'global_options': ' '.join(global_options_list), 'command':
        args.command, 'options': ' '.join(options_list)}
    return 'vg_api %(global_options)s %(command)s %(options)s' % params


def stock_sort_key(item, max_amount):
    """Sort by increasing amount but ensure that negative amounts are
    sorted first.  max_amount is the maximum amount found in the stock.

    """
    amount = item['amount']
    if amount < 0:
        amount = max_amount - amount
    return -amount


def do_mark_as_read(session, message_indicies):
    """ Mark all given messages read. """
    session.user['readmsgs'] = session.user.get('readmsgs', set()) | set(
        message_indicies)


def dibujar(símismo, ejes, fig):
    """
        Agrega la forma a la figura.

        Parameters
        ----------
        ejes:
            Los ejes de la figura.
        fig:
            La figura.

        """
    raise NotImplementedError


def transforms_clear():
    """Reset location, rotation, and scaling of selected bones to their default values

    """
    pass


def split_cli(line):
    """
    we'd like to use shlex.split() but that doesn't work well for
    windows types of things.  for now we'll take the easy approach
    and just split on space. We'll then cycle through and look for leading
    quotes and join those lines
    """
    parts = line.split(' ')
    final = []
    while len(parts) > 0:
        tok = parts.pop(0)
        if tok[:1] == '"':
            tok = tok[1:]
            next = parts.pop(0)
            while next[-1:] != '"' and len(parts) > 0:
                tok += ' ' + next
                next = parts.pop(0)
            if next[-1:] == '"':
                tok += ' ' + next[:-1]
        final.append(tok)
    return final


def setserver(value):
    """
    Sets the default server and port for remote access.
    """
    global NX_SERVER
    NX_SERVER = value


@staticmethod
def midpoint(start, end):
    """Returns the midpoint between two dates"""
    return start + (end - start) / 2


def myst_extensions(no_md=False):
    """The allowed extensions for the myst format."""
    if no_md:
        return ['.myst', '.mystnb', '.mnb']
    return ['.md', '.myst', '.mystnb', '.mnb']


@classmethod
def from_sec(cls, float_secs):
    """
        Create new TVal instance using time.time() value (float
        seconds)

        :param float_secs: time value in time.time() format, ``float``
        :returns: :class:`TVal` instance for specified time
        """
    secs = int(float_secs)
    nsecs = int((float_secs - secs) * 1000000000)
    return cls(secs, nsecs)


@classmethod
def rewind_folder_details(cls, val):
    """
        Create an instance of this class set to the ``rewind_folder_details``
        tag with value ``val``.

        :param RewindFolderDetails val:
        :rtype: EventDetails
        """
    return cls('rewind_folder_details', val)


def parse(arg_list):
    """
        Parse the argument list (i.e. sys.argv).  Can return any object as
        long as it's members contain those of the added arguments.  For
        example, if adding a '-v/--version' option that stores to the dest of
        'version', then the member must be callable as 'Object().version'.

        :param arg_list: A list of command line arguments.
        :returns: Callable object

        """


def subscriptions(requestor, service):
    """
        Called when a subscriptions retrieval request has been received.

        @param requestor: The entity the request originated from.
        @type requestor: L{JID<twisted.words.protocols.jabber.jid.JID>}
        @param service: The entity the request was addressed to.
        @type service: L{JID<twisted.words.protocols.jabber.jid.JID>}
        @return: A deferred that fires with a C{list} of subscriptions as
                 L{Subscription<wokkel.pubsub.Subscription>}.
        @rtype: L{Deferred<twisted.internet.defer.Deferred>}
        """


def format_time(t):
    """Format seconds into a human readable form."""
    m, s = divmod(t, 60)
    h, m = divmod(m, 60)
    d, h = divmod(h, 24)
    w, d = divmod(d, 7)
    if w:
        return '{0:2.0f}w{1:2.0f}d'.format(w, d)
    elif d:
        return '{0:2.0f}d{1:2.0f}h'.format(d, h)
    elif h:
        return '{0:2.0f}h{1:2.0f}m'.format(h, m)
    elif m:
        return '{0:2.0f}m{1:2.0f}s'.format(m, s)
    else:
        return '{0:5.0f}s'.format(s)


@classmethod
def parse(cls, fp, data_objects=None, close=True, split_columns=True, **
    fmt_params):
    """
            Files are sniffed for the used csv dialect, but an optional set of
            formatting parameters can be passed that will override the sniffed
            parameters.
        """
    filename, f, close = cls._get_file(fp, close=close)
    fmt_params, has_header, file_start = cls.sniff(f, **fmt_params)
    data_objects = cls._parse_header(filename, f, data_objects=data_objects,
        split_columns=split_columns, has_header=has_header, file_start=
        file_start, **fmt_params)
    data_objects = cls._parse_data(filename, f, data_objects=data_objects,
        split_columns=split_columns, has_header=has_header, **fmt_params)
    if close:
        f.close()
    return data_objects


@staticmethod
def _dimensions_to_values(dimensions):
    """
        Replace dimensions specs with their `dimension`
        values, and ignore those without
        """
    values = []
    for dimension in dimensions:
        if isinstance(dimension, dict):
            if 'extractionFn' in dimension:
                values.append(dimension)
            elif 'dimension' in dimension:
                values.append(dimension['dimension'])
        else:
            values.append(dimension)
    return values


def __new__(cls, s, bits):
    """Create a bit string instance,

        `s`,
            Bytes representing the binary part of bit-string
        `bits`,
            count value from 0 to 8 representing valid number bits in the last
            byte of `s`.
        """
    obj = super().__new__(cls, s)
    obj.bits = bits
    obj.s = s
    return obj


def parse_uri(uri):
    """Parses a BIP21 Payment URI into this class"""


@staticmethod
def _build_repr_for_class(props, class_name, parent_path_str=None):
    """
        Helper to build representation string for a class

        Parameters
        ----------
        class_name : str
            Name of the class being represented
        parent_path_str : str of None (default)
            Name of the class's parent package to display
        props : dict
            Properties to unpack into the constructor

        Returns
        -------
        str
            The representation string
        """
    from plotly.utils import ElidedPrettyPrinter
    if parent_path_str:
        class_name = parent_path_str + '.' + class_name
    if len(props) == 0:
        repr_str = class_name + '()'
    else:
        pprinter = ElidedPrettyPrinter(threshold=200, width=120)
        pprint_res = pprinter.pformat(props)
        body = '   ' + pprint_res[1:-1].replace('\n', '\n   ')
        repr_str = class_name + '({\n ' + body + '\n})'
    return repr_str


def star_sum(*args):
    """ Star Sum: Add All Args
    Similar to accumulate, but takes an arbitrary number of arguments.

    DocTests:
    >>> star_sum(1)
    1
    >>> star_sum(1, 2)
    3
    >>> star_sum(1, 2, 3)
    6
    >>> star_sum(1, 2, 3, 4)
    10

    @param args: Numbers to be summed.
    @return: Sum of all arguments.
    """
    return sum(args)


def build_position(poslist):
    """
    Construct a L{Position} object that takes the other positions as include list.

    @param poslist: Sequence of positions to report. First entry is the innermost position,
                    last entry is the nml statement that started it all.
    @type  poslist: C{list} of L{Position}

    @return: Position to attach to an error.
    @rtype:  L{Position}
    """
    if poslist is None or len(poslist) == 0:
        return None
    if len(poslist) == 1:
        return poslist[0]
    pos = poslist[-1]
    pos.includes = pos.includes + poslist[:-1]
    return pos


def __exit__(exc_type, exc_val, exc_tb):
    """Makes it possible to use with the context manager protocol"""


def pas_group():
    """
        Returns tuple of group name/id, group title to be used.

        Given group base name like 'viewers' or 'managers', composes
        a unique PAS group name using self.namespace (usually UUID)
        and group name.  Title is composed using title components of
        workspace and its parent hierarchy, along with the group base
        name/title.
        """


def load_fai(fname):
    """
    Load fai index of fasta created by samtools

    Parameters
    -----
    fname : str
        input fai file name

    Returns
    -----
    dict
         chromsome and start / end position in file

    """
    faidx = {}
    with open(fname, 'r') as f:
        for line in f:
            content = line.rstrip().split('\t')
            chrom, length, start, eff_length, line_length = content
            shift_length = int(length) * int(line_length) / int(eff_length)
            faidx[chrom] = [int(start), shift_length]
    return faidx


@classmethod
def process_token_augmentations(cls, value, token_attr):
    """ Uses any found augmentations from the TokenAttr to augment the final rendered value.  Currently
            this only processes the augmentations:
                TokenAttr().case
                TokenAttr().prefix
                TokenAttr().suffix

        :param value: str, the resulting rendered string from the TokenAttr
        :param token_attr: nomenclate.core.tokens.TokenAttr, the processed TokenAttr to be used to query settings.
        :return: str, final augmented string
        """
    return '{}{}{}'.format(token_attr.prefix, getattr(str, token_attr.case,
        str)(value), token_attr.suffix)


def is_variable_geometry(xmldoc):
    """
     Tries to guess whether the calculation involves changes in
     geometry.
     """
    itemlist = xmldoc.getElementsByTagName('module')
    for m in itemlist:
        if 'serial' in list(m.attributes.keys()):
            if 'dictRef' in list(m.attributes.keys()):
                if m.attributes['dictRef'].value == 'Single-Point':
                    return False
                else:
                    return True
    return False


def _get_overfit_counts(Nt1o1, Nt0o1, Nt1o0, Nt0o0, func=sum):
    """Calculate counts of causal behavior under assumption: all treated are
    persuadables, and these are the only persuadables.

    Determining the number of persuadables, sure things, lost causes, and
    sleeping dogs is impossible, but we can do so if we make assumptions and
    follow these assumptions to their logical end. We can then calculate
    maximal qini curves.

    In this case, we assume that all those with a positive outcome in the
    treatment group are persuadables, and that these are the only persuadables.
    In almost all circumstances, this combination of counts are impossible, but
    they do provide the points for the absolute maximal qini curve possible.

    Parameters
    ----------
    Nt1o1 : int
        Number of entries where (treatment, outcome) == (1,1).
    Nt0o1 : int
        Number of entries where (treatment, outcome) == (0,1).
    Nt1o0 : int
        Number of entries where (treatment, outcome) == (1,0).
    Nt0o0 : int
        Number of entries where (treatment, outcome) == (0,0).
    func : function
        Function to process tuples before output is returned. `sum` is typical,
        but an identity function can be passed if you want to keep the tuples.

    Returns
    -------
    persuadables : func(tuple)
        Number of persuadables in control and treatment, respectively, under the given assumption.
    dogs : func(tuple)
        Number of sleeping dogs, in control and treatment, respectively, under the given assumption.
    sure_things : func(tuple)
        Number of sure things, in control and treatment, respectively, under the given assumption.
    lost_causes : func(tuple)
        Number of lost causes, in control and treatment, respectively, under the given assumption.

    """
    persuadables = 0, Nt1o1
    dogs = Nt0o1, 0
    sure_things = 0, 0
    lost_causes = Nt0o0, Nt1o0
    return func(persuadables), func(dogs), func(sure_things), func(lost_causes)


def set_dimensions(dimensions):
    """
    Set properly dimensions that we want to load
    @dimensions: list
    """
    result = []
    for i in dimensions:
        d = {'name': i}
        result.append(d)
    return result


def move_individual(destination_rank, destination_index, source_rank,
    source_index):
    """
    Move an archive individual from one rank to another rank.
    This function does not check bounds or make any other safety guarantees.
    This function assumes that the individual is valid and adjusts
    occupancy accordingly.

    destination_rank (Rank)
    destination_index (int): index into destination_rank
    source_rank (Rank)
    source_index (int): index into source_rank

    Returns an updated destination rank and source rank.
    """
    individual = source_rank.individuals[source_index]
    destination_rank.individuals[destination_index] = individual
    destination_rank = destination_rank._replace(occupancy=destination_rank
        .occupancy + 1)
    source_rank.individuals[source_index] = individual._replace(valid=False)
    source_rank = source_rank._replace(occupancy=source_rank.occupancy - 1)
    return destination_rank, source_rank


def create_new_label(check_label, label_map, row, col, label):
    """
    A function to create new label if non-exist label neighborhood
    """
    if check_label == False:
        label += 1
        label_map[row][col].label = label
    return label_map, label


@staticmethod
def show_vpp_devices(devices, show_interfaces=True, show_header=True):
    """
        show the vpp devices specified in the argument

        :param devices: A list of devices
        :param show_interfaces: show the kernel information
        :param show_header: Display the header if true
        :type devices: dict
        :type show_interfaces: bool
        :type show_header: bool
        """
    if show_interfaces:
        header = '{:15} {:25} {:50}'.format('PCI ID', 'Kernel Interface(s)',
            'Description')
    else:
        header = '{:15} {:50}'.format('PCI ID', 'Description')
    dashseparator = '-' * (len(header) - 2)
    if show_header is True:
        print(header)
        print(dashseparator)
    for dit in devices.items():
        dvid = dit[0]
        device = dit[1]
        if show_interfaces:
            interfaces = device['interfaces']
            interface = ''
            for i, j in enumerate(interfaces):
                if i > 0:
                    interface += ',' + interfaces[i]
                else:
                    interface = interfaces[i]
            print('{:15} {:25} {:50}'.format(dvid, interface, device[
                'description']))
        else:
            print('{:15} {:50}'.format(dvid, device['description']))


def unauthenticated_userid(request):
    """
    Helper method for getting the `unauthenticated_userid` value from a
    request. For pyramid >= 1.5 `unauthenticated_userid` is an attribute
    on the request object. For older pyramid versions, before 1.5,
    `unauthenticated_userid` is a helper method in `pyramid.security`.
    """
    try:
        return request.unauthenticated_userid
    except AttributeError:
        try:
            from pyramid.security import unauthenticated_userid
            return unauthenticated_userid(request)
        except ImportError:
            return None


def dummynum(character, name):
    """Count how many nodes there already are in the character whose name
    starts the same.

    """
    num = 0
    for nodename in character.node:
        nodename = str(nodename)
        if not nodename.startswith(name):
            continue
        try:
            nodenum = int(nodename.lstrip(name))
        except ValueError:
            continue
        num = max((nodenum, num))
    return num


def grant_permission_to_role_no_inherit(permission_id, role_id):
    """Assign the role to the principal without local inherit."""


def fitness(gen, sp):
    """Constant positive selection pressure."""
    return [1, 1.01, 1.02]


@classmethod
def started_enterprise_admin_session_details(cls, val):
    """
        Create an instance of this class set to the
        ``started_enterprise_admin_session_details`` tag with value ``val``.

        :param StartedEnterpriseAdminSessionDetails val:
        :rtype: EventDetails
        """
    return cls('started_enterprise_admin_session_details', val)


def p_newlines(p):
    """ newlines : NEWLINE
                 | newlines NEWLINE """
    pass


def is_frontier(node):
    """
    Find if a node is a frontier node
    """
    itrans = node.incoming_trans
    if itrans == []:
        return True
    else:
        for trans in itrans:
            if trans.ori.is_start():
                return True
    return False


@staticmethod
def add_arguments(parser, window=None, fft_size=None):
    """
        Add STFT related arguments to an existing parser.

        Parameters
        ----------
        parser : argparse parser instance
            Existing argparse parser.
        window : numpy ufunc, optional
            Window function.
        fft_size : int, optional
            Use this size for FFT (should be a power of 2).

        Returns
        -------
        argparse argument group
            STFT argument parser group.

        Notes
        -----
        Parameters are included in the group only if they are not 'None'.

        """
    g = parser.add_argument_group('short-time Fourier transform arguments')
    if window is not None:
        g.add_argument('--window', dest='window', action='store', default=
            window, help='window function to use for FFT')
    if fft_size is not None:
        g.add_argument('--fft_size', action='store', type=int, default=
            fft_size, help=
            'use this size for FFT (should be a power of 2) [default=%(default)i]'
            )
    return g


def redo():
    """Redo previous action

    """
    pass


def disabled(func):
    """Disable a function previously decorated with a listener like registerSignal.

	If the decorated function (`func`) has been decorated with :any:`registerSignal`,
	:any:`registerEventFilter` or some other kind of listener decorator, the decorated function
	will not be called anymore when a matching signal is emitted or a event has to pass in a
	filter, until it is enabled again.

	This decorator simply sets an ``enabled`` attribute on the decorated function to False.
	To re-enable the disabled function, just set the ``enabled`` attribute to True.

	When the function is re-enabled, missed signals and events will not cause the decorated
	function to be called, but upcoming signals/events will trigger the decorated function.

	Since functions decorated with :any:`registerSetup` can be triggered only when an object
	_starts_ matching categories, re-enabling such a function will not catch-up the setup of
	an object.
	"""
    func.enabled = False
    return func


def bytes2NativeString(x, encoding='utf-8'):
    """
    Convert C{bytes} to a native C{str}.

    On Python 3 and higher, str and bytes
    are not equivalent.  In this case, decode
    the bytes, and return a native string.

    On Python 2 and lower, str and bytes
    are equivalent.  In this case, just
    just return the native string.

    @param x: a string of type C{bytes}
    @param encoding: an optional codec, default: 'utf-8'
    @return: a string of type C{str}
    """
    if isinstance(x, bytes) and str != bytes:
        return x.decode(encoding)
    return x


def nd(fsm, group, phi):
    """
    Return the set of states of fsm satisfying nD<group> phi

    fsm -- a MAS representing the system
    group -- a non-empty list of (str) names of agents of fsm
    phi -- a BDD representing the set of states of fsm satisfying phi
    """
    return fsm.equivalent_states(phi & fsm.reachable_states, frozenset(group)
        ) & fsm.reachable_states


def logger(msg):
    """ Common method for writing debug information in a file """
    msg = str(msg)
    if not msg.endswith('\n'):
        msg += '\n'
    try:
        fh = open('report.log', 'a')
        fh.write(msg)
        fh.close()
    except Exception:
        pass


def inttohex(n):
    """Convert int to lower-case hex."""
    return '0x{:x}'.format(n)


def htmlList(list):
    """
    Converts a list of strings to an HTML

 structure.
    """
    s = '
'
    for x in list:
        s += '
' + str(x) + '
'
    s += '
'
    return s


def p_log_op_or(p):
    """log_op : expr OR expr"""
    p[0] = 'or', p[1], p[3]


def do_list(value):
    """Convert the value into a list.  If it was a string the returned list
    will be a list of characters.
    """
    return list(value)


def glInitNames():
    """Initialize the name stack

    """
    pass


def _get_poverty_statistics(dataframe, state_code, county_code):
    """
    Calculates poverty-rate of people living below certain threshold

    :param dataframe: Containing poverty data

    :param int state_code:

    :param int county_code:

    :return float:

    """
    dataframe.columns = ['STATE', 'COUNTY', 'NAME', 'POV']
    df = dataframe[dataframe.STATE == int(state_code)]
    if len(df) > 0:
        df = df[df.COUNTY == int(county_code)]
        return float(df['POV'].values[0])
    else:
        return 0


def join_path(a, b):
    """
    Join two URL path segments together.
    Unlike ``os.path.join``, this removes leading slashes before joining the
    paths, so absolute paths are appended as if they were relative.

    Synopsis::

        >>> join_path('/', '/abc')
        '/abc'

        >>> join_path('/', '/abc/')
        '/abc/'

        >>> join_path('/foo', '/bar/')
        '/foo/bar/'

        >>> join_path('/foo/', '/bar/')
        '/foo/bar/'

        >>> join_path('/foo', 'bar')
        '/foo/bar'
    """
    if not b:
        return a
    while a and a[-1] == '/':
        a = a[:-1]
    while b and b[0] == '/':
        b = b[1:]
    return a + '/' + b


def make_vector(dim, init_value):
    """
    Return a list of dim copies of init_value
    """
    return [init_value] * dim