@classmethod
def from_int(cls, x, length, bitorder='big', *, signed=False):
    """Represent the Python int x as a BitString.
        Acts similarly to int.to_bytes.

        :param int x:
            An integer to represent. Negative integers are represented in two's
            complement form, unless the argument signed is False, in which case
            negative integers raise an OverflowError.

        :param int length:
            The length of the resulting BitString. An OverflowError is raised
            if the integer is not representable in this many bits.

        :param bitorder:
            Determines the bit order used in the BitString representation. By
            default, this function uses Postgres conventions for casting ints
            to bits. If bitorder is 'big', the most significant bit is at the
            start of the string (this is the same as the default). If bitorder
            is 'little', the most significant bit is at the end of the string.

        :param bool signed:
            Determines whether two's complement is used in the BitString
            representation. If signed is False and a negative integer is given,
            an OverflowError is raised.

        :return BitString: A BitString representing the input integer, in the
                           form specified by the other input args.

        .. versionadded:: 0.18.0
        """
    if length < 0:
        raise ValueError('length argument must be non-negative')
    elif length < x.bit_length():
        raise OverflowError('int too big to convert')
    if x < 0:
        if not signed:
            raise OverflowError("can't convert negative int to unsigned")
        x &= (1 << length) - 1
    if bitorder == 'big':
        pass
    elif bitorder == 'little':
        x = int(bin(x)[:1:-1].ljust(length, '0'), 2)
    else:
        raise ValueError("bitorder must be either 'big' or 'little'")
    x <<= -length % 8
    bytes_ = x.to_bytes((length + 7) // 8, byteorder='big')
    return cls.frombytes(bytes_, length)


@classmethod
def find_all(cls, deleted=False):
    """Returns all tracks with positive weight."""
    cond = '1' if deleted else 'weight > 0'
    return cls.where(cond)


@classmethod
def save_all(cls, objs):
    """
        在一个请求中 save 多个 leancloud.Object 对象实例。

        :param objs: 需要 save 的对象
        :type objs: list
        """
    if not objs:
        return
    return cls()._deep_save(objs, [])


def authGSSClientUserName(context):
    """
    Get the user name of the principal authenticated via the now complete
    GSSAPI client-side operations, or the current user name obtained via
    authGSSClientInquireCred. This method must only be called after
    authGSSClientStep or authGSSClientInquireCred return a complete response
    code.

    @param context: The context object returned from L{authGSSClientInit}.

    @return: A string containing the user name.
    """


def remap_name(name_generator, names, table=None):
    """
    Produces a series of variable assignments in the form of::

        <obfuscated name> = <some identifier>

    for each item in *names* using *name_generator* to come up with the
    replacement names.

    If *table* is provided, replacements will be looked up there before
    generating a new unique name.
    """
    out = ''
    for name in names:
        if table and name in table[0].keys():
            replacement = table[0][name]
        else:
            replacement = next(name_generator)
        out += '%s=%s\n' % (replacement, name)
    return out


def enter_new_scope(ctx):
    """
    we inside new scope with it onw
    :param ctx:
    :return:
    """
    ctx = ctx.clone()
    ctx.waiting_for = ctx.compiled_story().children_matcher()
    return ctx


def true_solar_time_min(equation_of_time, long, local_tz):
    """Returns True Solar time in minutes, with Equation of Time, equation_of_time,
    Longitude, long and Local Time Zone, local tz."""
    true_solar_time = (0.5 * 1440 + equation_of_time + 4 * long - 60 * local_tz
        ) % 1440
    return true_solar_time


def destroy():
    """
        Destroys the result view
        """


def list_team_players(dataframe, team):
    """Lists the players in `dataframe` who took shots for a `team`"""
    return dataframe.loc[dataframe['team'] == team].groupby('shots_by'
        ).shots_by.count().reset_index(name='count').sort_values(['count'],
        ascending=False)


def intersection(other, self_weight, other_weight):
    """Given BTrees.IFBTree data structure, return weighted intersection"""


def _mw_dist(game, mix):
    """Distributional multiplicative weights payoff function"""
    return game.deviation_payoffs(mix)


def is_iterable(obj):
    """ Return True if `obj` is iterable
    """
    try:
        iter(obj)
    except TypeError:
        return False
    return True


def write_config(config, config_template, config_path):
    """Writes a new config file based upon the config template.

    :param config: A dict containing all the key/value pairs which should be
                   used for the new configuration file.
    :param config_template: The config (jinja2-)template.
    :param config_path: The place to write the new config file.
    """
    with open(config_path, 'wb') as cfg_file:
        cfg_file.write(config_template.render(**config).encode('utf-8'))


def patch_http_development_server():
    """
    HACK: without HTTP/1.1, Chrome ignores certain cache headers during development!
     see http://stackoverflow.com/a/28033770/179583 for a bit more discussion.

    You can include this in your wsgi.py file.

    """
    from wsgiref import simple_server
    simple_server.ServerHandler.http_version = '1.1'


def poll_for_third_party_jobs(actionTypeId=None, maxBatchSize=None):
    """
    Determines whether there are any third party jobs for a job worker to act on. Only used for partner actions.
    See also: AWS API Documentation

    :example: response = client.poll_for_third_party_jobs(
        actionTypeId={
            'category': 'Source'|'Build'|'Deploy'|'Test'|'Invoke'|'Approval',
            'owner': 'AWS'|'ThirdParty'|'Custom',
            'provider': 'string',
            'version': 'string'
        },
        maxBatchSize=123
    )

    :type actionTypeId: dict
    :param actionTypeId: [REQUIRED]
            Represents information about an action type.
            category (string) -- [REQUIRED]A category defines what kind of action can be taken in the stage, and constrains the provider type for the action. Valid categories are limited to one of the values below.
            owner (string) -- [REQUIRED]The creator of the action being called.
            provider (string) -- [REQUIRED]The provider of the service being called by the action. Valid providers are determined by the action category. For example, an action in the Deploy category type might have a provider of AWS CodeDeploy, which would be specified as CodeDeploy.
            version (string) -- [REQUIRED]A string that identifies the action type.

    :type maxBatchSize: integer
    :param maxBatchSize: The maximum number of jobs to return in a poll for jobs call.

    :rtype: dict
    :return: {
        'jobs': [
            {
                'clientId': 'string',
                'jobId': 'string'
            },
        ]
    }

    """
    pass


def rpartition(text, sep):
    """
    Splits ``text`` at the last occurrence of ``sep``, returning the result as 3-tuple.

    If the separator is not found, this function a 3-tuple containing two empty strings,
    followed by the string itself.

    :return: a 3-tuple containing the part before the separator, the separator itself, and the part after the separator.
    :rtype:  ``tuple`` of ``str``
    """
    assert isinstance(text, str), '%s is not a string' % text
    return text.rpartition(sep)


def launch(url, wait=False, locate=False):
    """This function launches the given URL (or filename) in the default
    viewer application for this file type.  If this is an executable, it
    might launch the executable in a new session.  The return value is
    the exit code of the launched application.  Usually, ``0`` indicates
    success.

    Examples::

        click.launch('https://click.palletsprojects.com/')
        click.launch('/my/downloaded/file', locate=True)

    .. versionadded:: 2.0

    :param url: URL or filename of the thing to launch.
    :param wait: waits for the program to stop.
    :param locate: if this is set to `True` then instead of launching the
                   application associated with the URL it will attempt to
                   launch a file manager with the file located.  This
                   might have weird effects if the URL does not point to
                   the filesystem.
    """
    from ._termui_impl import open_url
    return open_url(url, wait=wait, locate=locate)


def path_for(objectid):
    """ Return the path tuple for objectid """


@classmethod
def _from_dict(cls, _dict):
    """Initialize a TargetedSentimentResults object from a json dictionary."""
    args = {}
    if 'text' in _dict:
        args['text'] = _dict.get('text')
    if 'score' in _dict:
        args['score'] = _dict.get('score')
    return cls(**args)


@classmethod
def tearDownClass(cls):
    """
        recycing request session and clean everything
        :return:
        """
    pass


def urljoin(netloc, port, ssl):
    """
    Basically the counter-part of :func:`urlsplit`.
    """
    rv = ('https' if ssl else 'http') + '://' + netloc
    if ssl and port != 443 or not ssl and port != 80:
        rv += ':%i' % port
    return rv


def make_vector(position, joints, velocity):
    """
    A convenience method to make a vector from a list of positions, a list of joints,
    and a list of velocities.

    :param position: A list of servo positions.
    :param joints: A list of servo ids.
    :param velocity: The velocities at which to move each joint.

    :returns: A vector.

    """
    vector = []
    for i in range(len(joints)):
        vector.append((joints[i], position[i], velocity[i]))
    return vector


def try_encode(string, enc):
    """turn unicode encoding into a functional routine"""
    try:
        return string.encode(enc)
    except UnicodeEncodeError:
        return None


def save_to_disk(obj, fname, **dump_opts):
    """Save an object to disk using joblib.dump.
    """
    import joblib
    return joblib.dump(obj, fname, **dump_opts)


def __call__(context, request):
    """ Provide content."""


def joinStringsInList(literalEntities, prefLanguage='en'):
    """
    from a list of literals, returns the ones in prefLanguage joined up.
    if the desired language specification is not available, join all up
    """
    match = []
    if len(literalEntities) == 1:
        return literalEntities[0]
    elif len(literalEntities) > 1:
        for x in literalEntities:
            if getattr(x, 'language') and getattr(x, 'language'
                ) == prefLanguage:
                match.append(x)
        if not match:
            for x in literalEntities:
                match.append(x)
    return ' - '.join([x for x in match])


def minute():
    """
    Return millis for a minute
    :return: 60 * 1000
    """
    return 60000


@classmethod
def dynamorm_fields(cls):
    """Returns a dictionary of key value pairs where keys are attributes and values are type classes"""
    raise NotImplementedError('{0} class must implement dynamallow_fields'.
        format(cls.__name__))


def get_transformed_name(name, transform):
    """
    Consistent way of transforming names

    Parameters
    ----------
    name : str
        Name to transform
    transform : transforms.Transform
        Should be a subclass of `transforms.Transform`

    Returns
    -------
    str
        A string to use for the transformed variable
    """
    return '{}_{}__'.format(name, transform.name)


@staticmethod
def prepare_dict_for_unparse(url_dict: dict) ->dict:
    """
        remove and add required back slash of 'netloc' and 'path'
        to parse it properly, urllib.parse.unparse() function can't
        create url properly if path doesn't have '/' at the start
        """
    url_dict['netloc'] = url_dict['netloc'].rstrip('/')
    url_dict['path'] = '/' + url_dict['path'].strip('/')
    return url_dict


def __setitem__(name, obj):
    """Add the named subclass to the mapping of subclasses"""


def group_filenames(filelist):
    """ Group entries in the form (id, filename, name) by filename. """
    filename_groups = dict()
    for pub_id, filename, name in filelist:
        if filename not in filename_groups.keys():
            filename_groups[filename] = list()
        filename_groups[filename].append((pub_id, name))
    return filename_groups


def psi_H_trisH_Cl_GT17simopt(T, P):
    """c-c'-a: hydrogen trisH chloride [GT17simopt]."""
    psi = -0.007
    valid = T == 298.15
    return psi, valid


@classmethod
def min_bits(cls) ->int:
    """Minimum amount of bits than can be processed with these primes."""
    return min(cls._PRIMES.keys())


@staticmethod
def center_text(text):
    """Place a text string to center.

        :param text: a text string.
        :type text: str
        :return: a string like this exampple: ``'text'``
        """
    return '' + text + ''


def add_initial_data(couchish_config, store):
    """
    Build a configuration dict for adminish.

    :param: couchish_config the couchish config instance
    :param: store a couchish store
    """
    for type, data in couchish_config.types.items():
        initial_data = data.get('initial_data', [])
        for data in initial_data:
            data['model_type'] = type
            with store.session() as S:
                S.create(data)


def store_val(arg, val, args, acc):
    """
    lambda that store the value of the argument on the parser result

    """
    if val == '':
        val = None
    acc[arg] = val
    return args, acc


def _escape(input_string: str) ->str:
    """
    Adopted from https://github.com/titan550/bcpy/blob/master/bcpy/format_file_builder.py#L25
    """
    return input_string.replace('"', '\\"').replace("'", "\\'").replace('\r',
        '\\r').replace('\n', '\\n')


def _get_tests():
    """Enables ``python setup.py test``."""
    import doctest
    return doctest.DocTestSuite()


def _unpickle_cached_list(cls, *args, **kwargs):
    """
    When unpickling the list, attach an attribute which tells it to unpack
    the values when first accessed. This is done lazily because the cache
    backend breaks if trying to access the cache while in the middle of
    unpickling a cached object.

    """
    new_list = cls(*args, **kwargs)
    new_list._unpack = True
    return new_list


def extract_and_zero_grades(fields, d):
    """Extract an array of grades from a dictionary; convert non-numeric values to 0.0"""
    grades = []
    for f in fields:
        try:
            g = float(d[f])
        except ValueError:
            g = 0.0
        grades.append(g)
    return grades


@classmethod
def supports_metadata(cls):
    """returns True if this audio type supports MetaData"""
    return True


def create_uvsphere(bm: 'bmesh.types.BMesh', u_segments: int, v_segments:
    int, diameter: float, matrix: 'mathutils.Matrix', calc_uvs: bool) ->dict:
    """Creates a grid with a variable number of subdivisions

    :param bm: The bmesh to operate on.
    :type bm: 'bmesh.types.BMesh'
    :param u_segments: number of u segments
    :type u_segments: int
    :param v_segments: number of v segment
    :type v_segments: int
    :param diameter: diameter
    :type diameter: float
    :param matrix: matrix to multiply the new geometry with
    :type matrix: 'mathutils.Matrix'
    :param calc_uvs: calculate default UVs
    :type calc_uvs: bool
    :return:  verts: output vertstype list of (bmesh.types.BMVert)
    """
    pass


def UpSampling(*data, **kwargs):
    """Upsamples the given input data.

    Two algorithms (``sample_type``) are available for upsampling:

    - Nearest Neighbor
    - Bilinear

    **Nearest Neighbor Upsampling**

    Input data is expected to be NCHW.

    Example::

      x = [[[[1. 1. 1.]
             [1. 1. 1.]
             [1. 1. 1.]]]]

      UpSampling(x, scale=2, sample_type='nearest') = [[[[1. 1. 1. 1. 1. 1.]
                                                         [1. 1. 1. 1. 1. 1.]
                                                         [1. 1. 1. 1. 1. 1.]
                                                         [1. 1. 1. 1. 1. 1.]
                                                         [1. 1. 1. 1. 1. 1.]
                                                         [1. 1. 1. 1. 1. 1.]]]]

    **Bilinear Upsampling**

    Uses `deconvolution` algorithm under the hood. You need provide both input data and the kernel.

    Input data is expected to be NCHW.

    `num_filter` is expected to be same as the number of channels.

    Example::

      x = [[[[1. 1. 1.]
             [1. 1. 1.]
             [1. 1. 1.]]]]

      w = [[[[1. 1. 1. 1.]
             [1. 1. 1. 1.]
             [1. 1. 1. 1.]
             [1. 1. 1. 1.]]]]

      UpSampling(x, w, scale=2, sample_type='bilinear', num_filter=1) = [[[[1. 2. 2. 2. 2. 1.]
                                                                           [2. 4. 4. 4. 4. 2.]
                                                                           [2. 4. 4. 4. 4. 2.]
                                                                           [2. 4. 4. 4. 4. 2.]
                                                                           [2. 4. 4. 4. 4. 2.]
                                                                           [1. 2. 2. 2. 2. 1.]]]]

    Defined in src/operator/nn/upsampling.cc:L173
    This function support variable length of positional input.

    Parameters
    ----------
    data : Symbol[]
        Array of tensors to upsample. For bilinear upsampling, there should be 2 inputs - 1 data and 1 weight.
    scale : int, required
        Up sampling scale
    num_filter : int, optional, default='0'
        Input filter. Only used by bilinear sample_type.Since bilinear upsampling uses deconvolution, num_filters is set to the number of channels.
    sample_type : {'bilinear', 'nearest'}, required
        upsampling method
    multi_input_mode : {'concat', 'sum'},optional, default='concat'
        How to handle multiple input. concat means concatenate upsampled images along the channel dimension. sum means add all images together, only available for nearest neighbor upsampling.
    workspace : long (non-negative), optional, default=512
        Tmp workspace for deconvolution (MB)

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

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


def guess_y(ds, default=None):
    """Given a dataset, guess the dependent variable"""
    for y in ('srcm', 'src', 'meg', 'eeg'):
        if y in ds:
            return y
    if default is not None:
        return default
    raise RuntimeError('Could not find data in {ds}')


@classmethod
def _elements_to_dtypes(cls, elements):
    """Converts a list of `Element` instances into a dtype dictionary."""
    dtypes = {}
    for element in elements:
        k, v = element.attrib.get('Name'), element.attrib.get('DataType')
        dtypes[k] = cls._dtypes[v]
    return dtypes


def read_colormap(fh, byteorder, dtype, count, offsetsize):
    """Read ColorMap data from file and return as numpy array."""
    cmap = fh.read_array(byteorder + dtype[-1], count)
    cmap.shape = 3, -1
    return cmap


def make_subparser(parser):
    """ Creates default arguments for all command line subparsers.
    Returns a subparser configuration and base arguments.
    """
    return parser.add_subparsers(title='required commands', description='',
        dest='command', metavar='Commands', help='Description:')


def findCompleteFragments(fragments, max_dist, current_position,
    max_collapse_dist=20):
    """Find complete fragments that are >max_dist bp away from
    the current BAM file position

    Parameters
    ----------
    fragments : dict
        A dictionary containing ATAC fragment information
    max_dist : int
        The maximum allowed distance between fragment start and
        end positions
    current_position : int
        The current position being looked at in the position-sorted
        BAM file
    max_collapse_dist : int
        Maximum allowed distance for fragments from the same cell
        barcode that share one Tn5 integration site (fragment
        start or end coordinate) to be collapsed into a single
        fragment.

    Moves completed fragments to a new dictionary
    Completed fragments will be deleted from the original dictionary
    """
    allkey = list(fragments.keys())
    completed = dict()
    d = max_dist + max_collapse_dist
    for key in allkey:
        if fragments[key][4]:
            if fragments[key][2] + d < current_position:
                completed[key] = fragments[key][:-1]
                del fragments[key]
        elif fragments[key][1] is None:
            if fragments[key][2] + d < current_position:
                del fragments[key]
        elif fragments[key][2] is None:
            if fragments[key][1] + d < current_position:
                del fragments[key]
        else:
            del fragments[key]
    return completed


def classify(text):
    """
        Классифицировать текст согласно модели.

        Результат классификации - текст "хороший" или "плохой" (относительно модели).

        @param text: текст, который классифируем
        @type text: C{unicode}
        @return: результат операции, C{bool}, хороший ли текст?
        @rtype: C{Deferred}
        """


@classmethod
def build(cls, data: dict):
    """
        Build a data concepts object from a dictionary or from a GEMD object.

        This is an internal method, and should not be called directly by users.

        Parameters
        ----------
        data: dict
            A representation of the object. It must be possible to put this dictionary through
            the loads/dumps cycle of the GMED
            :py:mod:`JSON encoder <gemd.jsonr>`. The ensuing dictionary must
            have a `type` field that corresponds to the response key of this class or of
            :py:class:`LinkByUID <gemd.entity.link_by_uid.LinkByUID>`.

        Returns
        -------
        DataConcepts
            An object corresponding to a data concepts resource.

        """
    return cls.get_json_support().copy(data)


def _find_similar(other_cl, population):
    """
    Searches for the first similar classifier `other` and returns it.
    Similarity is distinguished when both C-A-E triple is the same.

    Parameters
    ----------
    other_cl:
        classifier to compare

    Returns
    -------
    Optional[Classifier]
        classifier (with the same condition, action, effect),
        None otherwise
    """
    return next(filter(lambda cl: cl == other_cl, population), None)


def select_more():
    """Select keys linked to boundary selected keys of each particle

    """
    pass


def _get_cluster_name(instance: 'boto3.resources.factory.ec2.Instance') ->str:
    """
    Given an EC2 instance, get the name of the Flintrock cluster it belongs to.
    """
    for group in instance.security_groups:
        if group['GroupName'].startswith('flintrock-'):
            return group['GroupName'].replace('flintrock-', '', 1)
    else:
        raise Exception('Could not extract cluster name from instance: {i}'
            .format(i=instance.id))


def get_instructions(term, is_sysop=None):
    """ Show file browser instructions. """
    return [term.bold_blue_underline(u'Instructions'), u' ',
        u'{0} Un/flag file for download'.format(term.reverse(u'(SPACE)')),
        u'{0}  Back up'.format(term.reverse(u'(LEFT)')), term.reverse(
        u'(RIGHT, ENTER)'), u'        Browse subdirectory',
        u'{0}     Download flagged file(s)'.format(term.reverse(u'(D)')),
        u'{0}     Unflag all files'.format(term.reverse(u'(-)')),
        u'{0}     Upload file(s)'.format(term.reverse(u'(u)')),
        u'{0}     Edit description'.format(term.reverse(u'(e)')) if
        is_sysop else u'', u'{0}     Quit'.format(term.reverse(u'(q)')),
        u' ', u'Files are also available via {0}'.format(term.bold(u'SFTP'))]


@classmethod
def fromkeys(cls, iterable, value=None):
    """OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S
        and values equal to v (which defaults to None).

        """
    d = cls()
    for key in iterable:
        d[key] = value
    return d


def yes_no(prompt):
    """
    Prompt the user with a yes/no question until an answer is received

    :param prompt: the message to display
    :type prompt: str
    :return: whether the user answered yes or no
    :rtype: bool
    """
    while True:
        resp = input('{0} (Y/N) '.format(prompt.strip())).lower().strip()
        if resp == 'y' or resp == 'yes':
            return True
        elif resp == 'n' or resp == 'no':
            return False


def keyof(map, obj):
    """find key that obj is stored at in map by exhaustive search"""
    for k in map:
        if map[k] is obj:
            return k
    return None


def mag(initial, current):
    """
    Calculates the magnification of a specified value

    **Parameters**

    intial: *float*
        initial value (magnificiation of 1)

    current: *float*
        current value

    **Returns**

    magnification: *float*
        the magnification of the current value
    """
    return float(initial) / float(current)


def configure_logging(app):
    """Send ERROR log to ADMINS emails."""
    ADMINS = ['bbzbryce@gmail.com']
    if not app.debug:
        import logging
        from logging.handlers import SMTPHandler
        mail_handler = SMTPHandler('127.0.0.1',
            'server-error@updatechecker.bryceboe.com', ADMINS,
            'UpdateChecker Failed')
        mail_handler.setLevel(logging.ERROR)
        app.logger.addHandler(mail_handler)


def max_chunk_size(mem_bytes):
    """Determine maximum chunk size for use with given ammount of memory.

    :param mem_bytes: size of available memory in bytes. This might mean different things
     depending on for what computation method the chunk_size is being computed but the
     bottom line is: this is the ammount of memory that we are able to use
    :type mem_bytes: int
    :returns: maximum chunk size as a exponent determining part of search spaced sweep
     during a single iteration. More precisely, if the returned value is `m` then
     2 ** `m` states can be searched during a single pass of the algorithm (and this is
     a maximal such exponent `m` that can be used).
    :rtype: int
    """
    elements_max = mem_bytes // 16 // 2
    chunk_size = 0
    while elements_max > 1:
        elements_max >>= 1
        chunk_size += 1
    if 2 * 16 * 2 ** chunk_size + 1024 * 1024 * 1024 > mem_bytes:
        chunk_size -= 1
    return chunk_size


@staticmethod
def white_vertical_length_carryover_start(sub_matrix):
    """
        Start index of the sub matrix specific segment of the global white vertical length carryover array.

        :param sub_matrix: Sub matrix.
        :return: White vertical length carryover start.
        """
    return sub_matrix.start_x


def formatUnits(units):
    """
    Format a unit specification ([numerators,...], [denominators,...])
    into a string (this is the inverse of evalUnits)
    """
    pass


def process_transform_funcs(trans_funcs, func_args=None, func_kwargs=None):
    """Process input of the apply_transform_funcs function.

    :param iterable trans_funcs: functions to apply, specified the function or a (function, args, kwargs) tuple
    :param dict func_args: function positional arguments, specified as (function, arguments tuple) pairs
    :param dict func_kwargs: function keyword arguments, specified as (function, kwargs dict) pairs
    :returns: transformation functions for apply_transform_funcs function
    :rtype: list
    """
    func_args = dict(func_args) if func_args else {}
    func_kwargs = dict(func_kwargs) if func_kwargs else {}
    proc_funcs = []
    for func_spec in trans_funcs:
        try:
            func, args, kwargs = (func_spec, None, None) if isinstance(
                func_spec, str) else func_spec
        except TypeError:
            func, args, kwargs = func_spec, None, None
        except ValueError:
            raise ValueError(
                'expected (func, args, kwargs) combination (got {!s})'.
                format(func_spec))
        args_ = func_args.pop(func, None)
        if args is not None and args_ is not None:
            raise RuntimeError(
                'arguments for "{!s}" in both "trans_funcs" and "func_args"'
                .format(func))
        args = tuple(args) if args is not None else tuple(args_
            ) if args_ is not None else ()
        kwargs_ = func_kwargs.pop(func, None)
        if kwargs is not None and kwargs_ is not None:
            raise RuntimeError(
                'keyword arguments for "{!s}" in both "trans_funcs" and "func_kwargs"'
                .format(func))
        kwargs = dict(kwargs) if kwargs is not None else dict(kwargs_
            ) if kwargs_ is not None else {}
        if not (isinstance(func, str) or callable(func)):
            raise TypeError('function "{!s}" is not callable'.format(func))
        proc_funcs.append((func, args, kwargs))
    if func_args:
        raise ValueError('unused function arguments specified: {!s}'.format
            (func_args))
    if func_kwargs:
        raise ValueError('unused function keyword arguments specified: {!s}'
            .format(func_kwargs))
    return proc_funcs


def collection_show_inside():
    """Show all the objects and collections inside the collection

    """
    pass


def printProgressBar(iteration, total, prefix='', suffix='', decimals=1,
    length=100, fill='█', printEnd='\r'):
    '\n    Call in a loop to create terminal progress bar\n    @params:\n        iteration   - Required  : current iteration (Int)\n        total       - Required  : total iterations (Int)\n        prefix      - Optional  : prefix string (Str)\n        suffix      - Optional  : suffix string (Str)\n        decimals    - Optional  : positive number of decimals in percent complete (Int)\n        length      - Optional  : character length of bar (Int)\n        fill        - Optional  : bar fill character (Str)\n        printEnd    - Optional  : end character (e.g. "\r", "\r\n") (Str)\n    '
    percent = ('{0:.' + str(decimals) + 'f}').format(100 * (iteration /
        float(total)))
    filledLength = int(length * iteration // total)
    bar = fill * filledLength + '-' * (length - filledLength)
    print('\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix), end=printEnd)
    if iteration == total:
        print()


def get_sort_order(qdict, default, allowed_values=None):
    """Return a sort order from a querydict object

    :param QueryDict qdict: the object to analyse
    :param string default: the default sort order if no one is found
    :param list allowed_values: an optional list of allowed values
    :return: a 2uple of strings
    """
    sort_order = qdict.get('sort_order', default)
    if sort_order.startswith('-'):
        sort_dir = '-'
        sort_order = sort_order[1:]
    else:
        sort_dir = ''
    if allowed_values is not None and sort_order not in allowed_values:
        return default, ''
    return sort_order, sort_dir


def _generate_facet_normal_custom(gdim):
    """Generate code for setting facet normal in custom integrals"""
    code = format['comment'](
        'Set facet normal components for current quadrature point\n')
    for i in range(gdim):
        code += 'const double n_0%d =   facet_normals[%d*ip + %d];\n' % (i,
            gdim, i)
        code += 'const double n_1%d = - facet_normals[%d*ip + %d];\n' % (i,
            gdim, i)
    return code


def ESAcloudMask(img):
    """
    European Space Agency (ESA) clouds from 'QA60', i.e. Quality Assessment band at 60m

    parsed by Nick Clinton

    Parameters
    ----------
    img : gee.image.Image
        Sentinel-2 Image for which the cloud mask should be calculated

    Returns
    -------
    img : gee.image.Image
        Sentinel-2 image with cloud score as extra band
    """
    qa = img.select('QA60')
    cloudBitMask = int(2 ** 10)
    cirrusBitMask = int(2 ** 11)
    clear = qa.bitwiseAnd(cloudBitMask).eq(0).And(qa.bitwiseAnd(
        cirrusBitMask).eq(0))
    cloud = clear.Not().rename(['ESA_clouds'])
    return img.addBands(cloud)


@classmethod
def get_name(cls):
    """ Returns the name of the logger.

			# Return value

			A lower-case string unique to this logger.
		"""
    return cls.__name__.lower()


def bearing_damage(angle_moment_lst, m=3, thresshold=0.1):
    """Function ported from Matlab.

    Parameters
    ----------
    angle_moment_lst : ((angle_A_vector, moment_A_vector),(angle_B_vector, moment_B_vector),...)
        Angles[deg] and momements (e.g. pitch angle and blade root moment for the blades of a wind turbine)
    m : int, optional
        analogue to Wohler exponent, should be 3
    threeshold : float, optional
        Pitch noise. Pitch movement below this thresshold is ignored

    Returns
    -------
    max_damage : float
        A damage value of the most damaged pitch bearing. Only suitable for comparison
    """
    damages = []
    for angle, moment in angle_moment_lst:
        angle, moment = angle.tolist(), moment.tolist()
        k1 = 0
        p1, mflap = angle[0], moment[0]
        damage = 0
        for k, (pi, mo) in enumerate(zip(angle[1:], moment[1:]), 1):
            dangle = abs(pi - p1)
            if dangle > thresshold:
                damage += dangle * abs(mflap / (k - k1 + 1)) ** m
                k1 = k
                mflap = mo
                p1 = pi
            else:
                mflap += mo
        damages.append(damage)
    return max(damages)


@staticmethod
def _encode_to_bytes(string):
    """
        Tries to encode any string from bytes. Does not fail if gets already encoded string.
        :param string: string to encode
        :type string: basestring
        :return: encoded string
        :rtype: bytes
        """
    return string if isinstance(string, bytes) else string.encode('ascii',
        'ignore')


def get_device_type(device_type=0):
    """Return the device type from a device_type list."""
    device_types = {(0): 'Unknown', (1): 'Classic - BR/EDR devices', (2):
        'Low Energy - LE-only', (3): 'Dual Mode - BR/EDR/LE'}
    if device_type in [0, 1, 2, 3]:
        return_value = device_types[device_type]
    else:
        return_value = device_types[0]
    return return_value


def infer_precision(number):
    """
    Infer precision base on number size.

    >>> infer_precision(0.343)
    3
    >>> infer_precision(0.0001343)
    5
    >>> infer_precision(12300)
    0

    :param float number: number used to infer precision.
    :return int: precision as int (number of decimals recommended)
    """
    number = number or 0.0
    try:
        number = float(number)
    except ValueError:
        return number
    if number is not None and isinstance(number, float):
        if number < 1e-06:
            return 10
        elif number < 0.0001:
            return 8
        elif number < 0.01:
            return 5
        elif number < 1.0:
            return 3
        elif number < 100.0:
            return 2
        elif number < 1000.0:
            return 1
        else:
            return 0


@classmethod
def getch(cls):
    """
        Get the integer value for the keypress, such as 27 for escape.

        :return: integer keycode of keypress
        """
    if cls.KEY_EVENTS.empty():
        return None
    return cls.KEY_EVENTS.get()


def taxlist(include_strain=True):
    """
    Provide an ordered list of taxonomic ranks.
    """
    for k in ['superkingdom', 'phylum', 'class', 'order', 'family', 'genus',
        'species']:
        yield k
    if include_strain:
        yield 'strain'


@classmethod
def _broadcast_numpy_array(cls, array, broadcast_dict, leading_shape=()):
    """Broadcast a numpy array according to the broadcast_dict."""
    from numpy.lib.stride_tricks import as_strided
    shape = cls._shape_from_broadcast_dict(array.shape, broadcast_dict)
    shape = tuple(leading_shape) + shape
    strides = [0] * len(leading_shape) + list(array.strides)
    for broadcast_axis in broadcast_dict:
        strides[broadcast_axis + len(leading_shape)] = 0
    strided = as_strided(array, shape=tuple(shape), strides=tuple(strides))
    strided.flags.writeable = False
    return strided


def defval(val, default=None):
    """
    Returns val if is not None, default instead
    :param val:
    :param default:
    :return:
    """
    return val if val is not None else default


def translate_attach_remove_on_cancel(TRANSFORM_OT_translate=None,
    NODE_OT_attach=None, NODE_OT_insert_offset=None):
    """Move nodes and attach to frame

    :param TRANSFORM_OT_translate: Translate, Translate (move) selected items
    :param NODE_OT_attach: Attach Nodes, Attach active node to a frame
    :param NODE_OT_insert_offset: Insert Offset, Automatically offset nodes on insertion
    """
    pass


def penalize(x, n):
    """
    Thumb-rule for the aggregation of cross-border power lines.

    Parameters
    ---------
    x : float
        total line capacity
    n : int
        number of power lines

    Returns
    -------
    c : float
        resulting capacity
    """
    if n == 1:
        return x
    elif n == 2:
        return 5.0 / 6.0 * x
    elif n == 3:
        return 4.0 / 6.0 * x
    else:
        return 0.5 * x


def dist(c1, c2):
    """
	Return the distance between two colors.
	"""
    d0 = c1[0] - c2[0]
    d1 = c1[1] - c2[1]
    d2 = c1[2] - c2[2]
    return d0 * d0 + d1 * d1 + d2 * d2


def upload_receive(request):
    """
    Returns the file(s) uploaded by the user.
    """
    return request.FILES['files[]'] if request.FILES else None


def render_pep440_pre(pieces):
    """TAG[.post.devDISTANCE] -- No -dirty.

    Exceptions:
    1: no tags. 0.post.devDISTANCE
    """
    if pieces['closest-tag']:
        rendered = pieces['closest-tag']
        if pieces['distance']:
            rendered += '.post.dev%d' % pieces['distance']
    else:
        rendered = '0.post.dev%d' % pieces['distance']
    return rendered


def convert_to_date(col):
    """Convert datetime to date."""
    return col.date()


def sphere_bulk_velocity(halo):
    """
    Set the bulk velocity for the sphere.

    Parameters
    ----------
    halo : Halo object
        The Halo object to be provided by the HaloCatalog.

    """
    halo.data_object.set_field_parameter('bulk_velocity', halo.data_object.
        quantities.bulk_velocity(use_particles=True))


def __repr__(A):
    """For `print` and `pprint`"""
    return A.to_str()


def _applytfms(args):
    """
    Applies ANTs' antsApplyTransforms to the input image.
    All inputs are zipped in one tuple to make it digestible by
    multiprocessing's map
    """
    import nibabel as nb
    from nipype.utils.filemanip import fname_presuffix
    from ..niworkflows.interfaces.fixes import FixHeaderApplyTransforms as ApplyTransforms
    in_file, in_xform, ifargs, index, newpath = args
    out_file = fname_presuffix(in_file, suffix='_xform-%05d' % index,
        newpath=newpath, use_ext=True)
    copy_dtype = ifargs.pop('copy_dtype', False)
    xfm = ApplyTransforms(input_image=in_file, transforms=in_xform,
        output_image=out_file, **ifargs)
    xfm.terminal_output = 'allatonce'
    xfm.resource_monitor = False
    runtime = xfm.run().runtime
    if copy_dtype:
        nii = nb.load(out_file)
        in_dtype = nb.load(in_file).get_data_dtype()
        if in_dtype != nii.get_data_dtype():
            nii.set_data_dtype(in_dtype)
            nii.to_filename(out_file)
    return out_file, runtime.cmdline


@staticmethod
def prepare_group_by_item(item):
    """Prepare group by list item.

        Convert replaces any special "dimensions#", "meta#" or "value_meta#" occurrences into
        spark sql syntax to retrieve data from extra_data_map column.
        """
    if item.startswith('dimensions#') or item.startswith('meta#'
        ) or item.startswith('value_meta#'):
        return '.'.join(('extra_data_map', item))
    else:
        return item


def add_projection_defaults(apps, schema_editor):
    """
    Adds projectiondefaults for messages and countdowns.
    """
    Projector = apps.get_model('core', 'Projector')
    ProjectionDefault = apps.get_model('core', 'ProjectionDefault')
    default_projector = Projector.objects.get(pk=1)
    projectiondefaults = []
    projectiondefaults.append(ProjectionDefault(name='agenda_all_items',
        display_name='Agenda', projector=default_projector))
    projectiondefaults.append(ProjectionDefault(name='topics', display_name
        ='Topics', projector=default_projector))
    projectiondefaults.append(ProjectionDefault(name=
        'agenda_list_of_speakers', display_name='List of speakers',
        projector=default_projector))
    projectiondefaults.append(ProjectionDefault(name=
        'agenda_current_list_of_speakers', display_name=
        'Current list of speakers', projector=default_projector))
    projectiondefaults.append(ProjectionDefault(name='motions',
        display_name='Motions', projector=default_projector))
    projectiondefaults.append(ProjectionDefault(name='motionBlocks',
        display_name='Motion blocks', projector=default_projector))
    projectiondefaults.append(ProjectionDefault(name='assignments',
        display_name='Elections', projector=default_projector))
    projectiondefaults.append(ProjectionDefault(name='users', display_name=
        'Participants', projector=default_projector))
    projectiondefaults.append(ProjectionDefault(name='mediafiles',
        display_name='Files', projector=default_projector))
    projectiondefaults.append(ProjectionDefault(name='messages',
        display_name='Messages', projector=default_projector))
    projectiondefaults.append(ProjectionDefault(name='countdowns',
        display_name='Countdowns', projector=default_projector))
    ProjectionDefault.objects.bulk_create(projectiondefaults)


@staticmethod
def write(writer, value):
    """
        Writes Zserio varuint16 type to the bit stream.

        :param writer: Bit stream where to write.
        :param value: Zserio varuint16 type to write.
        """
    writer.writeVarUInt16(value)


@staticmethod
def _transcode(codecfunc, input_, errors):
    """Use `codecfunc` to encode or decode the given `input`."""
    if errors != 'strict':
        raise UnicodeError('Only strict error handling is supported.')
    return codecfunc(input_), len(input_)


def query(connection, statement):
    """
    query sql command

    @Args:
    * [connection] connector
    * [statement] str

    @Returns:
    * [any] could be None, dict, list, depending on how many rows returned
    """
    with connection.cursor() as cursor:
        rows = cursor.execute(statement)
        res = None
        if rows > 1:
            res = cursor.fetchall()
        if rows == 1:
            res = cursor.fetchone()
        connection.commit()
        return res


def _c_func(func, restype, argtypes, errcheck=None):
    """Wrap c function setting prototype."""
    func.restype = restype
    func.argtypes = argtypes
    if errcheck is not None:
        func.errcheck = errcheck
    return func


def render_pep440_old(pieces):
    """TAG[.postDISTANCE[.dev0]] .

    The ".dev0" means dirty.

    Eexceptions:
    1: no tags. 0.postDISTANCE[.dev0]
    """
    if pieces['closest-tag']:
        rendered = pieces['closest-tag']
        if pieces['distance'] or pieces['dirty']:
            rendered += '.post%d' % pieces['distance']
            if pieces['dirty']:
                rendered += '.dev0'
    else:
        rendered = '0.post%d' % pieces['distance']
        if pieces['dirty']:
            rendered += '.dev0'
    return rendered


@staticmethod
def get_assignment(course, activity):
    """If doesn't use quiz report, we need the activity_inviting_to_complete"""
    return course.get_assignment(activity.id)


def get_has_next_record(rawdata=None, **kwargs):
    """Returns whether or not more wmf records exist in the rawdata."""
    try:
        return len(rawdata.peek(6)) >= 6
    except Exception:
        return False


@staticmethod
def getSiteDomain():
    """ The site domain.  Does have www here, if it uses it. """
    return 'www.lushstories.com'


@classmethod
def union(cls, interval1, interval2):
    """Smallest interval comprising self and interval2"""
    return cls(min(interval1.first, interval2.first), max(interval1.last,
        interval2.last))


def _ip(ip, ip_type, cidr):
    """
    Helper for ipv4 and ipv6

    """
    if ip is False:
        return True
    if not isinstance(ip, str):
        raise TypeError('ipv4 must be false or string.')
    elif ip == cidr:
        return True
    elif ip == 'nat':
        return True
    elif ip == 'tor':
        return True
    else:
        raise ValueError('{} must be one of: False|{}'.format(ip_type, cidr))


def bech32_polymod(values):
    """Internal function that computes the Bech32 checksum."""
    generator = [996825010, 642813549, 513874426, 1027748829, 705979059]
    chk = 1
    for value in values:
        top = chk >> 25
        chk = (chk & 33554431) << 5 ^ value
        for i in range(5):
            chk ^= generator[i] if top >> i & 1 else 0
    return chk


def _join_translated(translated_parts, os_sep_class):
    """Join translated glob pattern parts.

    This is different from a simple join, as care need to be taken
    to allow ** to match ZERO or more directories.
    """
    res = ''
    for part in translated_parts[:-1]:
        if part == '.*':
            res += part
        else:
            res += part + os_sep_class
    if translated_parts[-1] == '.*':
        res += '.+'
        res += '({os_sep_class}?.*)?'.format(os_sep_class=os_sep_class)
    else:
        res += translated_parts[-1]
    return res


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 render_git_describe_long(pieces):
    """TAG-DISTANCE-gHEX[-dirty].

    Like 'git describe --tags --dirty --always -long'.
    The distance/hash is unconditional.

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


def _h(text: str) ->str:
    """
    For some reason, :mod:`click` does not strip new line characters
    from helps in :func:`click.option` (although it does strip them
    from helps for :func:`click.command`). So, we have to do it
    ourselves.
    """
    return text.replace('\n', ' ')


def _mako_template_names(template):
    """
    Return all the used identifiers in the Mako template.

    From Igonato's code at https://stackoverflow.com/a/23577289/622408.
    """
    from mako import lexer, codegen
    lexer = lexer.Lexer(template)
    node = lexer.parse()
    compiler = lambda : None
    compiler.reserved_names = set()
    identifiers = codegen._Identifiers(compiler, node)
    return identifiers.undeclared


def get_popcorn_name(model):
    """Get reverse friendly name for this view"""
    app = model._meta.app_label.lower()
    model = model._meta.object_name.lower()
    return '%s_%s_popcorn' % (app, model)


def is_video(mime):
    """ Returns `True` if the specified file pointer represents a video.
        `False` otherwise. """
    return mime.startswith('video/')


def remove_www(hostname):
    """
    Removes www. from the beginning of the address. Only for
    routing purposes. www.test.com/login/ and test.com/login/ should
    find the same tenant.
    """
    if hostname.startswith('www.'):
        return hostname[4:]
    return hostname


def build_markdown_header(title, date, author, categories, tags, slug,
    status=None, attachments=None):
    """Build a header from a list of fields"""
    header = 'Title: %s\n' % title
    if date:
        header += 'Date: %s\n' % date
    if author:
        header += 'Author: %s\n' % author
    if categories:
        header += 'Category: %s\n' % ', '.join(categories)
    if tags:
        header += 'Tags: %s\n' % ', '.join(tags)
    if slug:
        header += 'Slug: %s\n' % slug
    if status:
        header += 'Status: %s\n' % status
    if attachments:
        header += 'Attachments: %s\n' % ', '.join(attachments)
    header += '\n'
    return header


@classmethod
def config(cls):
    """
        Returns the dict with api configurations
        :return:
        """
    if cls._api_info is None:
        cls.load_config_file()
    return cls._api_info


@classmethod
def encode_source(cls, source):
    """Encode source from unicode.

        :param source: source string (may already be encoded).

        If the ``source`` string contains a coding specification
        within the first two lines, the specified coding is used,
        otherwise, ``UTF-8`` is applied.
        """
    if not source:
        return ''.encode('utf-8')
    if isinstance(source, cls.uc_type) and hasattr(source, 'encode'):
        source = source.encode(cls.check_coding(source))
    return source


def raisef(exctype, *args, **kwargs):
    """``raise`` as a function, to make it possible for lambdas to raise exceptions.

    Example::

        raisef(ValueError, "message")

    is (almost) equivalent to::

        raise ValueError("message")

    Parameters:
        exctype: type
            The object type to raise as an exception.

        *args: anything
            Passed on to the constructor of exctype.

        **kwargs: anything
            Passed on to the constructor of exctype.
    """
    raise exctype(*args, **kwargs)


def lon2phi(lon, unit='deg'):
    """spherical longitude -> phi transform; currently a no-op"""
    return lon


def select_linked():
    """Select all curve points linked to already selected ones

    """
    pass


def mos_repr_bool(b: bool) ->str:
    """ Get the Mosel source code representation of an bool, without type or bound checking. """
    return 'true' if b else 'false'


def theta_Cl_SO4_MNTR08(T):
    """a-a': chloride sulfate [MNTR08]."""
    theta = -0.07122
    valid = T == 298.15
    return theta, valid


def is_tool(name):
    """Check whether `name` is on PATH and marked as executable."""
    from shutil import which
    return which(name) is not None


def is_legacy_bundle(bundle):
    """Report whether the bundle uses the legacy (version 3) syntax."""
    return 'machines' not in bundle


def MACDEXT(df, price='Close'):
    """
    MACD with controllable MA type
    """


def getGeometry(win):
    """ Return the geometry information of the windows
    It will be a tuple (width, height, x, y)
    """
    return win.winfo_reqwidth(), win.winfo_reqheight(), win.winfo_x(
        ), win.winfo_y()


def scopes_converter(value):
    """Ensure that scopes are always sorted and immutable (a tuple)"""
    return tuple(sorted(value))


@staticmethod
def p_a2ml_identifier_optional(p):
    """a2ml_identifier_optional : empty
                                    | a2ml_identifier"""


def within_surrogate(text, index, *, length=None):
    """
    `True` if ``index`` is within a surrogate (before and after it, not at!).
    """
    if length is None:
        length = len(text)
    return 1 < index < len(text) and '\ud800' <= text[index - 1
        ] <= '\udfff' and '\ud800' <= text[index] <= '\udfff'


def Almedeij(Re):
    """Calculates drag coefficient of a smooth sphere using the method in
    [1]_ as described in [2]_.

    .. math::
        C_D = \\left[\\frac{1}{(\\phi_1 + \\phi_2)^{-1} + (\\phi_3)^{-1}} + \\phi_4\\right]^{0.1}

        \\phi_1 = (24Re^{-1})^{10} + (21Re^{-0.67})^{10} + (4Re^{-0.33})^{10} + 0.4^{10}

        \\phi_2 = \\left[(0.148Re^{0.11})^{-10} + (0.5)^{-10}\\right]^{-1}

        \\phi_3 = (1.57\\times10^8Re^{-1.625})^{10}

        \\phi_4 = \\left[(6\\times10^{-17}Re^{2.63})^{-10} + (0.2)^{-10}\\right]^{-1}

    Parameters
    ----------
    Re : float
        Reynolds number of the sphere, [-]

    Returns
    -------
    Cd : float
        Drag coefficient [-]

    Notes
    -----
    Range is Re <= 1E6.
    Original work has been reviewed.

    Examples
    --------
    >>> Almedeij(200.)
    0.7114768646813396

    References
    ----------
    .. [1] Almedeij, Jaber. "Drag Coefficient of Flow around a Sphere: Matching
       Asymptotically the Wide Trend." Powder Technology 186, no. 3
       (September 10, 2008): 218-23. doi:10.1016/j.powtec.2007.12.006.
    .. [2] Barati, Reza, Seyed Ali Akbar Salehi Neyshabouri, and Goodarz
       Ahmadi. "Development of Empirical Models with High Accuracy for
       Estimation of Drag Coefficient of Flow around a Smooth Sphere: An
       Evolutionary Approach." Powder Technology 257 (May 2014): 11-19.
       doi:10.1016/j.powtec.2014.02.045.
    """
    phi4 = ((6e-17 * Re ** 2.63) ** -10 + 0.2 ** -10) ** -1
    phi3 = (157000000.0 * Re ** -1.625) ** 10
    phi2 = ((0.148 * Re ** 0.11) ** -10 + 0.5 ** -10) ** -1
    phi1 = (24 * Re ** -1) ** 10 + (21 * Re ** -0.67) ** 10 + (4 * Re ** -0.33
        ) ** 10 + 0.4 ** 10
    Cd = (1 / ((phi1 + phi2) ** -1 + phi3 ** -1) + phi4) ** 0.1
    return Cd


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 loadfile(filename, encoding='windows-1251'):
    """
    Загрузка содержимого файла в строку
    """
    with open(filename, encoding=encoding) as file:
        return file.read()


def writeInputToTxt(s):
    """ Prepares prun option --writeInputToTxt
        comma-separated list of STREAM:STREAM.files.dat
        """
    out = []
    DSs = s.secondaryDSs()
    for i, DS in enumerate(DSs):
        if DS in s.inds:
            stream = s.inds[DS]
        else:
            stream = 'IN%d' % (i + 1,)
        out.append('%s:%s.files.dat' % (stream, stream))
    out.append('IN:IN.files.dat')
    return ','.join(out)


@classmethod
def from_list(cls, values):
    """Construct a tree from a list with paths."""
    self = cls()
    for value in values:
        self.add(value)
    return self


def get_remote_boot_volume(task):
    """Identify a boot volume from any configured volumes.

    :returns: None or the volume target representing the volume.
    """
    targets = task.volume_targets
    for volume in targets:
        if volume['boot_index'] == 0:
            return volume


def render_pep440_pre(pieces):
    """TAG[.post.devDISTANCE] -- No -dirty.

    Exceptions:
    1: no tags. 0.post.devDISTANCE
    """
    if pieces['closest-tag']:
        rendered = pieces['closest-tag']
        if pieces['distance']:
            rendered += '.post.dev%d' % pieces['distance']
    else:
        rendered = '0.post.dev%d' % pieces['distance']
    return rendered


def _str2bool(s):
    """ convert a string to a boolean value """
    return s in {'True', 'T', 'true', 't', 'yes', 'y', '1'}


def health_check(jaide):
    """ Retrieve alarm, CPU, RAM, and temperature status.

    @param jaide: The jaide connection to the device.
    @type jaide: jaide.Jaide object

    @returns: The output from the device.
    @rtype str
    """
    return jaide.health_check()


def unquote(s):
    """Undo the effects of quote(). Based heavily on urllib.parse.unquote()."""
    mychr = chr
    myatoi = int
    list = s.split('_')
    res = [list[0]]
    myappend = res.append
    del list[0]
    for item in list:
        if item[1:2]:
            try:
                myappend(mychr(myatoi(item[:2], 16)) + item[2:])
            except ValueError:
                myappend('_' + item)
        else:
            myappend('_' + item)
    return ''.join(res)


def dict_to_model(instance, data, mapping=None):
    """Assign the values in the data dictonary to an instance.

    ``data`` is the cleaned data of the form.

    ``mapping`` is an optional dictionary that maps field names to attribute names,
    for example {'field': 'instance.child.field'}.

    """
    mapping = mapping or {}
    for key, value in data.items():
        key = mapping.get(key, key)
        bits = key.split('.')
        obj = instance
        for bit in bits[:-1]:
            obj = getattr(obj, bit)
        setattr(obj, bits[-1], value)


def ga(n):
    """generates square of even nonnegative integers less than n"""
    for e in range(n):
        if e % 2 == 0:
            yield e * e


def _add_doc(func, doc):
    """Add documentation to a function."""
    func.__doc__ = doc


def get_list_id(mastodon, rest):
    """Get the ID for a list"""
    if not rest:
        return -1
    try:
        return int(rest)
    except ValueError:
        pass
    rest = rest.strip()
    lists = mastodon.lists()
    for item in lists:
        if item['title'].lower() == rest.lower():
            return item['id']


def chunked_read(timeout):
    """Reads chunked input.

    .. warning:: Bytes are returned for Python 3.

    * http://uwsgi.readthedocs.io/en/latest/Chunked.html
    * http://uwsgi.readthedocs.io/en/latest/Changelog-1.9.13.html#chunked-input-api

    :param int timeout: Wait timeout (seconds).

    :rtype: bytes|str

    :raises IOError: If unable to receive chunked part.
    """


def get_quality_by_depth(var):
    """
    Returns the quality by depth or the variant confidence,
    or None if it isn't present in the VCF.
    """
    return var.INFO.get('QD')


def linenumber_creator(txt):
    """
    >>> txt = '''This
    ... is
    ... a
    ... file'''
    >>> linenumber_creator(txt)
    [0, 4, 7, 9]

    >>> linenumber_creator('')
    []

    """
    linenumbers = []
    for idx, val in enumerate(txt):
        if val == '\n':
            linenumbers.append(idx)
    if linenumbers and linenumbers[0] != 0:
        linenumbers.insert(0, 0)
    return linenumbers


@classmethod
def read(cls):
    """
        Create a readonly and non-rebindable storage class.
        """
    return cls(write=False, rebindable=False)


def print_id(num_len, task_id):
    """
    Calculates how much spaces need to be added for formatting purposes.
    Takes:
        - the length of the longest Todo-ID (for formatting)
        - the specific task id (as String!)
    Returns:
        a formatted String like "   2".
    """
    return ' ' * (num_len - len(task_id)) + task_id


def set_ax_xylabels(ax, xlabel, ylabel, exchange_xy):
    """
    Set the x- and the y-label of axis ax, exchanging x and y if exchange_xy
    """
    if exchange_xy:
        xlabel, ylabel = ylabel, xlabel
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)


def select_border(gesture_mode: int=0, xmin: int=0, xmax: int=0, ymin: int=
    0, ymax: int=0):
    """Use box selection to select tree elements

    :param gesture_mode: Gesture Mode
    :type gesture_mode: int
    :param xmin: X Min
    :type xmin: int
    :param xmax: X Max
    :type xmax: int
    :param ymin: Y Min
    :type ymin: int
    :param ymax: Y Max
    :type ymax: int
    """
    pass


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

        :param UploadSessionFinishBatchResult val:
        :rtype: UploadSessionFinishBatchLaunch
        """
    return cls('complete', val)


def branches(config, args):
    """
  List all branches.
  """
    return config.repo.branches()


def getApplicationURL(depth=0, path_only=False):
    """Return the application URL plus depth steps

        If path_only is true, then only a path will be returned.
        """


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 post_document(gismo, i):
    """
    Document indice to document entry

    Parameters
    ----------
    gismo: Gismo
        Gismo instance
    i : int
        document indice

    Returns
    -------
    Object
        Document i from corpus
    """
    return gismo.corpus[i]


def replace_breaks(html):
    """Replace all the <br> tags in the html with newlines."""
    breakline = html.br
    while html.br is not None:
        breakline.insert_before('\n')
        html.br.decompose()
        breakline = html.br
    return html


def _codon_slicing(nt_pos):
    """Return (AA_position, codon_index_start, codon_index_stop)"""
    aa_pos, reminder = divmod(nt_pos, 3)
    if reminder == 0:
        start = nt_pos - 3
    else:
        start = nt_pos - reminder
        aa_pos += 1
    return aa_pos, start, start + 3


def print_header(*args):
    """
    Print a header containing the given elements.

    This is just a specific format for printing.
    """
    for arg in args:
        if not arg or arg == '':
            buffer_ = ''
        else:
            buffer_ = ' '
        print('{:#^80}'.format(arg.join([buffer_] * 2)))


def _describe_frame(frame):
    """Print filename, line number and function name of a stack frame."""
    filename, name = frame.f_code.co_filename, frame.f_code.co_name
    lineno = frame.f_lineno
    with open(filename) as f:
        for no, line in enumerate(f):
            if no + 1 == lineno:
                break
    return """  File "%s", line %d, in %s
    %s
""" % (filename, lineno,
        name, line.strip())


def trim(text):
    """Remove whitespace from both sides of a string."""
    return text.lstrip().rstrip()


def b2mb(num):
    """ convert Bs to MBs and round down """
    return int(num / 2 ** 20)


def splitLeafletCustomIconType(iconType):
    """
	If iconPrefix is 'custom', iconType is expected to be a string of the form '[marker size]-[font color]-[font size]' or '[marker size]-none'.  This function returns a list of size 3, containing the 3 elements separated by '-'.  Missing elements default to be None.
	"""
    if iconType is None:
        return [None, None, None]
    iconType = str(iconType)
    try:
        iconType = iconType.lower()
    except:
        pass
    iconType.replace(' ', '')
    if '-' in iconType:
        parts = iconType.split('-')
        try:
            parts[0] = float(parts[0])
        except:
            pass
        if len(parts) >= 2:
            if parts[1] == 'none':
                parts[1] = None
        if len(parts) >= 3:
            if parts[2] == 'none':
                parts[2] = None
            else:
                try:
                    parts[2] = float(parts[2])
                except:
                    pass
        else:
            parts.append(None)
        return parts[0:3]
    else:
        try:
            iconType = float(iconType)
        except:
            pass
        return [iconType, None, None]


def check_detector(detector):
    """Checks if fit and decision_function methods exist for given detector

    Parameters
    ----------
    detector : combo.models
        Detector instance for which the check is performed.

    """
    if not hasattr(detector, 'fit') or not hasattr(detector,
        'decision_function'):
        raise AttributeError('%s is not a detector instance.' % detector)


@staticmethod
def _map_preds(pred):
    """Map the predicted label to another integer or char to be written
        to .csv file

        This is called just before writing the prediction's list to .csv
        file. If labels different from 0, 1, 2, ... are desired, this must
        be overridden to change the prediction's list to anything desired.

        :param pred: integer prediction predicted by the nn.torch model
        :type pred: int
        :return: an integer or character representing the prediction
        :rtype: int or str
        """
    return str(pred.item())


def printSuccess(msg: str):
    """ 	printSuccess(str)

		Prints the message in a success green on unicode supported
		consoles.

		Args:
			msg(str): The string to print
	"""
    print('\x1b[92m' + msg + '\x1b[0m')


def _show_slicing(name, query, _print):
    """Show slicing objects"""
    objects = list(query)
    if objects:
        _print(name)
        for obj in objects:
            _print(str(obj), 1)


def calc_crc(data):
    """Calculate frame CRC."""
    crc = 45
    for b in data:
        crc += b
    return crc & 255


def get_attributes_config(obj, refresh=False):
    """Experimental function. Not part of the official API"""
    return obj._helper.get_attr_cache(refresh=refresh)


def convert_to_list(data):
    """Convert input into a list for further processing."""
    if data is not None:
        if isinstance(data, list):
            return data
        else:
            return [data]


def reverse(array):
    """Return `array` in reverse order.

    Args:
        array (list|string): Object to process.

    Returns:
        list|string: Reverse of object.

    Example:

        >>> reverse([1, 2, 3, 4])
        [4, 3, 2, 1]

    .. versionadded:: 2.2.0
    """
    return array[::-1]


def write(bytes):
    """Write some bytes to this file.
        """


@classmethod
def sum(cls, item='uid', like={}, isin={}, orderby='', where='', limit='',
    **criteria):
    """return min of item (column) filtered by these criteria
    """
    what = 'sum(%s)' % item
    return cls.list(asObjects=False, sql='', like=like, isin=isin, orderby=
        orderby, where=where, limit=limit, what=what, **criteria)[0][what]


@classmethod
def _getExtra(cls, grows, extraD=False):
    """ provides growing dimension

        :param grows: growing dimension
        :type grows: :obj:`int`
        :param extraD: True if the object grows
        :type extraD: :obj:`bool`
        :returns: growing dimension
        :rtype: :obj:`int`
        """
    if extraD:
        if grows and grows > 1:
            exDim = grows
        else:
            exDim = 1
    else:
        exDim = 0
    return exDim


def check_host(host):
    """
    Returns SMTP host name and port
    """
    if 'gmail' in host:
        return 'smtp.gmail.com', 587
    elif 'yahoo' in host:
        return 'smtp.mail.yahoo.com', 465
    elif 'hotmail' in host or 'outlook' in host:
        return 'smtp.live.com', 25


def get_permissions_from_urls(urls):
    """
    Return a set of permissions for a given iterable of urls.

    :param urls: Iterable of url objects to check for permissions
    :type urls: Iterable[django.core.urlresolvers.RegexURLPattern]
    :return: Set of permissions for urls as strings
    :rtype: set[str]
    """
    permissions = set()
    for url in urls:
        if hasattr(url, 'permissions') and url.permissions:
            permissions.update(url.permissions)
    return permissions


@classmethod
def _get_metadata_key(cls, kw):
    """ kw could be e.g. 'compiler' """
    return cls.__name__ + '_' + kw


def utf(immigrant, xnl=True):
    """Convert to utf-8, and possibly delete new line character.
       xnl means "delete new line"
    """
    if xnl:
        return immigrant.decode('utf-8').strip('\n')
    else:
        return immigrant.decode('utf-8')


@classmethod
def release(cls, duration, start_level=1, curve_shape=None):
    """
        Construct an simple decaying envelope
        :param duration: total decay length
        :param start_level: level decayed from
        :param curve_shape: shape of the curve
        :return: an Envelope constructed accordingly
        """
    curve_shapes = (curve_shape,) if curve_shape is not None else None
    return cls.from_levels_and_durations((start_level, 0), (duration,),
        curve_shapes=curve_shapes)


def nptype(dtype):
    """ converts to numpy types

    :param dtype: h5 writer type type
    :type dtype: :obj:`str`
    :returns: nupy type
    :rtype: :obj:`str`
    """
    if str(dtype) in ['string', b'string']:
        return 'str'
    return dtype


def fileheader2dic(header):
    """
    Convert a fileheader list into a Sparky parameter dictionary.
    """
    dic = dict()
    dic['ident'] = str(header[0].decode()).strip('\x00')
    dic['naxis'] = ord(header[1].decode())
    dic['ncomponents'] = ord(header[2].decode())
    dic['encoding'] = ord(header[3].decode())
    dic['version'] = ord(header[4].decode())
    dic['owner'] = str(header[5].decode()).strip('\x00')
    dic['date'] = str(header[6].decode()).strip('\x00')
    dic['comment'] = str(header[7].decode()).strip('\x00')
    dic['seek_pos'] = header[8]
    dic['scratch'] = str(header[9].decode()).strip('\x00')
    return dic


def _get_traceback(content):
    """
    Get the traceback part from the content containing the standard
    error/output of a python process. It is used to get the traceback
    of `ramp_test_submission` when there is an error.

    Parameters
    ----------
    content : str

    Returns
    -------
    str with the traceback

    """
    if not content:
        return ''
    cut_exception_text = content.find('Traceback')
    if cut_exception_text > 0:
        content = content[cut_exception_text:]
    return content


def _user_written_stack_frame():
    """get the frame of first stack frame outside Viscid"""
    import inspect
    import os
    stack = inspect.stack()
    frame_info = None
    for frame_info in stack:
        if 'viscid' not in os.path.normpath(frame_info[1]):
            break
    return frame_info


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

        :param SharingUserError val:
        :rtype: ListFileMembersContinueError
        """
    return cls('user_error', val)


def homogenizeDictsN(allDicts, allKeys=0):
    """Homogenizes more than 3 dictionaries

	Not in use right now, for polyxipe"""
    ndicts = len(allDicts)
    if allKeys == 0:
        allKeys = []
        for dict in allDicts:
            allKeys = allKeys + dict.keys()
        allKeys = list(set(allKeys))
    newDicts = []
    for dict in allDicts:
        thisDict = {}
        for key in allKeys:
            if key in dict:
                thisDict[key] = dict[key]
            else:
                thisDict[key] = 0
        newDicts.append(thisDict)
    return newDicts


def _add_doc(func, doc):
    """Add documentation to a function."""
    func.__doc__ = doc


def bonfPCorrection(tup, numFeats):
    """given tuple with second entry a p value, multiply by num of feats and return"""
    return (tup[0], tup[1] * numFeats) + tup[2:]


def _upper(string):
    """Custom upper string function.
    Examples:
        foo_bar -> FooBar
    """
    return string.title().replace('_', '')


def count(iterable):
    """ Count elements that are True. """
    return float(len(list(filter(bool, iterable))))


def get_xds_commands(lines_of_input):
    """Get the command input to XDS - that is, all of the text between
    the line which goes ***** STEP ***** and **********. Love FORTRAN."""
    collecting = False
    result = []
    for l in lines_of_input:
        if '*****' in l and not collecting:
            collecting = True
            continue
        if '*****' in l:
            break
        if collecting:
            if l.strip():
                result.append(l.strip())
    return result


def chunks(l, n):
    """Yield successive n-sized chunks from l."""
    for i in range(0, len(l), n):
        yield l[i:i + n]


def set_attributes(d, elm):
    """Set attributes from dictionary of values."""
    for key in d:
        elm.setAttribute(key, d[key])


def remove_media_permissions(apps, schema_editor):
    """Reverse the above additions of permissions."""
    ContentType = apps.get_model('contenttypes.ContentType')
    Permission = apps.get_model('auth.Permission')
    media_content_type = ContentType.objects.get(model='media', app_label=
        'wagtailmedia')
    Permission.objects.filter(content_type=media_content_type, codename__in
        =('add_media', 'change_media', 'delete_media')).delete()


def theta_Ca_H_MP98(T, P):
    """c-c': calcium hydrogen [MP98]."""
    theta = 0.0612 + 0.0003275 * (T - 298.15)
    valid = T == 298.15
    return theta, valid


@classmethod
def create(cls, name, description, refgen, type='Ontology'):
    """
            This method creates a fresh Ontology with nothing it it.
        """
    self = super().create(name, description, type=type)
    self.refgen = refgen
    self._global('refgen', refgen.name)
    self._create_tables()
    return self


@classmethod
def all(cls, otp=False, ccid=False, u2f=False):
    """Returns a set of all USB modes, with optional filtering"""
    modes = set([cls.OTP, cls.CCID, cls.OTP_CCID, cls.U2F, cls.OTP_U2F, cls
        .U2F_CCID, cls.OTP_U2F_CCID])
    if otp:
        modes.difference_update(set([cls.CCID, cls.U2F, cls.U2F_CCID]))
    if ccid:
        modes.difference_update(set([cls.OTP, cls.U2F, cls.OTP_U2F]))
    if u2f:
        modes.difference_update(set([cls.OTP, cls.CCID, cls.OTP_CCID]))
    return modes


@classmethod
def content_add_lifecycle_environment(cls, options):
    """Add lifecycle environments to the capsule."""
    cls.command_sub = 'content add-lifecycle-environment'
    result = cls.execute(cls._construct_command(options), output_format='csv')
    return result


@staticmethod
def _checkDepth(z, dep_lays_choose):
    """
        TODO: Add docstring

        """
    if z > dep_lays_choose[-1]:
        return -1
    else:
        k = ((z - dep_lays_choose) ** 2).argmin()
        return k


def create_client_user(client):
    """helper function to create ClientUser instance on association proxy
    """
    from stalker.models.client import ClientUser
    return ClientUser(client=client)


def p_variable_modifiers_var(p):
    """variable_modifiers : VAR"""
    p[0] = []


@classmethod
def _from_et(cls, root, parent):
    """
        Create a :class:`Grid` from a :code:`grid` element.

        :param root: The element tree tree to parse.
        :param parent: :class:`EagleFilePart` that should hold the resulting :class:`EagleFilePart`
        :rtype: :class:`Grid`
        """
    n = cls()
    n._init_from_et(root, parent)
    return n


@classmethod
def flatten(cls, root_node):
    """ Flatten a parse tree """
    dumper = cls()
    dumper.go(root_node)
    return dumper.root


def check_param_val(param):
    """Wrapper on accessing a parameter.

    Parameters
    ----------
    param : Parameter
        The parameter whose value is being accessed.

    Returns
    -------
    The numerical value of the parameter.

    Raises
    ------
    ValueError
        Raises error if parameter value is None.
    """
    val = param.value
    if val is None:
        raise ValueError('Problem has missing parameter value.')
    else:
        return val


def task_hash(task):
    """
    Calculate the checksum of a task.

    input hash, output hash, environment hash

    Parameters
    ----------
    task : :class:`~pydra.engine.core.TaskBase`
        The input task.

    """
    return NotImplementedError


@staticmethod
def decode(buffer):
    """
          Get the value of a multi-byte integer from a buffer
          Return the value, and the number of bytes used.

          [MQTT-1.5.5-1] the encoded value MUST use the minimum number of bytes necessary to represent the value
        """
    multiplier = 1
    value = 0
    bytes = 0
    while 1:
        bytes += 1
        digit = buffer[0]
        buffer = buffer[1:]
        value += (digit & 127) * multiplier
        if digit & 128 == 0:
            break
        multiplier *= 128
    return value, bytes


def _is_autonomous(indep, exprs):
    """ Whether the expressions for the dependent variables are autonomous.

    Note that the system may still behave as an autonomous system on the interface
    of :meth:`integrate` due to use of pre-/post-processors.
    """
    if indep is None:
        return True
    for expr in exprs:
        try:
            in_there = indep in expr.free_symbols
        except:
            in_there = expr.has(indep)
        if in_there:
            return False
    return True


def editorAvailable():
    """Is the editor viewlet available in this context"""


def median(series, n):
    """
    中位数: 求series在n个周期内居于中间的数值

        注意:
            1. 当n为有效值但当前的series序列元素个数不足n个, 函数返回 NaN 序列
            2. 对n个周期内所有series排序后, 若n为奇数, 则选择第(n + 1) / 2个为中位数, 若n为偶数, 则中位数是(n / 2)以及(n / 2 + 1)的平均数

    Args:
        series (pandas.Series): 数据序列

        n (int): 周期

    Returns:
        pandas.Series: 中位数序列

    Example::

        例1:
            # 假设最近3日的收盘价为2727, 2754, 2748, 那么当前 median(df["close"], 3) 的返回值是2748
            median3 = tafunc.median(df["close"], 3)

        例2:
            # 假设最近4日的开盘价为2752, 2743, 2730, 2728, 那么当前 median(df["open"], 4) 的返回值是2736.5
            median4 = tafunc.median(df["open"], 4)
    """
    median_data = series.rolling(n).median()
    return median_data


def safe_join(root, *paths):
    """The provided os.path.join() does not work as desired. Any path starting with /
    will simply be returned rather than actually being joined with the other elements."""
    if not root.startswith('/'):
        root = '/' + root
    for path in paths:
        while root.endswith('/'):
            root = root[:-1]
        while path.startswith('/'):
            path = path[1:]
        root += '/' + path
    return root


def getimagesize(url):
    """
    Attempts to determine an image's width and height, and returns a tuple,
    (width, height), in pixels or an empty string in case of failure.
    Requires that PIL is installed.

    """
    try:
        from PIL import ImageFile
    except ImportError:
        return ''
    from urllib.request import urlopen
    try:
        p = ImageFile.Parser()
        f = urlopen(url)
        while True:
            s = f.read(1024)
            if not s:
                break
            p.feed(s)
            if p.image:
                return p.image.size
    except (IOError, ValueError):
        return ''


def loop_separate(loop: 'bmesh.types.BMLoop'):
    """Rip a vertex in a face away and add a new vertex.

    :param loop: The loop to separate.
    :type loop: 'bmesh.types.BMLoop'
    """
    pass


def YEAR(expression):
    """
    Returns the year portion of a date.
    See https://docs.mongodb.com/manual/reference/operator/aggregation/year/
    for more details
    :param expression: expression or variable of a Date, a Timestamp, or an ObjectID
    :return: Aggregation operator
    """
    return {'$year': expression}


def Fake():
    """load fake driver"""
    from .fake import FakeMotor
    return FakeMotor


def KK_RC75_fit(params, w, t_values):
    """
    Kramers-Kronig Function: -RC-

    Kristian B. Knudsen (kknu@berkeley.edu / kristianbknudsen@gmail.com)
    """
    Rs = params['Rs']
    R1 = params['R1']
    R2 = params['R2']
    R3 = params['R3']
    R4 = params['R4']
    R5 = params['R5']
    R6 = params['R6']
    R7 = params['R7']
    R8 = params['R8']
    R9 = params['R9']
    R10 = params['R10']
    R11 = params['R11']
    R12 = params['R12']
    R13 = params['R13']
    R14 = params['R14']
    R15 = params['R15']
    R16 = params['R16']
    R17 = params['R17']
    R18 = params['R18']
    R19 = params['R19']
    R20 = params['R20']
    R21 = params['R21']
    R22 = params['R22']
    R23 = params['R23']
    R24 = params['R24']
    R25 = params['R25']
    R26 = params['R26']
    R27 = params['R27']
    R28 = params['R28']
    R29 = params['R29']
    R30 = params['R30']
    R31 = params['R31']
    R32 = params['R32']
    R33 = params['R33']
    R34 = params['R34']
    R35 = params['R35']
    R36 = params['R36']
    R37 = params['R37']
    R38 = params['R38']
    R39 = params['R39']
    R40 = params['R40']
    R41 = params['R41']
    R42 = params['R42']
    R43 = params['R43']
    R44 = params['R44']
    R45 = params['R45']
    R46 = params['R46']
    R47 = params['R47']
    R48 = params['R48']
    R49 = params['R49']
    R50 = params['R50']
    R51 = params['R51']
    R52 = params['R52']
    R53 = params['R53']
    R54 = params['R54']
    R55 = params['R55']
    R56 = params['R56']
    R57 = params['R57']
    R58 = params['R58']
    R59 = params['R59']
    R60 = params['R60']
    R61 = params['R61']
    R62 = params['R62']
    R63 = params['R63']
    R64 = params['R64']
    R65 = params['R65']
    R66 = params['R66']
    R67 = params['R67']
    R68 = params['R68']
    R69 = params['R69']
    R70 = params['R70']
    R71 = params['R71']
    R72 = params['R72']
    R73 = params['R73']
    R74 = params['R74']
    R75 = params['R75']
    return Rs + R1 / (1 + w * 1.0j * t_values[0]) + R2 / (1 + w * 1.0j *
        t_values[1]) + R3 / (1 + w * 1.0j * t_values[2]) + R4 / (1 + w *
        1.0j * t_values[3]) + R5 / (1 + w * 1.0j * t_values[4]) + R6 / (1 +
        w * 1.0j * t_values[5]) + R7 / (1 + w * 1.0j * t_values[6]) + R8 / (
        1 + w * 1.0j * t_values[7]) + R9 / (1 + w * 1.0j * t_values[8]
        ) + R10 / (1 + w * 1.0j * t_values[9]) + R11 / (1 + w * 1.0j *
        t_values[10]) + R12 / (1 + w * 1.0j * t_values[11]) + R13 / (1 + w *
        1.0j * t_values[12]) + R14 / (1 + w * 1.0j * t_values[13]) + R15 / (
        1 + w * 1.0j * t_values[14]) + R16 / (1 + w * 1.0j * t_values[15]
        ) + R17 / (1 + w * 1.0j * t_values[16]) + R18 / (1 + w * 1.0j *
        t_values[17]) + R19 / (1 + w * 1.0j * t_values[18]) + R20 / (1 + w *
        1.0j * t_values[19]) + R21 / (1 + w * 1.0j * t_values[20]) + R22 / (
        1 + w * 1.0j * t_values[21]) + R23 / (1 + w * 1.0j * t_values[22]
        ) + R24 / (1 + w * 1.0j * t_values[23]) + R25 / (1 + w * 1.0j *
        t_values[24]) + R26 / (1 + w * 1.0j * t_values[25]) + R27 / (1 + w *
        1.0j * t_values[26]) + R28 / (1 + w * 1.0j * t_values[27]) + R29 / (
        1 + w * 1.0j * t_values[28]) + R30 / (1 + w * 1.0j * t_values[29]
        ) + R31 / (1 + w * 1.0j * t_values[30]) + R32 / (1 + w * 1.0j *
        t_values[31]) + R33 / (1 + w * 1.0j * t_values[32]) + R34 / (1 + w *
        1.0j * t_values[33]) + R35 / (1 + w * 1.0j * t_values[34]) + R36 / (
        1 + w * 1.0j * t_values[35]) + R37 / (1 + w * 1.0j * t_values[36]
        ) + R38 / (1 + w * 1.0j * t_values[37]) + R39 / (1 + w * 1.0j *
        t_values[38]) + R40 / (1 + w * 1.0j * t_values[39]) + R41 / (1 + w *
        1.0j * t_values[40]) + R42 / (1 + w * 1.0j * t_values[41]) + R43 / (
        1 + w * 1.0j * t_values[42]) + R44 / (1 + w * 1.0j * t_values[43]
        ) + R45 / (1 + w * 1.0j * t_values[44]) + R46 / (1 + w * 1.0j *
        t_values[45]) + R47 / (1 + w * 1.0j * t_values[46]) + R48 / (1 + w *
        1.0j * t_values[47]) + R49 / (1 + w * 1.0j * t_values[48]) + R50 / (
        1 + w * 1.0j * t_values[49]) + R51 / (1 + w * 1.0j * t_values[50]
        ) + R52 / (1 + w * 1.0j * t_values[51]) + R53 / (1 + w * 1.0j *
        t_values[52]) + R54 / (1 + w * 1.0j * t_values[53]) + R55 / (1 + w *
        1.0j * t_values[54]) + R56 / (1 + w * 1.0j * t_values[55]) + R57 / (
        1 + w * 1.0j * t_values[56]) + R58 / (1 + w * 1.0j * t_values[57]
        ) + R59 / (1 + w * 1.0j * t_values[58]) + R60 / (1 + w * 1.0j *
        t_values[59]) + R61 / (1 + w * 1.0j * t_values[60]) + R62 / (1 + w *
        1.0j * t_values[61]) + R63 / (1 + w * 1.0j * t_values[62]) + R64 / (
        1 + w * 1.0j * t_values[63]) + R65 / (1 + w * 1.0j * t_values[64]
        ) + R66 / (1 + w * 1.0j * t_values[65]) + R67 / (1 + w * 1.0j *
        t_values[66]) + R68 / (1 + w * 1.0j * t_values[67]) + R69 / (1 + w *
        1.0j * t_values[68]) + R70 / (1 + w * 1.0j * t_values[69]) + R71 / (
        1 + w * 1.0j * t_values[70]) + R72 / (1 + w * 1.0j * t_values[71]
        ) + R73 / (1 + w * 1.0j * t_values[72]) + R74 / (1 + w * 1.0j *
        t_values[73]) + R75 / (1 + w * 1.0j * t_values[74])


def default_parent_inspection(element, parent):
    """
    Check if the element bases has the specified parent
    :param element: the element to check
    :param parent: the expected parent
    :return: the check result
    """
    return parent in element.__bases__


def getuid(username):
    """Return username's numerical user ID."""
    import pwd
    return pwd.getpwnam(username)[2]


def security_group_rule_port(os_port):
    """Translate openstack rule port

    Translate to/from openstack - occi

    :param neutron_type: neutron status
    """
    ports = str(os_port).split('-')
    if ports.__len__() == 1:
        port_min = port_max = ports[0]
    elif ports.__len__() == 2:
        port_min, port_max = ports
    else:
        raise Exception('Port value')
    return port_min, port_max


def fresh_operation(op_id):
    """Create a default operation object."""
    operation = {'path': '', 'headers': {}, 'header_params': {},
        'path_params': {}, 'query_params': {}, 'params': {}, 'files': None,
        'form_data': None, 'json': None, 'id': op_id, 'dl_path': None,
        'auth_settings': 'access_token'}
    return operation


@classmethod
def get_default(cls):
    """Get a list of deposition type names."""
    from .registry import deposit_default_type
    return deposit_default_type.get()


def get_permissions_for_principal(principal_id):
    """Get the permissions granted to a principal.

        Return the list of (permission, setting) tuples that describe
        security assertions for this principal.

        If no permissions have been set for this principal, then the empty
        list is returned.
        """


def key_from_image_name(image_name):
    """
    >>> key_from_image_name('shipwright/blah:1234')
    '1234'
    """
    return image_name.split(':', 1)[1]


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


@staticmethod
def _inches(length, units='mm'):
    """Convert measurements to inches

        Inputs:

            * length (scalar) - dimension to be converted into units
            * units (str) - the units of the dimension. Must be one of mm, cm, inch, or pts

        Returns:

            * length in inches

        Example:

        >>> converted = Set._inches(10, 'cm') # Convert 10cm to inches
        >>> print '%.3f' %(converted) # Check the result
        3.937
        """
    unitconverter = {'pts': 1.0 / 72.0, 'mm': 0.039370079, 'cm': 0.39370079,
        'inch': 1.0}
    inches = length * unitconverter[units]
    return inches


@classmethod
def from_golix(cls, golix_obj):
    """ Convert the golix object to a lightweight representation.
        """
    return cls(ghid=golix_obj.ghid, author=golix_obj.binder, target=
        golix_obj.target)


def duplicate():
    """Duplicate selected control points

    """
    pass


def validate_component_name(component_name, allow_slashes=False):
    """Check that component name starts with an alphanumeric character, and
    disalllow all non-alphanumeric characters except underscore, hyphen, colon,
    and period in component names.
    """
    allowed = '_', '-', ':', '.'
    if allow_slashes:
        allowed += '/',
    if len(component_name) == 0:
        return False
    if not component_name[0].isalnum():
        return False
    for c in component_name:
        if c not in allowed and not c.isalnum():
            return False
    return True


@classmethod
def get_compatible_check_class(cls):
    """
        Get the compatible abstract check class.
        :return: cls
        """
    return None


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

        :param str val:
        :rtype: MemberAddResult
        """
    return cls('duplicate_external_member_id', val)


def get_corrupt_shares():
    """Return a set of (IServer, storage_index, sharenum) for all shares
        that were found to be corrupt before any repair was attempted.
        storage_index is binary.
        """


def _makenofollowfilematcher(repo, pats, opts):
    """hook for extensions to override the filematcher for non-follow cases"""
    return None


def hub_exceptions(state=True):
    """Toggles whether the hub prints exceptions that are raised from its
    timers.  This can be useful to see how greenthreads are terminating.
    """
    from eventlet import hubs
    hubs.get_hub().set_timer_exceptions(state)
    from eventlet import greenpool
    greenpool.DEBUG = state


def calc_height(thumb_width, viewport):
    """
    Figure out the height based on the viewport/thumbnail_max_width
    """
    width, height = map(int, viewport.split('x'))
    ratio = float(thumb_width) / width
    return int(height * ratio)


def lighter(image1, image2):
    """
    Compares the two images, pixel by pixel, and returns a new image containing
    the lighter values. At least one of the images must have mode "1".

    .. code-block:: python

        out = max(image1, image2)

    :rtype: :py:class:`~PIL.Image.Image`
    """
    image1.load()
    image2.load()
    return image1._new(image1.im.chop_lighter(image2.im))


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

    The output is in the closed interval :math:`[-\\pi/2, \\pi/2]`

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

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

       - arctan(default) = default
       - arctan(row_sparse) = row_sparse
       - arctan(csr) = csr

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

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

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

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


def _add_doc(func, doc):
    """Add documentation to a function."""
    func.__doc__ = doc


def get_magic(name):
    """Get a magic function by name or None if not exists."""
    return globals().get('do_' + name)


def _outputs_contain_output_type(restricted_red_batch_outputs, output_type):
    """
    Returns whether the given restricted red batch outputs contain an output with the given output type.
    This function is used to determine, if this batch output contain stdout or stderr specifications.

    :param restricted_red_batch_outputs: The restricted red batch outputs to search in. The keys are the output keys of
                                         the converted red file and the values are the output values corresponding to
                                         this key.
    :type restricted_red_batch_outputs: dict
    :param output_type: The OutputType to search given as string
    :type output_type: str
    :return: True, if an output of type output_type could be found, otherwise False
    """
    for output_value in restricted_red_batch_outputs.values():
        if output_value.get('class') == output_type:
            return True
    return False


@classmethod
def serialize_string(cls, read):
    """
        Emulates gst_value_serialize_string.
        Accepts a bytes, str or None type.
        Returns a str type.
        """
    if read is None:
        return 'NULL'
    if read == 'NULL':
        return '"NULL"'
    if type(read) is bytes:
        pass
    elif type(read) is str:
        read = read.encode()
    else:
        raise TypeError('Expect a None, str, or a bytes type')
    if not read:
        return '""'
    added_wrap = False
    ser_string_list = []
    for byte in bytearray(read):
        if byte in cls.GST_ASCII_CHARS:
            ser_string_list.append(chr(byte))
        elif byte < 32 or byte >= 127:
            ser_string_list.append('\\{:03o}'.format(byte))
            added_wrap = True
        else:
            ser_string_list.append('\\' + chr(byte))
            added_wrap = True
    if added_wrap:
        ser_string_list.insert(0, '"')
        ser_string_list.append('"')
    return ''.join(ser_string_list)


@staticmethod
def _have_required_configs(config):
    """Will raise an exception if any are missing."""
    config.get('JIRA', 'server')
    config.get('JIRA', 'username')
    config.get('JIRA', 'password')
    config.get('Gerrit', 'url')


def create_attachment(payload):
    """Create a simple url-based attachment"""
    assert payload['type'] in ['image', 'video', 'file', 'audio'
        ], 'unsupported attachment type'
    assert 'url' in payload or 'attachment_id' in payload, 'unsupported attachment method: must contain url or attachment_id'
    if 'url' in payload:
        return {'type': payload['type'], 'payload': {'url': payload['url']}}
    elif 'attachment_id' in payload:
        return {'type': payload['type'], 'payload': {'attachment_id':
            payload['attachment_id']}}


def create_instance_export_task(Description=None, InstanceId=None,
    TargetEnvironment=None, ExportToS3Task=None):
    """
    Exports a running or stopped instance to an S3 bucket.
    For information about the supported operating systems, image formats, and known limitations for the types of instances you can export, see Exporting an Instance as a VM Using VM Import/Export in the VM Import/Export User Guide .
    See also: AWS API Documentation

    :example: response = client.create_instance_export_task(
        Description='string',
        InstanceId='string',
        TargetEnvironment='citrix'|'vmware'|'microsoft',
        ExportToS3Task={
            'DiskImageFormat': 'VMDK'|'RAW'|'VHD',
            'ContainerFormat': 'ova',
            'S3Bucket': 'string',
            'S3Prefix': 'string'
        }
    )

    :type Description: string
    :param Description: A description for the conversion task or the resource being exported. The maximum length is 255 bytes.

    :type InstanceId: string
    :param InstanceId: [REQUIRED]
            The ID of the instance.

    :type TargetEnvironment: string
    :param TargetEnvironment: The target virtualization environment.

    :type ExportToS3Task: dict
    :param ExportToS3Task: The format and location for an instance export task.
            DiskImageFormat (string) --The format for the exported image.
            ContainerFormat (string) --The container format used to combine disk images with metadata (such as OVF). If absent, only the disk image is exported.
            S3Bucket (string) --The S3 bucket for the destination image. The destination bucket must exist and grant WRITE and READ_ACP permissions to the AWS account vm-import-export@amazon.com .
            S3Prefix (string) --The image is written to a single object in the S3 bucket at the S3 key s3prefix + exportTaskId + '.' + diskImageFormat.

    :rtype: dict
    :return: {
        'ExportTask': {
            'ExportTaskId': 'string',
            'Description': 'string',
            'State': 'active'|'cancelling'|'cancelled'|'completed',
            'StatusMessage': 'string',
            'InstanceExportDetails': {
                'InstanceId': 'string',
                'TargetEnvironment': 'citrix'|'vmware'|'microsoft'
            },
            'ExportToS3Task': {
                'DiskImageFormat': 'VMDK'|'RAW'|'VHD',
                'ContainerFormat': 'ova',
                'S3Bucket': 'string',
                'S3Key': 'string'
            }
        }
    }

    """
    pass


def linkrev(rev):
    """Obtain the changeset revision number a revision is linked to."""


@staticmethod
def __evaluate__(x_obj, y_obj):
    """Perform a greater than on int or float."""
    if isinstance(x_obj, (float, int)) and isinstance(y_obj, (float, int)):
        return x_obj > y_obj
    return False


def load_numpy_f2py___version__(finder, module):
    """the numpy.f2py.__version__ module optionally imports the __svn_version__
       module; ignore the error if the module cannot be found."""
    module.IgnoreName('__svn_version__')


def substitute(template, context):
    """
    Performs string substitution.

    Args:
        template (str): The string to perform the substitution on.
        context (dict): A mapping of keys to values for substitution.

    Returns:
        str: The substituted string.
    """
    from string import Template
    template = Template(template)
    return template.safe_substitute(context)


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

    Like 'git describe --tags --dirty --always -long'.
    The distance/hash is unconditional.

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


def escape_html(text):
    """Escape &, <, > as well as single and double quotes for HTML."""
    return text.replace('&', '&').replace('<', '<').replace('>', '>'
        ).replace('"', '"').replace("'", ''')