def sapm_cell_from_module(module_temperature, poa_global, deltaT, irrad_ref
    =1000):
    """
    Calculate cell temperature from module temperature using the Sandia Array
    Performance Model.

    See [1]_ for details on the Sandia Array Performance Model.

    Parameters
    ----------
    module_temperature : numeric
        Temperature of back of module surface [C].

    poa_global : numeric
        Total incident irradiance [W/m^2].

    deltaT : float
        Parameter :math:`\\Delta T` in :eq:`sapm2` [C].

    irrad_ref : float, default 1000
        Reference irradiance, parameter :math:`E_{0}` in
        :eq:`sapm2` [W/m^2].

    Returns
    -------
    numeric, values in degrees C.

    Notes
    -----
    The model for cell temperature :math:`T_{C}` is given by Eq. 12 in [1]_.

    .. math::
       :label: sapm2

       T_{C} = T_{m} + \\frac{E}{E_{0}} \\Delta T

    The module back surface temperature :math:`T_{m}` is implemented in
    :py:func:`~pvlib.temperature.sapm_module`.

    Model parameters depend both on the module construction and its mounting.
    Parameter sets are provided in [1]_ for representative modules and
    mounting, and are coded for convenience in
    ``pvlib.temperature.TEMPERATURE_MODEL_PARAMETERS``.

    +---------------+----------------+-------+---------+---------------------+
    | Module        | Mounting       | a     | b       | :math:`\\Delta T [C]`|
    +===============+================+=======+=========+=====================+
    | glass/glass   | open rack      | -3.47 | -0.0594 | 3                   |
    +---------------+----------------+-------+---------+---------------------+
    | glass/glass   | close roof     | -2.98 | -0.0471 | 1                   |
    +---------------+----------------+-------+---------+---------------------+
    | glass/polymer | open rack      | -3.56 | -0.075  | 3                   |
    +---------------+----------------+-------+---------+---------------------+
    | glass/polymer | insulated back | -2.81 | -0.0455 | 0                   |
    +---------------+----------------+-------+---------+---------------------+

    References
    ----------
    .. [1] King, D. et al, 2004, "Sandia Photovoltaic Array Performance
       Model", SAND Report 3535, Sandia National Laboratories, Albuquerque,
       NM.

    See also
    --------
    sapm_cell
    sapm_module
    """
    return module_temperature + poa_global / irrad_ref * deltaT


def is_ssh_for_nimbus(env_config):
    """Check if we need to use SSH access to Nimbus or not.
    """
    return env_config.get('use_ssh_for_nimbus', True)


@staticmethod
def _getdata(theroot):
    """Get a set of child node data and a mapping of data to node."""
    lookup = {}
    data = []
    for c in theroot.childnodes:
        d = c.data[0]
        lookup[d] = c
        data.append(d)
    return lookup, set(data)


def close():
    """Release the accessor.

        Resources held by the accessor are freed, and further use of
        the accessor will result in a `ValueError` exception.

        """


def IGT(SG, Tavg, mu, L=None, D=None, P1=None, P2=None, Q=None, Ts=288.7,
    Ps=101325.0, Zavg=1, E=1):
    """Calculation function for dealing with flow of a compressible gas in a
    pipeline with the IGT formula. Can calculate any of the following,
    given all other inputs:

    * Flow rate
    * Upstream pressure
    * Downstream pressure
    * Diameter of pipe
    * Length of pipe

    A variety of different constants and expressions have been presented
    for the IGT formula. Here, the form as in [1]_
    is used but with all inputs in base SI units.

    .. math::
        Q = 24.6241\\frac{T_s}{P_s}E\\left(\\frac{P_1^2 - P_2^2}{L \\cdot Z_{avg}
        \\cdot T_{avg}}\\right)^{5/9} \\left(\\frac{D^{8/3}}{\\mu^{1/9}
        SG^{4/9}}\\right)

    Parameters
    ----------
    SG : float
        Specific gravity of fluid with respect to air at the reference
        temperature and pressure `Ts` and `Ps`, [-]
    Tavg : float
        Average temperature of the fluid in the pipeline, [K]
    mu : float
        Average viscosity of the fluid in the pipeline, [Pa*s]
    L : float, optional
        Length of pipe, [m]
    D : float, optional
        Diameter of pipe, [m]
    P1 : float, optional
        Inlet pressure to pipe, [Pa]
    P2 : float, optional
        Outlet pressure from pipe, [Pa]
    Q : float, optional
        Flow rate of gas through pipe, [m^3/s]
    Ts : float, optional
        Reference temperature for the specific gravity of the gas, [K]
    Ps : float, optional
        Reference pressure for the specific gravity of the gas, [Pa]
    Zavg : float, optional
        Average compressibility factor for gas, [-]
    E : float, optional
        Pipeline efficiency, a correction factor between 0 and 1

    Returns
    -------
    Q, P1, P2, D, or L : float
        The missing input which was solved for [base SI]

    Notes
    -----
    This model is presented in [1]_ with a leading constant of 0.6643, the same
    exponents as used here, units of inches (diameter), psi, feet (length),
    Rankine, pound/(foot*second) for viscosity, and 1000 ft^3/hour.

    This model is also presented in [2]_  in both SI and imperial form. Both
    forms are correct. The imperial version has a leading constant of 136.9,
    the same powers as used here except with rounded values of powers of
    viscosity (0.2) and specific gravity (0.8) rearranged to be inside the
    bracketed group; its units are inches (diameter), psi, miles (length),
    Rankine, pound/(foot*second) for viscosity, and ft^3/day.

    This model is shown in base SI units in [3]_, and with a leading constant
    of 24.6145, and the same powers as used here.

    Examples
    --------
    >>> IGT(D=0.340, P1=90E5, P2=20E5, L=160E3, SG=0.693, mu=1E-5, Tavg=277.15)
    48.92351786788815

    References
    ----------
    .. [1] Mohitpour, Mo, Golshan, and Allan Murray. Pipeline Design and
       Construction: A Practical Approach. 3rd edition. New York: Amer Soc
       Mechanical Engineers, 2006.
    .. [2] Menon, E. Shashi. Gas Pipeline Hydraulics. 1st edition. Boca Raton,
       FL: CRC Press, 2005.
    .. [3] Coelho, Paulo M., and Carlos Pinho. "Considerations about Equations
       for Steady State Flow in Natural Gas Pipelines." Journal of the
       Brazilian Society of Mechanical Sciences and Engineering 29, no. 3
       (September 2007): 262-73. doi:10.1590/S1678-58782007000300005.
    """
    c5 = 24.62412451461407
    c2 = 5 / 9.0
    c3 = 8 / 3.0
    c4 = 4 / 9.0
    c1 = 1 / 9.0
    if Q is None and None not in [L, D, P1, P2]:
        return c5 * Ts / Ps * E * ((P1 ** 2 - P2 ** 2) / Tavg / L / Zavg
            ) ** c2 * D ** c3 / SG ** c4 / mu ** c1
    elif D is None and None not in [L, Q, P1, P2]:
        return (Ps * Q * SG ** c4 * mu ** c1 * ((P1 ** 2 - P2 ** 2) / (L *
            Tavg * Zavg)) ** -c2 / (E * Ts * c5)) ** (1.0 / c3)
    elif P1 is None and None not in [L, Q, D, P2]:
        return (L * Tavg * Zavg * (D ** -c3 * Ps * Q * SG ** c4 * mu ** c1 /
            (E * Ts * c5)) ** (1 / c2) + P2 ** 2) ** 0.5
    elif P2 is None and None not in [L, Q, D, P1]:
        return (-L * Tavg * Zavg * (D ** -c3 * Ps * Q * SG ** c4 * mu ** c1 /
            (E * Ts * c5)) ** (1 / c2) + P1 ** 2) ** 0.5
    elif L is None and None not in [P2, Q, D, P1]:
        return (D ** -c3 * Ps * Q * SG ** c4 * mu ** c1 / (E * Ts * c5)) ** (
            -1 / c2) * (P1 ** 2 - P2 ** 2) / (Tavg * Zavg)
    else:
        raise Exception(
            'This function solves for either flow, upstream pressure, downstream pressure, diameter, or length; all other inputs must be provided.'
            )


def remove_all_resource_permissions(ResourceId=None):
    """
    Removes all the permissions from the specified resource.
    See also: AWS API Documentation

    :example: response = client.remove_all_resource_permissions(
        ResourceId='string'
    )

    :type ResourceId: string
    :param ResourceId: [REQUIRED]
            The ID of the resource.

    """
    pass


def order_chunks(hub, chunks):
    """
    Sort the chunk list verifying that the chunks follow the order
    specified in the order options.
    """
    cap = 1
    for chunk in chunks:
        if 'order' in chunk:
            if not isinstance(chunk['order'], int):
                continue
            chunk_order = chunk['order']
            if chunk_order > cap - 1 and chunk_order > 0:
                cap = chunk_order + 100
    for chunk in chunks:
        if 'order' not in chunk:
            chunk['order'] = cap
            continue
        if not isinstance(chunk['order'], (int, float)):
            if chunk['order'] == 'last':
                chunk['order'] = cap + 1000000
            elif chunk['order'] == 'first':
                chunk['order'] = 0
            else:
                chunk['order'] = cap
        if 'name_order' in chunk:
            chunk['order'] = chunk['order'] + chunk.pop('name_order') / 10000.0
        if chunk['order'] < 0:
            chunk['order'] = cap + 1000000 + chunk['order']
    chunks.sort(key=lambda chunk: (chunk['order'],
        '{0[state]}{0[name]}{0[fun]}'.format(chunk)))
    return chunks


def iter_fields(node):
    """Iterate over all fields of a node, only yielding existing fields."""
    if not hasattr(node, '_fields') or not node._fields:
        return
    for field in node._fields:
        try:
            yield field, getattr(node, field)
        except AttributeError:
            pass


def is_special(ip_address):
    """Determine if the address is SPECIAL
       Note: This is super bad, improve it
    """
    special = {'224.0.0.251': 'multicast_dns', 'ff02::fb': 'multicast_dns'}
    return special[ip_address] if ip_address in special else False


def req_map(hub):
    """
    Gather the requisite restrtrictions and populate the requisite behavior map
    """
    rmap = {}
    for mod in hub.idem.req:
        if mod.__name__ == 'init':
            continue
        if hasattr(mod, 'define'):
            rmap[mod.__name__] = mod.define()
    hub.idem.RMAP = rmap


def bits_to_indices(mask):
    """Generate list of indices of bits set to one in the value."""
    i = 1
    while mask > 0:
        if bool(mask & 1):
            yield i
        mask >>= 1
        i += 1
    return


def shell_quote(arg):
    """
    Quote a string argument to be safely included in a shell command line.

    :param str arg: The script argument
    :return: The argument quoted
    """
    assert arg is not None
    return "'%s'" % arg.replace("'", "'\\''")


def MIDPOINT(df, n, price='Close'):
    """
    MidPoint over period
    source: http://www.tadoc.org/indicator/MIDPOINT.htm
    """
    midpoint_list = []
    i = 0
    while i < len(df[price]):
        if i + 1 < n:
            midpoint = float('NaN')
        else:
            start = i + 1 - n
            end = i + 1
            midpoint = (max(df[price][start:end]) + min(df[price][start:end])
                ) / 2
        midpoint_list.append(midpoint)
        i += 1
    return midpoint_list


@classmethod
def capture_ids(cls, obj):
    """
        Given an list of ids, capture a list of ids that can be
        restored using the restore_ids.
        """
    return obj.traverse(lambda o: getattr(o, 'id'))


def get_vlan() ->int:
    """Generates a globally unique VLAN tags.

    :return: VLAN tag"""
    for i in range(2000, 4096):
        yield i


def DownloadData(status, conf) ->int:
    """This is main interface.

    Args:
        status (dict): Status.
        conf (dict): Configuration.
    """
    status_cod = -1
    return status_cod


def selector(zelf, *args, **kwargs):
    """ see if this objects has the desired attributes. """
    wanted = args[0]
    if not wanted:
        return True
    go = False
    for w in wanted:
        if zelf.get(w, ''):
            go = True
            break
    return go


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

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

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


def get_productions_d(productions):
    """ Get productions as a dictionary """
    productions_d = dict()
    for production in productions:
        production_head = productions_d.setdefault(production.head, [])
        production_head.append(production)
    return productions_d


def get_capabilities():
    """ Returns a capabilities dictionary, where the keys are the strings
        below and its values are Capability instances

        * item_code           (str)
        * item_id             (int)
        * items_quantity      (float)
        * item_price          (float)
        * item_description    (str)
        * payment_value       (float)
        * payment_description (str)
        * promotional_message (str)
        * customer_name       (str)
        * customer_id         (str)
        * customer_address    (str)
        * add_cash_value      (float)
        * remove_cash_value   (float)
        """


def list_workers_with_qualification_type(QualificationTypeId=None, Status=
    None, NextToken=None, MaxResults=None):
    """
    The ListWorkersWithQualificationType operation returns all of the Workers that have been associated with a given Qualification type.
    See also: AWS API Documentation

    :example: response = client.list_workers_with_qualification_type(
        QualificationTypeId='string',
        Status='Granted'|'Revoked',
        NextToken='string',
        MaxResults=123
    )

    :type QualificationTypeId: string
    :param QualificationTypeId: [REQUIRED]
            The ID of the Qualification type of the Qualifications to return.

    :type Status: string
    :param Status: The status of the Qualifications to return. Can be Granted | Revoked .

    :type NextToken: string
    :param NextToken: Pagination Token

    :type MaxResults: integer
    :param MaxResults: Limit the number of results returned.

    :rtype: dict
    :return: {
        'NextToken': 'string',
        'NumResults': 123,
        'Qualifications': [
            {
                'QualificationTypeId': 'string',
                'WorkerId': 'string',
                'GrantTime': datetime(2015, 1, 1),
                'IntegerValue': 123,
                'LocaleValue': {
                    'Country': 'string',
                    'Subdivision': 'string'
                },
                'Status': 'Granted'|'Revoked'
            },
        ]
    }

    """
    pass


def isFolderOrFolderDefaultPage():
    """Returns true only if the current object is either a folder (as
           determined by isStructuralFolder) or the default page in context.
        """


def lyround(x, basen):
    """
    Rounds the specified number using a specific base

    **Parameters**

    x: *float*
        The value to be rounded

    basen: *int*
        The number base to use for rounding

    **Returns**

    value: *float*
        The rounded value.

    **Notes**

    This function is based on http://stackoverflow.com/questions/2272149/round-to-5-or-other-number-in-python
    """
    base = basen ** (int(len(str(int(x)))) - 1)
    return int(base * round(float(x) / base))


@staticmethod
def number(tree):
    """
        Compiles a number tree
        """
    token = tree.child(0)
    if token.value[0] == '+':
        token.value = token.value[1:]
    if token.type == 'FLOAT':
        return {'$OBJECT': 'float', 'float': float(token.value)}
    return {'$OBJECT': 'int', 'int': int(token.value)}


def use(app=None, gl=None):
    """ Set the usage options for vispy

    Specify what app backend and GL backend to use.

    Parameters
    ----------
    app : str
        The app backend to use (case insensitive). Standard backends:
            * 'PyQt4': use Qt widget toolkit via PyQt4.
            * 'PyQt5': use Qt widget toolkit via PyQt5.
            * 'PySide': use Qt widget toolkit via PySide.
            * 'PyGlet': use Pyglet backend.
            * 'Glfw': use Glfw backend (successor of Glut). Widely available
              on Linux.
            * 'SDL2': use SDL v2 backend.
            * 'osmesa': Use OSMesa backend
        Additional backends:
            * 'ipynb_vnc': render in the IPython notebook via a VNC approach
              (experimental)
    gl : str
        The gl backend to use (case insensitive). Options are:
            * 'gl2': use Vispy's desktop OpenGL API.
            * 'pyopengl2': use PyOpenGL's desktop OpenGL API. Mostly for
              testing.
            * 'es2': (TO COME) use real OpenGL ES 2.0 on Windows via Angle.
              Availability of ES 2.0 is larger for Windows, since it relies
              on DirectX.
            * 'gl+': use the full OpenGL functionality available on
              your system (via PyOpenGL).

    Notes
    -----
    If the app option is given, ``vispy.app.use_app()`` is called. If
    the gl option is given, ``vispy.gloo.use_gl()`` is called.

    If an app backend name is provided, and that backend could not be
    loaded, an error is raised.

    If no backend name is provided, Vispy will first check if the GUI
    toolkit corresponding to each backend is already imported, and try
    that backend first. If this is unsuccessful, it will try the
    'default_backend' provided in the vispy config. If still not
    succesful, it will try each backend in a predetermined order.

    See Also
    --------
    vispy.app.use_app
    vispy.gloo.gl.use_gl
    """
    if app is None and gl is None:
        raise TypeError('Must specify at least one of "app" or "gl".')
    if app == 'ipynb_webgl':
        app = 'headless'
        gl = 'webgl'
    if app == 'osmesa':
        from ..util.osmesa_gl import fix_osmesa_gl_lib
        fix_osmesa_gl_lib()
        if gl is not None:
            raise ValueError('Do not specify gl when using osmesa')
    if gl:
        from .. import gloo, config
        config['gl_backend'] = gl
        gloo.gl.use_gl(gl)
    if app:
        from ..app import use_app
        use_app(app)


def addIterativeIonPair(object1, object2, interaction, version):
    """
    Adding the Coulomb 'iterative' interaction (an acid-base pair):
    the pKa of the acid is lowered & the pKa of the base is raised
    """
    values = interaction[1]
    annihilation = interaction[2]
    hbond_value = values[0]
    coulomb_value = values[1]
    Q1 = object1.Q
    Q2 = object2.Q
    comp1 = object1.pKa_old + annihilation[0] + Q1 * coulomb_value
    comp2 = object2.pKa_old + annihilation[1] + Q2 * coulomb_value
    if (object1.resName not in version.parameters.
        exclude_sidechain_interactions):
        comp1 += Q1 * hbond_value
    if (object2.resName not in version.parameters.
        exclude_sidechain_interactions):
        comp2 += Q2 * hbond_value
    if Q1 == -1.0 and comp1 < comp2:
        add_term = True
    elif Q1 == 1.0 and comp1 > comp2:
        add_term = True
    else:
        add_term = False
    annihilation[0] = 0.0
    annihilation[1] = 0.0
    if add_term == True:
        if coulomb_value > 0.005:
            interaction = [object2, Q1 * coulomb_value]
            annihilation[0] += -Q1 * coulomb_value
            object1.determinants['coulomb'].append(interaction)
            interaction = [object1, Q2 * coulomb_value]
            annihilation[1] += -Q2 * coulomb_value
            object2.determinants['coulomb'].append(interaction)
        if hbond_value > 0.005:
            if (object1.resName not in version.parameters.
                exclude_sidechain_interactions):
                interaction = [object2, Q1 * hbond_value]
                annihilation[0] += -Q1 * hbond_value
                object1.determinants['sidechain'].append(interaction)
            if (object2.resName not in version.parameters.
                exclude_sidechain_interactions):
                interaction = [object1, Q2 * hbond_value]
                annihilation[1] += -Q2 * hbond_value
                object2.determinants['sidechain'].append(interaction)


def _ensure_geometry_column(df):
    """
    Helper function to ensure the geometry column is called 'geometry'.
    If another column with that name exists, it will be dropped.
    """
    if not df._geometry_column_name == 'geometry':
        if 'geometry' in df.columns:
            df.drop('geometry', axis=1, inplace=True)
        df.rename(columns={df._geometry_column_name: 'geometry'}, copy=
            False, inplace=True)
        df.set_geometry('geometry', inplace=True)


def qualifying_prefix(modname, qualname):
    """
    Returns a new string that is used for the first half of the mangled name.
    """
    return '{}.{}'.format(modname, qualname) if modname else qualname


def molecular_type(name, bases=(str,)):
    """Define a new molecular type

    The optional argument bases (defaults to str) can be any python
    type or tuple of types.
    """
    if not isinstance(bases, tuple):
        bases = bases,
    return type(name, bases, {})


def force_to_branch_head(repo, branch):
    """Checkout branch and reset --hard"""
    if repo.get_branch() == branch:
        repo.force_head(branch, hard=True)
    repo.set_branch(branch)


def poll():
    """Called periodically to poll for projects"""


def _check_length_equal(param_1, param_2, name_param_1, name_param_2):
    """
    Raises an error when the length of given two arguments is not equal
    """
    if len(param_1) != len(param_2):
        raise ValueError('Length of {} must be same as Length of {}'.format
            (name_param_1, name_param_2))


def extract_smilesfile(line) ->str:
    """
    Extract smiles from SMILES file

    Returns:
        SMILES string
    """
    return line.split(' ')[0].strip()


def authenticated_userid(request):
    """Helper function that can be used in ``db_key`` to support `self`
    as a collection key.
    """
    user = getattr(request, 'user', None)
    key = user.pk_field()
    return getattr(user, key)


@classmethod
def index(cls, value):
    """Return an index into the Enum given a value."""
    return cls.ALL.index(value)


def get_diagonal(x):
    """
    Return a writeable view of the diagonal of x
    """
    return x.reshape(-1)[::x.shape[0] + 1]


def equals_lf(line):
    """Return True if line (a text or byte string) equals '
'."""
    return line == ('\n' if isinstance(line, str) else b'\n')


def f_to_c(f=0):
    """ Convert fahrenheight to celcius """
    return round((f - 32.0) / 1.8, 2)


def to_upper_camel_case(snake_case_str):
    """Converts snake_case to UpperCamelCase.
    Example:
        foo_bar -> FooBar
    """
    return ''.join(map(str.title, snake_case_str.split('_')))


def aicc(llf, nobs, df_modelwc):
    """Akaike information criterion (AIC) with small sample correction

    Parameters
    ----------
    llf : float
        value of the loglikelihood
    nobs : int
        number of observations
    df_modelwc : int
        number of parameters including constant

    Returns
    -------
    aicc : float
        information criterion

    References
    ----------
    http://en.wikipedia.org/wiki/Akaike_information_criterion#AICc

    """
    return -2.0 * llf + 2.0 * df_modelwc * nobs / (nobs - df_modelwc - 1.0)


@staticmethod
def _chunks(fulllist, chunklength):
    """Yield successive n-sized chunks from l."""
    for pos in range(0, len(fulllist), chunklength):
        yield fulllist[pos:pos + chunklength]


@classmethod
def record_add(cls, dn, attrs):
    """Called to indicate the addition of a new LDAP record.

        :param str dn: The DN of the added record.

        :param attrs: The record's attributes.
        :type attrs: Dict of lists of bytes

        :return: None - any returned value is ignored.

        .. warning::

            :data:`attrs` is passed by reference.  If you modify the
            dictionary—or its contents—in any way, you will pay for it later!

        This callback can happen in all modes, and in all phases, to indicate
        that an entry has been added to your view of the search results.  In
        refresh-only mode, and the refresh phase of refresh-and-perist mode,
        the addition may have taken place at any time since your last update.
        In the persist phase of refresh-and-persist mode, a new entry has just
        been added—or modified—such that it matches your search.

        Attributes which are not present in the record will not present in
        `attrs`.  Dict keys are attribute names, and dict values are arrays
        (to support multi-valued attributes).

        .. note::

            Just because the dict values are arrays, does not mean that all
            attributes are multi-valued.  The LDAP client does not know which
            attributes are single- and which are multi-valued, so it assumes
            that all are multi-valued.

            Also, all attribute values will come in as (in Python 2) :obj:`str`
            objects or (in Python 3) :obj:`bytes` objects.

            To learn which attributes are single- or multi-valued, and to learn
            the type (or, in LDAP terms, the *syntax*) of an attribute, you
            need to look at the schema, possibly using :mod:`ldap.schema`.
        """
    pass


def get_all_names():
    """Returns all names that may be authenticated.

        :rtype: `collections.Iterable` of `str`

        """


def co_code_findloadednames(co):
    """Find in the code of a code object, all loaded names.
    (by LOAD_NAME, LOAD_GLOBAL or LOAD_FAST) """
    import dis
    from opcode import HAVE_ARGUMENT, opmap
    hasloadname = opmap['LOAD_NAME'], opmap['LOAD_GLOBAL'], opmap['LOAD_FAST']
    insns = dis.get_instructions(co)
    len_co_names = len(co.co_names)
    indexset = {}
    for insn in insns:
        if insn.opcode >= HAVE_ARGUMENT:
            if insn.opcode in hasloadname:
                indexset[insn.argval] = 1
                if len(indexset) >= len_co_names:
                    break
    for name in co.co_varnames:
        try:
            del indexset[name]
        except KeyError:
            pass
    return indexset


def _fold(header):
    """Fold a header line into multiple crlf-separated lines at column 72."""
    i = header.rfind(b'\r\n ')
    if i == -1:
        pre = b''
    else:
        i += 3
        pre = header[:i]
        header = header[i:]
    while len(header) > 72:
        i = header[:72].rfind(b' ')
        if i == -1:
            i = j = 72
        else:
            j = i + 1
        pre += header[:i] + b'\r\n '
        header = header[j:]
    return pre + header


def init(config, endpoints):
    """
    Initialize authenticator with configuration values and properties of all modules.
    :param config: hash with parsed client_authentication section of yaml configuration
    :param modules: hash containing True or False for endpoints, if True, perform auth, if False, skip (see ``server`` module)
    """
    pass


def add_sra_subparser(subparser):
    """
    Function to add subparser for SRA data.
    """
    parser_sra = subparser.add_parser('sra', help='download from SRA')
    parser_sra.add_argument('id', type=str, nargs='+', help=
        'One or more BioProject, ERR/SRR or ERP/SRP number(s)')
    parser_sra.add_argument('-m', dest='metadata', type=str, default='',
        help=
        'filename in which to save SRA metadata (.csv format, relative to OUTDIR)'
        )
    parser_sra.add_argument('-o', dest='outdir', type=str, default='', help
        ="directory in which to save output. created if it doesn't exist")
    parser_sra.add_argument('-r', dest='retries', type=int, default=2, help
        ='number of times to retry download')
    parser_sra.add_argument('-t', dest='threads', type=int, default=1, help
        ='threads to use (for fasterq-dump/pigz)')
    parser_sra.add_argument('-f', dest='force', action='store_true', help=
        'force re-download of files')
    parser_sra.add_argument('-l', dest='list', action='store_true', help=
        'list (but do not download) samples to be grabbed')
    parser_sra.add_argument('--parse_run_ids', dest='SRR_parsing', action=
        'store_true', help=
        'parse SRR/ERR identifers (do not pass straight to fasterq-dump)')
    parser_sra.add_argument('--use_fastq_dump', dest='fastqdump', action=
        'store_true', help=
        'use legacy fastq-dump instead of fasterq-dump (no multithreaded downloading)'
        )
    parser_sra.add_argument('--custom_fqdump_args', dest='custom_fqd_args',
        type=str, default='', help=
        "'string' containing args to pass to fast(er)q-dump")
    parser_sra.add_argument('--no_parsing', dest='no_SRR_parsing', action=
        'store_true', help='Legacy option to not parse SRR IDs (now default)')


@classmethod
def wrap(cls, iterator, length=None, **kargs):
    """Shortcut to wrap an iterator that does not do all the work internally"""
    return cls(iterator, length, body=True, **kargs)


@staticmethod
def get_attributes(operation, **kwargs):
    """ Get the operation attributes. """
    if operation:
        command = operation.command
        input_obj = operation.input_obj
        context = operation.context
        params = operation.params
    else:
        command = kwargs.pop('command', None)
        input_obj = kwargs.pop('input_obj', None)
        context = kwargs.pop('context', None)
        params = kwargs.pop('params', kwargs)
    return command, input_obj, params, context


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


def parse_args(args):
    """
    This parses the arguments and returns a tuple containing:

    (args, command, command_args)

    For example, "--config=bar start --with=baz" would return:

    (['--config=bar'], 'start', ['--with=baz'])
    """
    index = None
    for arg_i, arg in enumerate(args):
        if not arg.startswith('-'):
            index = arg_i
            break
    if index is None:
        return args, None, []
    return args[:index], args[index], args[index + 1:]


def first():
    """first incoming thing"""


def get_linear_interpolation(p1, p2, x):
    """Given two points in 2D returns y for a given x for y = ax + b

    Parameters
    ----------
    p1,p2 : (x, y)
    x : float

    Returns
    -------
    y : float

    """
    x1, y1 = p1
    x2, y2 = p2
    a = (y2 - y1) / (x2 - x1)
    b = (x2 * y1 - x1 * y2) / (x2 - x1)
    y = a * x + b
    return y


@classmethod
def genprefix(cls, node, ns):
    """
        Generate a prefix.
        @param node: An XML node on which the prefix will be used.
        @type node: L{sax.element.Element}
        @param ns: A namespace needing an unique prefix.
        @type ns: (prefix, uri)
        @return: The I{ns} with a new prefix.
        """
    for n in range(1, 1024):
        p = 'ns%d' % n
        u = node.resolvePrefix(p, default=None)
        if u is None or u == ns[1]:
            return p, ns[1]
    raise Exception('auto prefix, exhausted')


def concat_key_values(dicts, keys, new_key, join_string):
    """
    Concatenate multiple dict fields into a new field
    """
    print('concat keys {}'.format(keys))
    for d in dicts:
        concat = []
        for key in keys:
            if not key in d:
                continue
            concat.append(str(d[key]))
        d[new_key] = join_string.join(concat)
    return dicts


def encode_edd25519_xmr_const(arr):
    """
    Converts Monero based ed25519 constants to int32_t constants

    :param arr:
    :return:
    """
    bits = [26, 25, 26, 25, 26, 25, 26, 25, 26, 25]
    limbs = []
    c = 0
    for i, x in enumerate(arr):
        r = x + c
        if x < 0:
            r = r + (1 << bits[i])
            c = x >> bits[i]
        else:
            c = 0
        limbs.append(r)
    return limbs


@classmethod
def is_overlapping_cds(cls, first, second):
    """
        :param first: first ORF to check for overlap
        :param second: second ORF to check for overlap
        :rtype bool
        """
    if first == second or cls.overlap((first.thick_start, first.thick_end),
        (second.thick_start, second.thick_end)) < 0:
        return False
    return True


def convert_to_fortran_string(string):
    """
    converts some parameter strings to the format for the inpgen
    :param string: some string
    :returns: string in right format (extra "")
    """
    new_string = '"' + string + '"'
    return new_string


@staticmethod
def validate_native(cls, value):
    """Override this method to do your own input validation on the native
        value. This is called after converting the incoming string to the
        native python value."""
    return cls.Attributes.nullable or value is not None


def from_dero(value_in_dero):
    """Convert number in dero to smallest unit"""
    return int(value_in_dero * 10 ** 12)


def set_n_digits(n):
    """
    Sets the number of digits "after the dot" you want to print.
    For example if you call `set_n_digits(3)` and then `print(my_qubit)`
    the result will be something like `'+0.707|0> +0.707|1>'`
    """
    if not isinstance(n, int):
        raise TypeError('The number of digits must be an int')
    if n < 1:
        raise ValueError('Number of digits too low')
    global num_format
    num_format = '{:+.' + str(n) + '}'


def _default_merge(mosaic):
    """The default merge strategy -- just average all 4 pixels"""
    return (mosaic[::2, ::2] / 4.0 + mosaic[1::2, ::2] / 4.0 + mosaic[::2,
        1::2] / 4.0 + mosaic[1::2, 1::2] / 4.0).astype(mosaic.dtype)


def get_rup_wid_west(mag):
    """ Rupture width from WC1994 - See Atkinson (2012) Appendix A"""
    return 10 ** (-1.01 + 0.32 * mag)


def norm_color(image):
    """Normalize colors to be in range from 0.0 to 1.0 instead of from 0 to 255.

    :param image: Numpy image array with colors from 0 to 255

    :return: Numpy image array with colors normalized to floats
    """
    return image / 255


def getCookiePath():
    """Get the path for the cookie
        the parent URL if local_cookie_path is True otherwise /"""


def code_variable_value(real_value, limits):
    """Transform a variable value to a scale between -1 and +1.

    Parameters
    ----------
    real_value : float
        Variable real value.
    limits : Tuple of 2 floats.
        Minimum and maximum real variable values.

    Returns
    -------
    float
        Coded variable value.
    """
    x_max, x_min = max(limits), min(limits)
    return 2 * (real_value - x_min) / (x_max - x_min) - 1


def join_uuids(*uuids):
    """
    DEPRECATED. Only used in Cassandra backend.
    """
    if not uuids or uuids[0] == '':
        uuid_str = b''
    else:
        uuid_str = ''.join(map(lambda x: x.hex, uuids))
    return uuid_str


def energy_res_fermi(e):
    """Fermi-LAT's energy resolution :math:`\\Delta E / E`.

    This is the average of the most optimistic normal and 60deg off-axis values
    from `fig. 18 <https://arxiv.org/abs/0902.1089>`_.
    """
    return 0.075


def write_input_txt(inputs, full_name):
    """
    Writes input parameters to simple textfile.
        - full_name includes the absolute or relative path to the file.
    """
    f = open(full_name, 'w')
    if inputs.fixed_mass:
        mass = inputs.total_mass
        sfr = 'N/A'
    else:
        mass = 'N/A'
        sfr = inputs.SFR
    if inputs.log_scale:
        dt = 'N/A'
        steps = inputs.nsteps
    else:
        dt = inputs.dt
        steps = 'N/A'
    if hasattr(inputs, 'IMF'):
        IMF = inputs.IMF
    else:
        IMF = ''
    lines = ['{:.<35}'.format('Model Name:') + '{0}\n\n'.format(inputs.
        model_name), '{:.<35}'.format('Fixed Mass:') + '{0}\n'.format(
        inputs.fixed_mass), '{:.<35}'.format('    Total Mass:') +
        '{0} M_sun\n'.format(mass), '{:.<35}'.format(
        'Continuous Star Formation:') + '{0}\n'.format(not inputs.
        fixed_mass), '{:.<35}'.format('    SFR:') + '{0} M_sun/yr\n\n'.
        format(sfr), '{:.<35}'.format('IMF:') + '{0}\n'.format(IMF),
        '{:.<35}'.format('IMF Boundaries:') + '{0} M_sun\n'.format(inputs.
        IMF_bound), '{:.<35}'.format('IMF Exponents:') + '{0}\n'.format(
        inputs.IMF_exp), '{:.<35}'.format('    IMF Mass Limits:') +
        '{0}, {1} M_sun\n'.format(inputs.mass_lo, inputs.mass_hi),
        '{:.<35}'.format('    SN Mass Limits:') + """{0}, {1} M_sun

""".
        format(inputs.SN_lo_mass, inputs.SN_hi_mass), '{:.<35}'.format(
        'Evolutionary Track:') + '{0}\n'.format(inputs.evolve_track),
        '{:.<35}'.format('Metallicity') + '{0}\n'.format(inputs.metallicity
        ), '{:.<35}'.format('Wind Model:') + '{0}\n\n'.format(inputs.
        wind_model), '{:.<35}'.format('Time Limits:') + '{0}-{1} yrs\n'.
        format(inputs.start_time, inputs.end_time), '{:.<35}'.format(
        'Log Scale:') + '{0}\n'.format(inputs.log_scale), '{:.<35}'.format(
        '    dt:') + '{0} yrs\n'.format(dt), '{:.<35}'.format('    Nsteps:'
        ) + '{0}\n\n'.format(steps), '{:.<35}'.format('Mass Grid:') +
        '{0}\n'.format(inputs.mass_grid), '{:.<35}'.format('Mass Track:') +
        '{0}\n'.format(inputs.mass_track), '{:.<35}'.format(
        'Output Spectra dt:') + '{0} yrs\n'.format(inputs.spec_dt),
        '{:.<35}'.format('Low-res Spectra Output:') + '{0}\n'.format(inputs
        .low_res_spec), '{:.<35}'.format('High-res Spectra Library:') +
        '{0}\n'.format(inputs.high_res_spec_Z), '{:.<35}'.format(
        'UV spectral library:') + '{0}\n'.format(inputs.UV_line_lib),
        '{:.<35}'.format('RGS microturbulance:') + '{0} km/s\n'.format(
        inputs.RGS_turb_vel), '{:.<35}'.format('RGS Abundance:') +
        'Solar: {0}\n\n'.format(inputs.RGS_abund), '{:*^35}'.format(
        'Output') + '\n\n', '{:.<35}'.format('QUANTA:') + '{0}\n'.format(
        inputs.outputs['QUANTA']), '{:.<35}'.format('SNR:') + '{0}\n'.
        format(inputs.outputs['SNR']), '{:.<35}'.format('HRD:') + '{0}\n'.
        format(inputs.outputs['HRD']), '{:.<35}'.format('POWER:') + '{0}\n'
        .format(inputs.outputs['POWER']), '{:.<35}'.format('SP:') + '{0}\n'
        .format(inputs.outputs['SP']), '{:.<35}'.format('YIELDS:') +
        '{0}\n'.format(inputs.outputs['YIELDS']), '{:.<35}'.format(
        'SPECTRUM:') + '{0}\n'.format(inputs.outputs['SPECTRUM']),
        '{:.<35}'.format('LINE:') + '{0}\n'.format(inputs.outputs['LINE']),
        '{:.<35}'.format('COLOR:') + '{0}\n'.format(inputs.outputs['COLOR']
        ), '{:.<35}'.format('WIDTH:') + '{0}\n'.format(inputs.outputs[
        'WIDTH']), '{:.<35}'.format('FEATURES:') + '{0}\n'.format(inputs.
        outputs['FEATURES']), '{:.<35}'.format('OVI:') + '{0}\n'.format(
        inputs.outputs['OVI']), '{:.<35}'.format('HIRES:') + '{0}\n'.format
        (inputs.outputs['HIRES']), '{:.<35}'.format('WRLINES:') + '{0}\n'.
        format(inputs.outputs['WRLINES']), '{:.<35}'.format('IFASPEC:') +
        '{0}\n'.format(inputs.outputs['IFASPEC'])]
    f.writelines(lines)
    f.close()


def delete_sql_injection_match_set(SqlInjectionMatchSetId=None, ChangeToken
    =None):
    """
    Permanently deletes a  SqlInjectionMatchSet . You can't delete a SqlInjectionMatchSet if it's still used in any Rules or if it still contains any  SqlInjectionMatchTuple objects.
    If you just want to remove a SqlInjectionMatchSet from a Rule , use  UpdateRule .
    To permanently delete a SqlInjectionMatchSet from AWS WAF, perform the following steps:
    See also: AWS API Documentation

    Examples
    The following example deletes a SQL injection match set  with the ID example1ds3t-46da-4fdb-b8d5-abc321j569j5.
    Expected Output:

    :example: response = client.delete_sql_injection_match_set(
        SqlInjectionMatchSetId='string',
        ChangeToken='string'
    )

    :type SqlInjectionMatchSetId: string
    :param SqlInjectionMatchSetId: [REQUIRED]
            The SqlInjectionMatchSetId of the SqlInjectionMatchSet that you want to delete. SqlInjectionMatchSetId is returned by CreateSqlInjectionMatchSet and by ListSqlInjectionMatchSets .

    :type ChangeToken: string
    :param ChangeToken: [REQUIRED]
            The value returned by the most recent call to GetChangeToken .

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

    :returns:
    SqlInjectionMatchSetId (string) -- [REQUIRED]
    The SqlInjectionMatchSetId of the  SqlInjectionMatchSet that you want to delete. SqlInjectionMatchSetId is returned by  CreateSqlInjectionMatchSet and by  ListSqlInjectionMatchSets .

    ChangeToken (string) -- [REQUIRED]
    The value returned by the most recent call to  GetChangeToken .

    """
    pass


def is_url(url: str) ->bool:
    """Return True if a string is a URL.

    >>> is_url("")
    False
    >>> is_url("  ")
    False
    >>> is_url("http://example.com")
    True
    """
    return url.startswith('http')


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

        :param WebSessionLogInfo val:
        :rtype: AccessMethodLogInfo
        """
    return cls('admin_console', val)


def build_index_l(l, key):
    """Build an index using key for a list of dicts where key is not unique
    """
    our_dict = dict()
    for d in l:
        if key not in d:
            continue
        idx = d[key]
        if idx in our_dict:
            our_dict[idx].append(d)
        else:
            our_dict[idx] = [d]
    return our_dict


def release_range(pool: list, rng: list):
    """Releases given token range and pushes it back into the pool"""
    if rng:
        pool.append(rng)


def extrude_move(CURVE_OT_extrude=None, TRANSFORM_OT_translate=None):
    """Extrude curve and move result

    :param CURVE_OT_extrude: Extrude, Extrude selected control point(s)
    :param TRANSFORM_OT_translate: Translate, Translate (move) selected items
    """
    pass


def clothing_inputs(listinp):
    """ A dummy function the just concatenate the list inputs to the output.

    <unit>
        <output name="outp" type="Str" description="test" />
        <input name="listinp" type="List" content="Str" description="test" />
    </unit>
    """
    outp = ''.join(listinp)
    return outp


def get_config_boolean(config, section, option, default_value):
    """tries to retrieve a boolean value from config or returns the default"""
    try:
        return config.getboolean(section, option)
    except:
        return default_value


@staticmethod
def module_repr(m):
    """Return repr for the module.

        The method is deprecated.  The import machinery does the job itself.

        """
    return '<module {!r} (frozen)>'.format(m.__name__)


def refix(val, p_in='', p_out=''):
    """

    Convert between different SI unit prefixes. Available options are:

    :code:`'T'`   Terra

    :code:`'G'` Giga

    :code:`'M'` Mega

    :code:`'k'` Kilo

    :code:`'m'` Milli

    :code:`'mu'` Micro

    :code:`'n'` Nano

    :code:`'p'` Pico

    Parameters
    ----------
    val: scalar
        The value for which to convert the unit prefix.
    p_in: string, any of the above, optional
        The current prefix of :code:`val`. If :code:`p_in` is undefined,
        :code:`val` has no SI unit prefix.
    p_out: string, any of the above, optional
        The prefix of :code:`val_refix` after the conversion.  If :code:`p_in`
        is undefined, :code:`val_refix` has no SI unit prefix.

    Returns
    -------
    val_refix: scalar
        The value in units of prefix :code:`p_out`.

    """
    prefix = {'p': 10 ** -12, 'n': 10 ** -9, 'mu': 10 ** -6, 'm': 10 ** -3,
        '': 10 ** -0, 'k': 10 ** 3, 'M': 10 ** 6, 'G': 10 ** 9, 'T': 10 ** 12}
    val_refix = val * prefix[p_in] / prefix[p_out]
    return val_refix


def bC_Ca_CO3_HMW84(T, P):
    """c-a: calcium carbonate [HMW84]."""
    b0 = 0.0
    b1 = 0.0
    b2 = 0.0
    C0 = 0
    C1 = 0
    alph1 = 1.4
    alph2 = -9
    omega = -9
    valid = T == 298.15
    return b0, b1, b2, C0, C1, alph1, alph2, omega, valid


@classmethod
def get_real_child_model(cls, data):
    """Returns the real base class specified by the discriminator"""
    discriminator_value = data[cls.json_discriminator_key]
    return cls.discriminator_value_class_map.get(discriminator_value)


@classmethod
def _get_apic_classes(cls):
    """
        Get the APIC classes used by this acitoolkit class.

        :returns: list of strings containing APIC class names
        """
    return ['l2extDomP']


def _items(sobject):
    """
    Extract the I{items} from a suds object much like the
    items() method works on I{dict}.
    @param sobject: A suds object
    @type sobject: L{Object}
    @return: A list of items contained in I{sobject}.
    @rtype: [(key, value),...]
    """
    for item in sobject:
        yield item


def keyListSort(keyList):
    """
    Sort list of keys by their names ignoring the case
    """
    keyList.sort(key=lambda x: x.GetName().lower())


def isoformat(dt):
    """Return iso-formatted timestamp

    Like .isoformat(), but uses Z for UTC instead of +00:00
    """
    return dt.isoformat().replace('+00:00', 'Z')


@classmethod
def from_json(cls, s):
    """ return a DimArray, from a json string

        >>> s = '{"values":[[1.0,2.0,3.0],[4.0,5.0,6.0]],"dims":["a","b"],"labels":[[0,1],[10,11,12]],"shape":[2,3],"ndim":2,"meta":{}}'
        >>> DimArray.from_json(s)
        dimarray: 6 non-null elements (0 null)
        0 / a (2): 0 to 1
        1 / b (3): 10 to 12
        array([[1., 2., 3.],
               [4., 5., 6.]])
        """
    import json
    jsondict = json.loads(s)
    return cls.from_jsondict(jsondict)


def set_trace():
    """Pdb using original stdin and stdout.

    When debugging blackbox tests, sys.stdin and sys.stdout are captured for
    test purposes and cannot be used for interactive debugging. This class uses
    the origianl stdin/stdout to allow such use.

    Instead of doing:

       import pdb; pdb.set_trace()

    you can do:

       from breezy import debug; debug.set_trace()
    """
    import pdb
    import sys
    pdb.Pdb(stdin=sys.__stdin__, stdout=sys.__stdout__).set_trace(sys.
        _getframe().f_back)


@staticmethod
def connect_message_attribute(source_node, target_node, message_attribute):
    """
        Connects the message attribute of the input_node into a custom message attribute on target_node
        :param source_node: str, name of a node
        :param target_node: str, name of a node
        :param message_attribute: str, name of the message attribute to create and connect into. If already exists,
        just connect
        """
    raise NotImplementedError(
        'abstract DCC function connect_message_attribute() not implemented!')


def message_warning(msg, *a, **kwargs):
    """Ignore everything except the message."""
    return str(msg) + '\n'


def clear_render_border():
    """Clear the boundaries of the border render and disable border render

    """
    pass


def _get_best_indexes(logits, n_best_size):
    """Get the n-best logits from a list."""
    index_and_score = sorted(enumerate(logits), key=lambda x: x[1], reverse
        =True)
    best_indexes = []
    for i in range(len(index_and_score)):
        if i >= n_best_size:
            break
        best_indexes.append(index_and_score[i][0])
    return best_indexes


def sparse_table_function(*, index, data) ->callable:
    """
	The very simplest Python-ish "sparse matrix", and plenty fast on modern hardware, for the
	size of tables this module will probably ever see, is an ordinary Python dictionary from
	<row,column> tuples to significant table entries. There are better ways if you program
	closer to the bare metal, but this serves the purpose.

	This routine unpacks "compressed-sparse-row"-style data into an equivalent Python dictionary,
	then returns a means to query said dictionary according to the expected 2-dimensional interface.
	"""
    hashmap = {}
    for row_id, (Cs, Ds) in enumerate(zip(index, data)):
        if isinstance(Ds, int):
            for column_id in Cs:
                hashmap[row_id, column_id] = Ds
        else:
            for column_id, d in (zip(Cs, Ds) if Cs else enumerate(Ds)):
                hashmap[row_id, column_id] = d
    return lambda R, C: hashmap.get((R, C))


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

        :param PaperExternalViewForbidType val:
        :rtype: EventType
        """
    return cls('paper_external_view_forbid', val)


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


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


def knots_to_kmh(knots: float) ->float:
    """ Convert velocity in knots to km/h

    1 knot (i.e. 1 nm/h or 1 nautical mile per hour) is 1.852 km/h.

    :param knots: velocity in knots
    :returns: velocity in km/h
    """
    return knots * 1.852


def group_membership_v1_timeout(group_state: 'GroupState'):
    """
    v1 host timer associated with group GroupState object has expired
    """
    group_state.group_state_logger.debug(
        'Querier NoMembersPresent: group_membership_v1_timeout')
    return


def quotation(origin, target):
    """Return quotation between two currencies (origin, target)"""


def contains_lower(text: str) ->bool:
    """If text contains lower case characters, return True."""
    for character in text:
        if character.islower():
            return True
    return False


def format_bed_key(key: str) ->str:
    """Clean a bedtools parameter key."""
    return '-' + key.replace('_', '')


def coords_json_to_api_pan(ang_clockwise):
    """converts from robot coordinates to API coordinates."""
    return ang_clockwise


def interleave(seq1, seq2):
    """
    Interleave elements of `seq2` between consecutive elements of `seq1`.

    Example
    -------
    >>> list(interleave([1, 3, 5], [2, 4]))
    [1, 2, 3, 4, 5]
    >>> list(interleave([1, 2, 3, 4], repeat("<")))
    [1, '<', 2, '<', 3, '<', 4]
    """
    iterator1, iterator2 = iter(seq1), iter(seq2)
    try:
        leading = next(iterator1)
    except StopIteration:
        pass
    else:
        for element in iterator1:
            yield leading
            try:
                yield next(iterator2)
            except StopIteration:
                return
            leading = element
        yield leading


def find_sorted_peaks(x):
    """Find peaks, i.e. local maxima, of an array. Interior points are peaks if
    they are greater than both their neighbors, and edge points are peaks if
    they are greater than their only neighbor. In the case of ties, we
    (arbitrarily) choose the first index in the sequence of equal values as the
    peak.
    Returns a list of tuples (i, x[i]) of peak indices i and values x[i],
    sorted in decreasing order by peak value.
    """
    peak_inds = []
    nbins = len(x)
    for i in range(nbins):
        if i == 0 or x[i] > x[i - 1]:
            if i == nbins - 1 or x[i] > x[i + 1]:
                peak_inds.append(i)
            elif x[i] == x[i + 1]:
                for j in range(i + 1, nbins):
                    if x[j] != x[i]:
                        if x[j] < x[i]:
                            peak_inds.append(i)
                        break
                if j == nbins - 1 and x[i] == x[j]:
                    peak_inds.append(i)
    sorted_peak_inds = sorted(peak_inds, key=lambda i: x[i], reverse=True)
    return list(zip(sorted_peak_inds, x[sorted_peak_inds]))


def init_thread(r, f, x, c):
    """
    to initialise multithreaded worker
    """
    global requested_count, found_count, extracted_count, corrupted_count
    requested_count = r
    found_count = f
    extracted_count = x
    corrupted_count = c


@staticmethod
def __percentage_storage_saved(task):
    """
        Calculate the percentage of storage space saved by the compression.
        :param task: information about the task
        :return: percentage of storage space saved
        """
    task_information = task.get_task_information()
    return int((1 - task_information.output_filesize / task_information.
        filesize) * 100)


def calculate_fun(bean, productList, groupnum=1, oldpro_list=[]):
    """
    换购促销的计算方法 hexiaoxia
    :param bean: 一个换购促销对象
    :param productList: 录入所有商品列表对象
    :param groupnum: 当前是哪个倍数进来的倍数，从1开始（例如：某促销可以翻3倍，那么第一次进来传入1，第二次进来传入2，第三进来传入3，……
    :return:
    """
    from pro.utils.linq import linq
    import pro.utils.util as util
    import copy
    n_productList = copy.deepcopy(productList)
    operation_set = bean.operation_set
    three_id = str(bean.prom_type_three).lower()
    target_item = bean.target_item
    purchase_way = 'T'
    if three_id == 'ga1505' or three_id == 'ga1506':
        purchase_way = 'J'
        operation_set = sorted(operation_set, key=lambda x: x.
            purchase_condition)
    else:
        if three_id == 'ga1503' or three_id == 'ga1504':
            purchase_way = 'D'
        operation_set = sorted(operation_set, key=lambda x: x.
            purchase_condition, reverse=True)
    calculate_list = []
    swap_products = []
    operation_set_list = []
    pronum = 0
    give_value = operation_set[0].give_value
    one_item = {}
    one_item['one_multiple'] = False
    for row in operation_set:
        old_pronum = 0
        if pronum >= int(give_value):
            break
        isnew = True
        oneprice = 0
        tamt_receivable = 0
        t_qtty = 0
        rownum = 0
        pro_list = []
        r_item = {}
        r_item['pcond_id'] = row.pcond_id
        if oldpro_list:
            for index, row3 in enumerate(oldpro_list):
                if row3['pcond_id'] == row.pcond_id and len(row3['pro_list']
                    ) < give_value:
                    old_pronum = len(row3['pro_list'])
                    pro_list = row3['pro_list']
                    isnew = False
                    break
        for row1_index, row1 in enumerate(n_productList):
            if pronum >= int(give_value):
                break
            row1pro = linq(row.product_list).where(lambda x: x['ECODE'] ==
                row1.ecode).tolist().copy()
            if not row1pro:
                continue
            row1pro1 = linq(row1.productSeatList).where(lambda x: x.seat ==
                False and x.is_run_other_pro == True).tolist().copy()
            if not row1pro1:
                continue
            for row2_index, row2 in enumerate(row1.productSeatList):
                if pronum < int(give_value):
                    if row2.seat == True or row2.is_run_other_pro == False:
                        continue
                    if target_item == 'amt_retail':
                        tamt_receivable = tamt_receivable + row2.amt_retail
                        new_amtreceivable = row2.amt_retail
                    elif target_item == 'amt_list':
                        tamt_receivable = tamt_receivable + row2.amt_list
                        new_amtreceivable = row2.amt_list
                    else:
                        tamt_receivable = tamt_receivable + row2.amt_receivable
                        new_amtreceivable = row2.amt_receivable
                    t_qtty = t_qtty + row2.qtty
                    row2.amt_receivable = new_amtreceivable
                    if old_pronum >= int(give_value):
                        isnew = True
                        pro_list = []
                        old_pronum = 0
                    pro_list.append(row2)
                    row2.seat = True
                    productList[row1_index].productSeatList[row2_index
                        ].seat = True
                    productList[row1_index].productSeatList[row2_index
                        ].is_run_other_pro = False
                    productList[row1_index].productSeatList[row2_index
                        ].is_run_store_act = False
                    pronum += 1
                    old_pronum += 1
                else:
                    break
        if not pro_list:
            continue
        r_item['pro_list'] = pro_list
        if oldpro_list:
            if isnew:
                oldpro_list.append(r_item)
        else:
            operation_set_list.append(r_item)
    if pronum == int(give_value):
        one_item['one_multiple'] = True
    else:
        one_item['one_multiple'] = False
    one_item['pro_list'
        ] = operation_set_list if not oldpro_list else oldpro_list
    calculate_list.append(one_item)
    if not calculate_list:
        return None
    else:
        return calculate_list


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


@staticmethod
def add(args):
    """
        Add a new coldbrew remote with name and url
        :param args: Namespace containing path, name and url of the new remote
        :return:
        """
    from coldbrew import client
    client.remote_add(args.path, args.name, args.url)


def groups_lines(data):
    """A generator returning lines for a list of groups.

    data is the return value of rpc_groups()."""
    fmt = '{:<14} {:>9} {:>8} {:>8} {:>6} {:>6} {:>8}{:>7} {:>9} {:>7} {:>9}'
    yield fmt.format('Name', 'Sessions', 'Cost', 'Retained', 'Reqs', 'Txs',
        'Subs', 'Recv', 'Recv KB', 'Sent', 'Sent KB')
    for name, session_count, cost, retained_cost, reqs, txs_sent, subs, recv_count, recv_size, send_count, send_size in data:
        yield fmt.format(name, '{:,d}'.format(session_count), '{:,d}'.
            format(int(cost)), '{:,d}'.format(int(retained_cost)), '{:,d}'.
            format(reqs), '{:,d}'.format(txs_sent), '{:,d}'.format(subs),
            '{:,d}'.format(recv_count), '{:,d}'.format(recv_size // 1024),
            '{:,d}'.format(send_count), '{:,d}'.format(send_size // 1024))


def is_unicode_string(val):
    """Return True if `val` is a unicode string, False for a bytes-like
    object."""
    return hasattr(val, 'encode')


def formated_year(year, accuracy):
    """
    This function will create a standard formated year
    """
    if accuracy == 'EXACT':
        return str(year)
    elif accuracy in ['ABOUT', 'BETWEEN']:
        return 'ca ' + str(year)
    elif accuracy == 'AFTER':
        return 'aft. ' + str(year)
    elif accuracy == 'BEFORE':
        return 'bef. ' + str(year)


def get_opencensus_span():
    """Returns the OpenCensusSpan if opencensus is installed else returns None"""
    try:
        from azure.core.tracing.ext.opencensus_span import OpenCensusSpan
        return OpenCensusSpan
    except ImportError:
        return None


def format_heading(level, text):
    """Create a heading of <level> [1, 2 or 3 supported]."""
    underlining = ['=', '-', '~'][level - 1] * len(text)
    return '%s\n%s\n\n' % (text, underlining)


@classmethod
def create_statusfile(cls, statusfile):
    """Creates the status file required by all load balancing workers.

        Parameters
        ----------
        statusfile : str
            Filename of the status file.
        """
    with open(statusfile, 'w') as f:
        f.write('0')
        f.flush()


def evaluate_media_query(query_list, device_media_type):
    """Return the boolean evaluation of `query_list` for the given
    `device_media_type`.

    :attr query_list: a cssutilts.stlysheets.MediaList
    :attr device_media_type: a media type string (for now)

    """
    return 'all' in query_list or device_media_type in query_list


def clint_encode(value):
    """clint puts crashess when value is unicode. so we always encode"""
    return value


def list_clusters(base):
    """Utility function that lists Senlin clusters."""
    res = base.client.list_objs('clusters')
    return res['body']


@classmethod
def getSegmentsList(cls, workOrPart, removeEmptyLists=True):
    """
        Segments a part by its rests (and clefs) and returns a returns a list of lists where
        each sublist is one segment of contiguous notes. NB Uses .recurse() internally.

        >>> testStream = converter.parse("tinyNotation: C4 r D E r r F r G r A B r c")
        >>> segments = analysis.segmentByRests.Segmenter.getSegmentsList(testStream)
        >>> segments
        [[<music21.note.Note C>],
         [<music21.note.Note D>, <music21.note.Note E>],
         [<music21.note.Note F>],
         [<music21.note.Note G>],
         [<music21.note.Note A>, <music21.note.Note B>],
         [<music21.note.Note C>]]
        """
    segments = []
    thisSegment = []
    partNotes = workOrPart.recurse().getElementsByClass(['Note', 'Rest',
        'Clef'])
    for i in range(len(partNotes)):
        n = partNotes[i]
        if 'Note' in n.classes:
            thisSegment.append(n)
            if i == len(partNotes) - 1:
                segments.append(thisSegment)
        if 'Rest' in n.classes or 'Clef' in n.classes:
            segments.append(thisSegment)
            thisSegment = []
            continue
    if removeEmptyLists:
        for segment in segments[::-1]:
            if not segment:
                segments.remove(segment)
    return segments


def struct_decode(schema, stream, endianness='='):
    """
    Decode structured data from a stream, following a schema.

    :param schema:
        a list of two tuples: ````(name, field)``, where ``name`` is a string
        representing the attribute name, and ``field`` is an instance of a
        :py:class:`StructField` sub-class, providing a ``.load()`` method
        to be called on the stream to get the field value.

    :param stream:
        a file-like object, providing a ``.read()`` method, from which data
        will be read.

    :param endianness:
        endianness specifier, as accepted by Python struct module
        (one of ``<>!=``, defaults to ``=``).

    :return:
        a dictionary mapping the field names to decoded data
    """
    decoded = {}
    for name, field in schema:
        decoded[name] = field.load(stream, endianness=endianness)
    return decoded


def dump(obj, fp):
    """Serialize obj to fp (a file-like object) in ARPA format."""
    obj.write(fp)


def subst(table, text):
    """
    Make 1-to-1 string substitutions using a two-column table.

    Given a translation table and a text, perform 1-to-1 string
    substitution on the text, replacing terms in the first column of the
    table with the corresponding terms in the second column. Substitution
    is performed on three forms for each term: the original term, all
    lowercase, and all uppercase.

    """
    for term1, term2 in table:
        text = text.replace(term1, term2)
        text = text.replace(term1.lower(), term2.lower())
        text = text.replace(term1.upper(), term2.upper())
    return text


@classmethod
def get_fbits(cls, beyging):
    """ Get the (cached) fbits for a BIN 'beyging' field """
    fbits = cls._MEANING_CACHE.get(beyging)
    if fbits is None:
        fbits = cls.fbits(beyging)
        cls._MEANING_CACHE[beyging] = fbits
    return fbits


def orange(_start_or_stop, *args):
    """Range for arbitrary objects.

    Parameters
    ----------
    start, stop, step : any
        Arguments like :func:`range`.

    Yields
    ------
    value : any
        The values in the range ``[start, stop)`` with a step of ``step``.

    Notes
    -----
    ``o`` stands for object.
    """
    if not args:
        start = 0
        stop = _start_or_stop
        step = 1
    elif len(args) == 1:
        start = _start_or_stop
        stop = args[0]
        step = 1
    elif len(args) == 2:
        start = _start_or_stop
        stop, step = args
    else:
        raise TypeError(
            f'orange takes from 1 to 3 positional arguments but {len(args) + 1} were given'
            )
    while start < stop:
        yield start
        start += step


@classmethod
def validate_number_field(cls, value, max_value=None, min_value=None, null=True
    ):
    """
        Validate number field value

        :type value: int | float
        :param value: integer value

        :type max_value: int
        :param max_value: max allow number value

        :type min_value: int
        :param min_value: min allow integer value

        :type null: bool
        :param null: is allow None value

        :rtype: dict
        :return: {'is_valid':bool, 'error_msg':str}
        """
    is_valid = True
    error_msg = None
    if null is False and value is None:
        is_valid = False
        error_msg = 'Property value should not be None'
    if value is not None:
        if isinstance(value, int) is False and isinstance(value, float
            ) is False:
            is_valid = False
            error_msg = 'Data type should be <int>'
        if max_value is not None and value > max_value:
            is_valid = False
            error_msg = 'Max allow value: {}'.format(max_value)
        if min_value is not None and value < min_value:
            is_valid = False
            error_msg = 'Min allow value: {}'.format(min_value)
    return {'is_valid': is_valid, 'error_msg': error_msg}


@classmethod
def decode(cls, stream):
    """Factory method. Creates sub-item from binary stream.

        :param stream: binary stream that should be decoded
        :return: new sub-item
        """
    _, reserved, item_length, response_len = cls.header.unpack(stream.read(
        cls.header.size))
    server_response = stream.read(response_len).decode()
    return cls(server_response, reserved)


@staticmethod
def format_sizeof(num, suffix=''):
    """
        Formats a number (greater than unity) with SI Order of Magnitude
        prefixes.

        Parameters
        ----------
        num  : float
            Number ( >= 1) to format.
        suffix  : str, optional
            Post-postfix [default: ''].

        Returns
        -------
        out  : str
            Number with Order of Magnitude SI unit postfix.
        """
    for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']:
        if abs(num) < 999.95:
            if abs(num) < 99.95:
                if abs(num) < 9.995:
                    return '{0:1.2f}'.format(num) + unit + suffix
                return '{0:2.1f}'.format(num) + unit + suffix
            return '{0:3.0f}'.format(num) + unit + suffix
        num /= 1000.0
    return '{0:3.1f}Y'.format(num) + suffix


def void_function(*arg, **kw):
    """A function that accepts any number of parameters and does nothing"""
    pass


def derive_end_activities_from_log(log, activity_key):
    """
    Derive end activities from log

    Parameters
    -----------
    log
        Log object
    activity_key
        Activity key

    Returns
    -----------
    e
        End activities
    """
    e = set()
    for t in log:
        if len(t) > 0:
            if activity_key in t[len(t) - 1]:
                e.add(t[len(t) - 1][activity_key])
    return e


def aggregate_sternberg(data, sub_num, response_type='full'):
    """
    Aggregate data from the Sternberg task.

    Calculates various summary statistics for the Sternberg task for a
    given subject.

    Parameters
    ----------
    data : dataframe
        Pandas dataframe containing a single subjects trial data for the task.
    sub_num : str
        Subject number to which the data file belongs.
    response_type : {'full', 'correct', 'incorrect'}, optional
        Should the summary data be calculated using all trials? Only correct
        trials? Or only incorrect trials? This is not supported in all tasks.

    Returns
    -------
    stats : list
        List containing the calculated data for the subject.
    """
    df = data
    follow_error_rt = df.loc[df.correct.shift() == 0, 'RT'].mean()
    follow_correct_rt = df.loc[df.correct.shift() == 1, 'RT'].mean()
    if response_type == 'correct':
        df = data[data['correct'] == 1]
    elif response_type == 'incorrect':
        df = data[data['correct'] == 0]
    elif response_type == 'full':
        df = data
    grouped_set_size = df.groupby('setSize')
    set_2_rt = grouped_set_size.mean().get_value(2, 'RT')
    set_2_rtsd = grouped_set_size.std().get_value(2, 'RT')
    set_2_rtcov = set_2_rtsd / set_2_rt
    set_2_correct = grouped_set_size.sum().get_value(2, 'correct')
    set_6_rt = grouped_set_size.mean().get_value(6, 'RT')
    set_6_rtsd = grouped_set_size.std().get_value(6, 'RT')
    set_6_rtcov = set_6_rtsd / set_6_rt
    set_6_correct = grouped_set_size.sum().get_value(6, 'correct')
    intercept, slope = set_2_rt, set_6_rt - set_2_rt
    slope_norm = slope / set_2_rt
    return [sub_num, follow_error_rt, follow_correct_rt, set_2_rt, set_6_rt,
        set_2_rtsd, set_6_rtsd, set_2_rtcov, set_6_rtcov, set_2_correct,
        set_6_correct, intercept, slope, slope_norm]


def per_device_batch_size(batch_size, num_gpus):
    """For multi-gpu, batch-size must be a multiple of the number of GPUs.
  Note that this should eventually be handled by DistributionStrategies
  directly. Multi-GPU support is currently experimental, however,
  so doing the work here until that feature is in place.
  Args:
    batch_size: Global batch size to be divided among devices. This should be
      equal to num_gpus times the single-GPU batch_size for multi-gpu training.
    num_gpus: How many GPUs are used with DistributionStrategies.
  Returns:
    Batch size per device.
  Raises:
    ValueError: if batch_size is not divisible by number of devices
  """
    if num_gpus <= 1:
        return batch_size
    remainder = batch_size % num_gpus
    if remainder:
        err = (
            'When running with multiple GPUs, batch size must be a multiple of the number of available GPUs. Found {} GPUs with a batch size of {}; try --batch_size={} instead.'
            .format(num_gpus, batch_size, batch_size - remainder))
        raise ValueError(err)
    return int(batch_size / num_gpus)


def create(fqdn_listname):
    """Create a mailing list with the given name.

        :param fqdn_listname: The fully qualified name of the mailing list,
            e.g. `mylist@example.com`.
        :type fqdn_listname: Unicode
        :return: The newly created `IMailingList`.
        :raise `ListAlreadyExistsError` if the named list already exists.
        """


@classmethod
def new(cls, *args, **kwargs):
    """Return new uninitialized root which can be mounted on dispatch tree before VM initialization."""
    self = object.__new__(cls)
    self.args, self.kwargs = args, kwargs
    return self


def Enum(enum, value, default=None):
    """Get enum value from the provided value looking up in EnumClass.
    If None, default is returned
    """
    if value is None:
        return default
    for pair in enum:
        if pair.value == value:
            return pair
    raise KeyError("Value '{}' not contained in enum type".format(value))


def is_frozen(G):
    """Return True if graph is frozen.

    Parameters
    ----------
    G : graph
      A NetworkX graph

    See Also
    --------
    freeze
    """
    try:
        return G.frozen
    except AttributeError:
        return False


def nextDWord(offset):
    """ Align `offset` to the next 4-byte boundary """
    return offset + 3 >> 2 << 2


def IntVectorProperty(name: str='', description: str='', default: list=(0,
    0, 0), min: int=-2 ** 31, max: int=2 ** 31 - 1, soft_min: int=-2 ** 31,
    soft_max: int=2 ** 31 - 1, step: int=1, options: set={'ANIMATABLE'},
    tags: set={}, subtype: str='NONE', size: int=3, update=None, get=None,
    set=None):
    """Returns a new vector int property definition.

    :param name: Name used in the user interface.
    :type name: str
    :param description: Text used for the tooltip and api documentation.
    :type description: str
    :param default: sequence of ints the length of size.
    :type default: list
    :param min: Hard minimum, trying to assign a value below will silently assign this minimum instead.
    :type min: int
    :param max: Hard maximum, trying to assign a value above will silently assign this maximum instead.
    :type max: int
    :param soft_min: Soft minimum (>= min), user won’t be able to drag the widget below this value in the UI.
    :type soft_min: int
    :param soft_max: Soft maximum (<= max), user won’t be able to drag the widget above this value in the UI.
    :type soft_max: int
    :param step: Step of increment/decrement in UI, in [1, 100], defaults to 1 (WARNING: unused currently!).
    :type step: int
    :param options: Enumerator in [‘HIDDEN’, ‘SKIP_SAVE’, ‘ANIMATABLE’, ‘LIBRARY_EDITABLE’, ‘PROPORTIONAL’,’TEXTEDIT_UPDATE’].
    :type options: set
    :param tags: Enumerator of tags that are defined by parent class.
    :type tags: set
    :param subtype: Enumerator in [‘COLOR’, ‘TRANSLATION’, ‘DIRECTION’, ‘VELOCITY’, ‘ACCELERATION’, ‘MATRIX’, ‘EULER’, ‘QUATERNION’, ‘AXISANGLE’, ‘XYZ’, ‘COLOR_GAMMA’, ‘LAYER’, ‘LAYER_MEMBER’, ‘POWER’, ‘NONE’].
    :type subtype: str
    :param size: Vector dimensions in [1, 32].
    :type size: int
    :param update: Function to be called when this value is modified, This function must take 2 values (self, context) and return None. Warning there are no safety checks to avoid infinite recursion.
    :param get: Function to be called when this value is ‘read’, This function must take 1 value (self) and return the value of the property.
    :param set: Function to be called when this value is ‘written’, This function must take 2 values (self, value) and return None.
    """
    pass


def GetWSAActionOutput(operation):
    """Find wsa:Action attribute, and return value or the default."""
    attr = operation.output.action
    if attr is not None:
        return attr
    targetNamespace = operation.getPortType().getTargetNamespace()
    ptName = operation.getPortType().name
    msgName = operation.output.name
    if not msgName:
        msgName = operation.name + 'Response'
    if targetNamespace.endswith('/'):
        return '%s%s/%s' % (targetNamespace, ptName, msgName)
    return '%s/%s/%s' % (targetNamespace, ptName, msgName)


def _rehydrate_skeleton_class(skeleton_class, class_dict):
    """Put attributes from `class_dict` back on `skeleton_class`.
    See CloudPickler.save_dynamic_class for more info.
    """
    for attrname, attr in class_dict.items():
        setattr(skeleton_class, attrname, attr)
    return skeleton_class


def describe_host_reservations(HostReservationIdSet=None, Filters=None,
    MaxResults=None, NextToken=None):
    """
    Describes Dedicated Host Reservations which are associated with Dedicated Hosts in your account.
    See also: AWS API Documentation

    :example: response = client.describe_host_reservations(
        HostReservationIdSet=[
            'string',
        ],
        Filters=[
            {
                'Name': 'string',
                'Values': [
                    'string',
                ]
            },
        ],
        MaxResults=123,
        NextToken='string'
    )

    :type HostReservationIdSet: list
    :param HostReservationIdSet: One or more host reservation IDs.
            (string) --

    :type Filters: list
    :param Filters: One or more filters.
            instance-family - The instance family (e.g., m4 ).
            payment-option - The payment option (NoUpfront | PartialUpfront | AllUpfront ).
            state - The state of the reservation (payment-pending | payment-failed | active | retired ).
            (dict) --A filter name and value pair that is used to return a more specific list of results. Filters can be used to match a set of resources by various criteria, such as tags, attributes, or IDs.
            Name (string) --The name of the filter. Filter names are case-sensitive.
            Values (list) --One or more filter values. Filter values are case-sensitive.
            (string) --

    :type MaxResults: integer
    :param MaxResults: The maximum number of results to return for the request in a single page. The remaining results can be seen by sending another request with the returned nextToken value. This value can be between 5 and 500; if maxResults is given a larger value than 500, you will receive an error.

    :type NextToken: string
    :param NextToken: The token to use to retrieve the next page of results.

    :rtype: dict
    :return: {
        'HostReservationSet': [
            {
                'HostReservationId': 'string',
                'HostIdSet': [
                    'string',
                ],
                'OfferingId': 'string',
                'InstanceFamily': 'string',
                'PaymentOption': 'AllUpfront'|'PartialUpfront'|'NoUpfront',
                'HourlyPrice': 'string',
                'UpfrontPrice': 'string',
                'CurrencyCode': 'USD',
                'Count': 123,
                'Duration': 123,
                'End': datetime(2015, 1, 1),
                'Start': datetime(2015, 1, 1),
                'State': 'payment-pending'|'payment-failed'|'active'|'retired'
            },
        ],
        'NextToken': 'string'
    }

    :returns:
    (string) --

    """
    pass


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

        :param str val:
        :rtype: DeleteSecondaryEmailResult
        """
    return cls('cannot_remove_primary', val)


def put_share_hashes(sharehashes):
    """
        @param sharehashes=ListOf(TupleOf(int, Hash))
        @return: a Deferred that fires (with None) when the operation completes
        """


def get_URL_scheme_handler(url_scheme):
    """Get handler for given URL scheme."""
    return


def _fast_iter(context, func, config_dict, verbose, *args, **kwargs):
    """ Build XML Tree and clear """
    for event, elem in context:
        func(elem, config_dict, verbose, *args, **kwargs)
        elem.clear()
        for ancestor in elem.xpath('ancestor-or-self::*'):
            while ancestor.getprevious() is not None:
                del ancestor.getparent()[0]
    del context


@classmethod
def create(cls, *args, **kwargs):
    """
        check there each image only has one relationship with product, comment or users
        """
    product_img = cls.product_img
    comment_img = cls.comment_img
    user_img = cls.user_img
    if not cls.onlyonebelongs(product_img, comment_img, user_img):
        raise ValueError('it only allows one belongs entity for saving')
    super().create(*args, **kwargs)


def delete():
    """Delete active scene

    """
    pass


def _determinePickleModule():
    """
    Determine which 'pickle' API module to use.
    """
    try:
        import cPickle
        return cPickle
    except ImportError:
        import pickle
        return pickle


def initiate_job(accountId=None, vaultName=None, jobParameters=None):
    """
    This operation initiates a job of the specified type. In this release, you can initiate a job to retrieve either an archive or a vault inventory (a list of archives in a vault).
    Retrieving data from Amazon Glacier is a two-step process:
    The retrieval request is executed asynchronously. When you initiate a retrieval job, Amazon Glacier creates a job and returns a job ID in the response. When Amazon Glacier completes the job, you can get the job output (archive or inventory data). For information about getting job output, see  GetJobOutput operation.
    The job must complete before you can get its output. To determine when a job is complete, you have the following options:
    If for a specific event, you add both the notification configuration on the vault and also specify an SNS topic in your initiate job request, Amazon Glacier sends both notifications. For more information, see  SetVaultNotifications .
    An AWS account has full permission to perform all operations (actions). However, AWS Identity and Access Management (IAM) users don't have any permissions by default. You must grant them explicit permission to perform specific actions. For more information, see Access Control Using AWS Identity and Access Management (IAM) .
    Amazon Glacier prepares an inventory for each vault periodically, every 24 hours. When you initiate a job for a vault inventory, Amazon Glacier returns the last inventory for the vault. The inventory data you get might be up to a day or two days old. Also, the initiate inventory job might take some time to complete before you can download the vault inventory. So you do not want to retrieve a vault inventory for each vault operation. However, in some scenarios, you might find the vault inventory useful. For example, when you upload an archive, you can provide an archive description but not an archive name. Amazon Glacier provides you a unique archive ID, an opaque string of characters. So, you might maintain your own database that maps archive names to their corresponding Amazon Glacier assigned archive IDs. You might find the vault inventory useful in the event you need to reconcile information in your database with the actual vault inventory.
    You can limit the number of inventory items retrieved by filtering on the archive creation date or by setting a limit.
    You can retrieve inventory items for archives created between StartDate and EndDate by specifying values for these parameters in the InitiateJob request. Archives created on or after the StartDate and before the EndDate will be returned. If you only provide the StartDate without the EndDate , you will retrieve the inventory for all archives created on or after the StartDate . If you only provide the EndDate without the StartDate , you will get back the inventory for all archives created before the EndDate .
    You can limit the number of inventory items returned by setting the Limit parameter in the InitiateJob request. The inventory job output will contain inventory items up to the specified Limit . If there are more inventory items available, the result is paginated. After a job is complete you can use the  DescribeJob operation to get a marker that you use in a subsequent InitiateJob request. The marker will indicate the starting point to retrieve the next set of inventory items. You can page through your entire inventory by repeatedly making InitiateJob requests with the marker from the previous DescribeJob output, until you get a marker from DescribeJob that returns null, indicating that there are no more inventory items available.
    You can use the Limit parameter together with the date range parameters.
    You can initiate an archive retrieval for the whole archive or a range of the archive. In the case of ranged archive retrieval, you specify a byte range to return or the whole archive. The range specified must be megabyte (MB) aligned, that is the range start value must be divisible by 1 MB and range end value plus 1 must be divisible by 1 MB or equal the end of the archive. If the ranged archive retrieval is not megabyte aligned, this operation returns a 400 response. Furthermore, to ensure you get checksum values for data you download using Get Job Output API, the range must be tree hash aligned.
    An AWS account has full permission to perform all operations (actions). However, AWS Identity and Access Management (IAM) users don't have any permissions by default. You must grant them explicit permission to perform specific actions. For more information, see Access Control Using AWS Identity and Access Management (IAM) .
    For conceptual information and the underlying REST API, see Initiate a Job and Downloading a Vault Inventory
    When retrieving an archive, you can specify one of the following options in the Tier field of the request body:
    For more information about expedited and bulk retrievals, see Retrieving Amazon Glacier Archives .
    See also: AWS API Documentation

    Examples
    The example initiates an inventory-retrieval job for the vault named examplevault.
    Expected Output:

    :example: response = client.initiate_job(
        vaultName='string',
        jobParameters={
            'Format': 'string',
            'Type': 'string',
            'ArchiveId': 'string',
            'Description': 'string',
            'SNSTopic': 'string',
            'RetrievalByteRange': 'string',
            'Tier': 'string',
            'InventoryRetrievalParameters': {
                'StartDate': 'string',
                'EndDate': 'string',
                'Limit': 'string',
                'Marker': 'string'
            }
        }
    )

    :type accountId: string
    :param accountId: The AccountId value is the AWS account ID of the account that owns the vault. You can either specify an AWS account ID or optionally a single '- ' (hyphen), in which case Amazon Glacier uses the AWS account ID associated with the credentials used to sign the request. If you use an account ID, do not include any hyphens ('-') in the ID.
            Note: this parameter is set to '-' bydefault if no value is not specified.

    :type vaultName: string
    :param vaultName: [REQUIRED]
            The name of the vault.

    :type jobParameters: dict
    :param jobParameters: Provides options for specifying job information.
            Format (string) --When initiating a job to retrieve a vault inventory, you can optionally add this parameter to your request to specify the output format. If you are initiating an inventory job and do not specify a Format field, JSON is the default format. Valid values are 'CSV' and 'JSON'.
            Type (string) --The job type. You can initiate a job to retrieve an archive or get an inventory of a vault. Valid values are 'archive-retrieval' and 'inventory-retrieval'.
            ArchiveId (string) --The ID of the archive that you want to retrieve. This field is required only if Type is set to archive-retrieval. An error occurs if you specify this request parameter for an inventory retrieval job request.
            Description (string) --The optional description for the job. The description must be less than or equal to 1,024 bytes. The allowable characters are 7-bit ASCII without control codes-specifically, ASCII values 32-126 decimal or 0x20-0x7E hexadecimal.
            SNSTopic (string) --The Amazon SNS topic ARN to which Amazon Glacier sends a notification when the job is completed and the output is ready for you to download. The specified topic publishes the notification to its subscribers. The SNS topic must exist.
            RetrievalByteRange (string) --The byte range to retrieve for an archive retrieval. in the form 'StartByteValue -EndByteValue ' If not specified, the whole archive is retrieved. If specified, the byte range must be megabyte (1024*1024) aligned which means that StartByteValue must be divisible by 1 MB and EndByteValue plus 1 must be divisible by 1 MB or be the end of the archive specified as the archive byte size value minus 1. If RetrievalByteRange is not megabyte aligned, this operation returns a 400 response.
            An error occurs if you specify this field for an inventory retrieval job request.
            Tier (string) --The retrieval option to use for the archive retrieval. Valid values are Expedited , Standard , or Bulk . Standard is the default.
            InventoryRetrievalParameters (dict) --Input parameters used for range inventory retrieval.
            StartDate (string) --The start of the date range in UTC for vault inventory retrieval that includes archives created on or after this date. This value should be a string in the ISO 8601 date format, for example 2013-03-20T17:03:43Z .
            EndDate (string) --The end of the date range in UTC for vault inventory retrieval that includes archives created before this date. This value should be a string in the ISO 8601 date format, for example 2013-03-20T17:03:43Z .
            Limit (string) --Specifies the maximum number of inventory items returned per vault inventory retrieval request. Valid values are greater than or equal to 1.
            Marker (string) --An opaque string that represents where to continue pagination of the vault inventory retrieval results. You use the marker in a new InitiateJob request to obtain additional inventory items. If there are no more inventory items, this value is null .

    :rtype: dict
    :return: {
        'location': 'string',
        'jobId': 'string'
    }

    :returns:
    After the job completes, download the bytes.

    """
    pass


def intden(mean, area):
    """
        intden: integrated density: mean*area
    """
    return mean * area


@classmethod
def write_bin(cls, context: str) ->'IoTransferEventArgs':
    """Creates new IoTransferEventArgs of read binary data

		:param context: SCPI command. It is truncated to maximum of 100 characters.
		:return: IoTransferEventArgs object of a write binary data operation."""
    obj = cls(False, False, None, context.rstrip())
    obj.binary = True
    return obj


def glListBase(base: int):
    """Set the display-list base for glCallLists

    :param base: Specifies an integer offset that will be added to glCallLists offsets to generate display-list names. The initial value is 0.
    :type base: int
    """
    pass


@staticmethod
def get_cooling_status(root):
    """Get the active cooling status."""
    log_type = 'cooling_state'
    locator = ("appliance[type='heater_central']/logs/point_log[type='" +
        log_type + "']/period/measurement")
    if root.find(locator) is not None:
        return root.find(locator).text == 'on'
    return None


def get_disk(vm):
    """Return the hard drive for *vm*."""
    for drive in vm.get('hardDrives', []):
        if drive['type'] == 'DISK':
            return drive
    raise RuntimeError('VM {} does not have a DISK'.format(vm['name']))


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 glClearStencil(s: int):
    """Specify the clear value for the stencil buffer

    :param s: Specifies the index used when the stencil buffer is cleared. The initial value is 0.
    :type s: int
    """
    pass


def setMedfile(medfile_value):
    """ Copy medfile to a variable that is global for this file.

    Parameters
    ----------
    medfile_value : string
        name of output file for masked median image

    """
    global medfile
    medfile = medfile_value


def pagecontext(page):
    """After a page is identified, corresponding context information must
        be gathered. Context can be saved in JSON files that have one-to-one
        mapping with content-pages, and/or it can be supplied by the content
        itself (many markups, like rst, markdown, allow authors to add
        meta-data in their document). Refer to corresponding layout-plugin to
        know how pages are idenfitied from source layout.

        Returns back dictionary of ``context`` attributes.
        """


def get_dim_from_spin(spin):
    """ Get the dimension of the density matrix from the spin number written as a string."""
    if spin == '3/2':
        return 4
    elif spin == '5/2':
        return 6
    elif spin == '7/2':
        return 8
    elif spin == '9/2':
        return 10


@classmethod
def get_cpu_mhz(mcs):
    """The getter method for the CPU clock.

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

        """
    arm_src_pll_idx = mcs.ARM_CLK_CTRL[mcs.ARM_CLK_SRC_FIELD]
    arm_clk_odiv = mcs.ARM_CLK_CTRL[mcs.ARM_CLK_ODIV_FIELD]
    src_pll_reg = mcs.ARM_SRC_PLL_CTRLS[arm_src_pll_idx]
    return round(mcs.get_pll_mhz(src_pll_reg) / arm_clk_odiv, 6)


def _parse_arguments(*args):
    """Because I'm not particularly Pythonic."""
    formula = None
    if len(args) == 1:
        date = args[0]
    elif len(args) == 2:
        date, formula = args
    else:
        date = args
    return date, formula


def offset_to_column_line(text, offset):
    """Convert an offset in a file to (row, column) coordinates"""
    if offset > len(text):
        return False
    lines = text.split('\n')
    row = 0
    column = offset
    for line_number in range(0, len(lines)):
        line_length = len(lines[line_number])
        if column < line_length:
            row = line_number
            break
        column -= line_length + 1
    return row + 1, column + 1


def remove_ticket(ticket):
    """ Remove a ticket for the current user. Upon success return True """


@classmethod
def user_exists(cls, *args, **kwargs):
    """
        Return True/False if a User instance exists with the given arguments.
        Arguments are directly passed to filter() manager method.
        """
    if 'username' in kwargs:
        kwargs[cls.username_field()] = kwargs.pop('username')
    return cls.user_model().objects.filter(*args, **kwargs).count() > 0


def template_url(url_template: str, state_machine_name: str, label: str) ->str:
    """
    Templates a URL for an external service.

    Adds the label and state machine to a url that contains placeholders in the
    format `<label>` or '<state_machine>'.
    """
    return url_template.replace('<label>', label).replace('<state_machine>',
        state_machine_name)


@staticmethod
def visit_Index(_):
    """ Index are not part of return type dependency information. """
    assert False


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

        :param PaperChangePolicyDetails val:
        :rtype: EventDetails
        """
    return cls('paper_change_policy_details', val)


@classmethod
def convertList(class_, l):
    """Every item being a dict in p_l is converted to an object"""
    i = len(l) - 1
    while i >= 0:
        l[i] = class_.convertValue(l[i])
        i -= 1


def get_active_names(pageToken=None):
    """
    Returns the names of all active (not deleted) resources.
    See also: AWS API Documentation

    :example: response = client.get_active_names(
        pageToken='string'
    )

    :type pageToken: string
    :param pageToken: A token used for paginating results from your get active names request.

    :rtype: dict
    :return: {
        'activeNames': [
            'string',
        ],
        'nextPageToken': 'string'
    }

    """
    pass


@classmethod
def get_location_repr_from(cls, key):
    """
        Returns the location representation from the key
        """
    return key[0].rec_name


def evaluator_options_from_eval_config(eval_config):
    """Produces a dictionary of evaluation options for each eval metric.

  Args:
    eval_config: An `eval_pb2.EvalConfig`.

  Returns:
    evaluator_options: A dictionary of metric names (see
      EVAL_METRICS_CLASS_DICT) to `DetectionEvaluator` initialization
      keyword arguments. For example:
      evalator_options = {
        'coco_detection_metrics': {'include_metrics_per_category': True}
      }
  """
    eval_metric_fn_keys = eval_config.metrics_set
    evaluator_options = {}
    for eval_metric_fn_key in eval_metric_fn_keys:
        if eval_metric_fn_key in ('coco_detection_metrics', 'coco_mask_metrics'
            ):
            evaluator_options[eval_metric_fn_key] = {
                'include_metrics_per_category': eval_config.
                include_metrics_per_category}
    return evaluator_options


def RDtext(s):
    """Convert ICC textType to Python string."""
    assert s[0:4] == 'text'
    return s[8:-1]


def get_db(entity):
    """
  Returns the #pony.orm.Database backing the #Entity instance *entity*.
  """
    return entity._database_


def ip_str_to_bin(ip_str):
    """
    转化ip格式，从str转为bin
    支持ipv4/ipv6
    :param ip_str:
    :return: client_ip_num, ipv6
    """
    import socket
    if ':' in ip_str:
        client_ip_num = socket.inet_pton(socket.AF_INET6, ip_str)
        ipv6 = True
    else:
        client_ip_num = socket.inet_pton(socket.AF_INET, ip_str)
        ipv6 = False
    return client_ip_num, ipv6


def convert_gdk_rgba_to_hex(color):
    """
    Converts Gdk.RGBA to hexadecimal value.

    :param color: the Gdk.RGBA object to convert
    :type color: gi.overrides.Gdk.RGBA
    """
    return '#{}{}{}{}'.format(hex(int(255 * color.red)).replace('0x', ''),
        hex(int(255 * color.green)).replace('0x', ''), hex(int(255 * color.
        blue)).replace('0x', ''), hex(int(255 * color.alpha)).replace('0x', '')
        )


def group_remove():
    """Remove the active bone group

    """
    pass


def gray2bin(bits):
    """Converts a gray-encoded binary string into a binary string.

    Parameters
    ----------
    bits : list or tuple of bool
        The gray-encoded binary string as a list of True/False values.
    """
    b = [bits[0]]
    for nextb in bits[1:]:
        b.append(b[-1] ^ nextb)
    return b


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

        :param FileRequestsEmailsEnabledType val:
        :rtype: EventType
        """
    return cls('file_requests_emails_enabled', val)


@classmethod
def from_name(cls, value):
    """Create an instance from a name or return an existing instance.

        New instances are created with :meth:`~ecl.resource.Resource.new`

        :param value: If ``value`` is an instance of this Resource type,
                      it is returned.
                      If ``value`` is a name which an instance of this
                      Resource type can be created with, one is created
                      and returned.

        :rtype: :class:`~ecl.resource.Resource` or the
                appropriate subclass.
        :raises: :exc:`ValueError` if ``value`` is not an instance of
                this Resource type or a valid ``name``.
        """
    return cls._from_attr(cls.name_attribute, value)