def set_buffer(library, session, mask, size):
    """Sets the size for the formatted I/O and/or low-level I/O communication buffer(s).

    Corresponds to viSetBuf function of the VISA library.

    :param library: the visa library wrapped by ctypes.
    :param session: Unique logical identifier to a session.
    :param mask: Specifies the type of buffer. (Constants.READ_BUF, .WRITE_BUF, .IO_IN_BUF, .IO_OUT_BUF)
    :param size: The size to be set for the specified buffer(s).
    :return: return value of the library call.
    :rtype: :class:`pyvisa.constants.StatusCode`
    """
    return library.viSetBuf(session, mask, size)


def bayes(prior, sensitivity, specitivity):
    """Compute Bayes rule over the prior, sensitivity, and specitivity."""
    joint1 = prior * sensitivity
    joint2 = (1.0 - prior) * (1.0 - specitivity)
    normalizer = joint1 + joint2
    return joint1 / normalizer


def cube(target, pore_diameter='pore.diameter'):
    """
    Calculate pore volume from diameter assuming a cubic pore body

    Parameters
    ----------
    target : OpenPNM Object
        The object which this model is associated with. This controls
        the length of the calculated array, and also provides access to other
        necessary geometric properties.

    pore_diameter : string
        The dictionary key of the pore diameter values

    Returns
    -------
    value : NumPy ndarray
        Array containing pore volume values.

    """
    return target[pore_diameter] ** 3


@staticmethod
def to_fahrenheit(romer):
    """ Convert romer to fahrenheit """
    return (romer - 7.5) * 24 / 7 + 32


def check_permutation(permutation):
    """
    Check permutation sanity
    :param permutation:
    :return:
    """
    for n in range(len(permutation)):
        if n not in permutation:
            raise ValueError('Invalid permutation')


@classmethod
def _json_param(cls, name, p, boxtype):
    """
        Return the parameter mode string and None if parameter unsupported.
        """
    mode = boxtype.mode(name)
    if mode != 'untyped' and not cls.supported(p):
        return None
    return {'name': name, 'label': boxtype.label(name), 'mode': mode, 'doc':
        cls.param_doc(p), 'value': cls.param_default(p), 'lims': cls.
        param_lims(p), 'step': cls.param_step(p)}


def conv_output_length(input_length, filter_size, stride, pad=0):
    """Helper function to compute the output size of a convolution operation

    This function computes the length along a single axis, which corresponds
    to a 1D convolution. It can also be used for convolutions with higher
    dimensionalities by using it individually for each axis.

    Parameters
    ----------
    input_length : int or None
        The size of the input.

    filter_size : int
        The size of the filter.

    stride : int
        The stride of the convolution operation.

    pad : int, 'full' or 'same' (default: 0)
        By default, the convolution is only computed where the input and the
        filter fully overlap (a valid convolution). When ``stride=1``, this
        yields an output that is smaller than the input by ``filter_size - 1``.
        The `pad` argument allows you to implicitly pad the input with zeros,
        extending the output size.

        A single integer results in symmetric zero-padding of the given size on
        both borders.

        ``'full'`` pads with one less than the filter size on both sides. This
        is equivalent to computing the convolution wherever the input and the
        filter overlap by at least one position.

        ``'same'`` pads with half the filter size on both sides (one less on
        the second side for an even filter size). When ``stride=1``, this
        results in an output size equal to the input size.

    Returns
    -------
    int or None
        The output size corresponding to the given convolution parameters, or
        ``None`` if `input_size` is ``None``.

    Raises
    ------
    ValueError
        When an invalid padding is specified, a `ValueError` is raised.
    """
    if input_length is None:
        return None
    if pad == 'valid':
        output_length = input_length - filter_size + 1
    elif pad == 'full':
        output_length = input_length + filter_size - 1
    elif pad == 'same':
        output_length = input_length
    elif isinstance(pad, int):
        output_length = input_length + 2 * pad - filter_size + 1
    else:
        raise ValueError('Invalid pad: {0}'.format(pad))
    output_length = (output_length + stride - 1) // stride
    return output_length


def best_hits(max_hits, gene):
    """Selects candidates(hits) up to max_hits.
    Candidates have to be in hmm_hits

    returns: tuple with gene name and list with candidates names"""
    candidates = []
    hits = gene.hits()
    counter = 0
    if hits:
        for hit in hits:
            if counter == max_hits:
                break
            counter += 1
            if hit.in_hmm_hits() is True:
                candidates.append(hit)
    return gene.query, candidates


def listCriteriaTypes():
    """List available criteria types as dict
        """


@classmethod
def mget(cls, data):
    """Make a multi get

    data: list

    list: [1, 2, 3] <-- get the document 1,2,3 for the current class

    Check the doc for the different supported options
    https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-multi-get.html

    """
    from elasticsearch.exceptions import TransportError
    from collections import OrderedDict
    formatted_result = OrderedDict()
    conn = cls.get_connection()
    try:
        result = conn.mget(index=cls.get_index_name(), body={'ids': data})
    except TransportError:
        return {'total': 0, cls.get_index_name(): formatted_result}
    for one_doc in result.get('docs'):
        if one_doc.get('_source'):
            if cls.ID_KEY == '_id':
                formatted_result.update({one_doc[cls.ID_KEY]: one_doc[
                    '_source']})
            else:
                formatted_result.update({one_doc['_source'][cls.ID_KEY]:
                    one_doc['_source']})
        else:
            formatted_result.update({one_doc.get('_id'): False})
    return {'total': len(formatted_result), cls.get_index_name():
        formatted_result}


def add_home_zone(event_dict, home_team):
    """
    Determines the zone relative to the home team and add it to event.

    Keep in mind that the 'ev_zone' recorded is the zone relative to the event team. And for blocks the NHL counts
    the ev_team as the blocking team (I like counting the shooting team for blocks). Therefore, when it's the home team
    the zone only gets flipped when it's a block. For away teams it's the opposite. Think about it...

    :param event_dict: dict of event info
    :param home_team: home team

    :return: None
    """
    ev_team = event_dict['Ev_Team']
    ev_zone = event_dict['Ev_Zone']
    event = event_dict['Event']
    if ev_zone == '':
        event_dict['Home_Zone'] = ''
        return
    if (ev_team != home_team and event != 'BLOCK' or ev_team == home_team and
        event == 'BLOCK'):
        if ev_zone == 'Off':
            event_dict['Home_Zone'] = 'Def'
        elif ev_zone == 'Def':
            event_dict['Home_Zone'] = 'Off'
        else:
            event_dict['Home_Zone'] = ev_zone
    else:
        event_dict['Home_Zone'] = ev_zone


def yk_from_phi(phi, c_x, h_y):
    """
    *Return the mass fraction of elements from a fuel aspect ratio and stoechio element coeff.*

    :param phi: the air-fuel aspect ratio
    :type phi: float
    :param c_x: stoechio coeff of Carbone
    :type c_x: float
    :param h_y: stoechio coeff of hydrogene
    :type h_y: float

    """
    y_k = dict()
    mass_molar = {'C': 0.0120107, 'H': 0.00100797, 'O2': 0.0319988, 'N2':
        0.0280134}
    mass_mol_fuel = c_x * mass_molar['C'] + h_y * mass_molar['H']
    coeff_o2 = c_x + h_y / 4
    y_o2_fuel_sto = coeff_o2 * mass_molar['O2'] / mass_mol_fuel
    if phi == 0.0:
        y_k['fuel'] = 0.0
    else:
        y_k['fuel'] = 1.0 / (1.0 + (1.0 + 3.76 * (mass_molar['N2'] /
            mass_molar['O2'])) * (y_o2_fuel_sto / phi))
    y_air = 1 - y_k['fuel']
    y_k['N2'] = y_air / 1.303794
    y_k['O2'] = 0.303794 * y_k['N2']
    return y_k


def translateUpdateModel(database, schema, table, mapDict, valueDict):
    """
    get the sql of UPDATE
    mapDict：Model_feild to  of db_feild
    valueDict:the model_feild Name
    """
    if database is None or schema is None or table is None:
        raise 'interpreter cannot find the db or table'
    if mapDict is None or valueDict is None:
        raise AttributeError('db feild or value not be  none')
    schemaStr = '' if len(schema) <= 0 else f'.{schema}'
    updateStr = f'UPDATE {database}{schemaStr}."{table}"'
    parameters = []
    fields = []
    where = ()
    for k, v in mapDict.items():
        if v.primary_key:
            if k not in valueDict:
                raise 'primary_key not valid'
            if isinstance(valueDict.get(k), int) and valueDict.get(k) <= 0:
                raise 'primary_key not valid'
            where = v.name, valueDict.get(k)
            continue
        if k in valueDict:
            parameters.append(valueDict.get(k))
            fields.append(v.name)
        elif v.default is not None:
            parameters.append(v.default)
            fields.append(v.name)
    if len(parameters) < 0:
        raise 'Update cannot find '
    if len(where) != 2:
        raise 'model not primary_key'
    updateStr = f'{updateStr} \nSET'
    for index, field in enumerate(fields):
        updateStr = f'{updateStr} {field}=${index + 1},'
    updateStr = updateStr.strip(',')
    parameters.append(where[1])
    updateStr = f'{updateStr} \nWHERE {where[0]}=${len(parameters)}'
    return updateStr, parameters


def date_to_juliandate(year, month, day):
    """Convert year, month, and day to a Julian Date

    Julian Date is the number of days since noon on January 1, 4713 B.C.
    So the returned date will end in .5 because the date refers to midnight.

    :param year: a Gregorian year (B.C. years are negative).
    :param month: a Gregorian month (1-12).
    :param day: a Gregorian day (1-31).
    :return: the Julian Date for the given year, month, and day.

    """
    year1 = year
    month1 = month
    if year1 < 0:
        year1 += 1
    if month in [1, 2]:
        year1 -= 1
        month1 = month + 12
    if year1 > 1582 or year1 == 1582 and month >= 10 and day >= 15:
        a = int(year1 / 100)
        b = 2 - a + int(a / 4)
    else:
        b = 0
    if year1 < 0:
        c = int(365.25 * year1 - 0.75)
    else:
        c = int(365.25 * year1)
    d = int(30.6001 * (month1 + 1))
    return b + c + d + day + 1720994.5


def copy_reduce(reducer, graph, target, in_data, out_size, in_map, out_map):
    """Copy target data and perform reduce based on graph structure.

    Parameters
    ----------
    reducer : str
        Type of reduction: be 'sum', 'max', 'min', 'mean', 'prod', 'none' (no
        reduction)
    graph : GraphIndex
        The graph
    target : int
        The input target (src, dst, edge)
    in_data : Tensor
        The input data
    out_size : int
        Size of first dimension of output data
    in_map : tuple
        Two input id mapping arrays, one for forward, the other for backward
    out_map : tuple
        Two output id mapping arrays, one for forward, the other for backward

    Returns
    -------
    Tensor
        The result.
    """
    pass


@staticmethod
def _assert_format_exists(file_format, methods):
    """Checks whether the given file format exists in 'methods'.
        """
    try:
        return methods[file_format]
    except KeyError:
        formats = ', '.join(sorted(methods.keys()))
        raise ValueError('Unsupported format: %r, try one of %s' % (
            file_format, formats))


@staticmethod
def calc_error(mz_exp, mz_calc, method='ppm'):
    """method should be ppm or ppb"""
    if method == 'ppm':
        multi_factor = 1000000
    elif method == 'ppb':
        multi_factor = 1000000
    elif method == 'perc':
        multi_factor = 100
    else:
        raise Exception(
            'method needs to be ppm or ppb, you have entered %s' % method)
    if mz_exp:
        return (mz_calc - mz_exp) / mz_calc * multi_factor
    else:
        raise Exception('Please set mz_calc first')


def _em_initial_state_mean(smoothed_state_means):
    """Apply the EM algorithm to parameter `initial_state_mean`

    Maximize expected log likelihood of observations with respect to the
    initial state distribution mean `initial_state_mean`.

    .. math::

        \\mu_0 = \\mathbb{E}[x_0]
    """
    return smoothed_state_means[0]


def from_ascii_hex(text: str) ->int:
    """Converts to an int value from both ASCII and regular hex.
       The format used appears to vary based on whether the command was to
       get an existing value (regular hex) or set a new value (ASCII hex
       mirrored back from original command).

       Regular hex: 0123456789abcdef
       ASCII hex:   0123456789:;<=>?  """
    value = 0
    for index in range(0, len(text)):
        char_ord = ord(text[index:index + 1])
        if char_ord in range(ord('0'), ord('?') + 1):
            digit = char_ord - ord('0')
        elif char_ord in range(ord('a'), ord('f') + 1):
            digit = 10 + (char_ord - ord('a'))
        else:
            raise ValueError('Response contains invalid character.')
        value = value * 16 + digit
    return value


@classmethod
def HasSingleton(cls):
    """
        Do we have any singleton set?

        :rtype: bool
        :returns:
            True if there's a singleton set.
        """
    stack = cls._ObtainStack()
    return len(stack) > 0


def date_for_json(value):
    """
    Return a Python ``date``, and rely on the JSON encoder in
    :class:`LedgerJSONEncoder` to do the appropriate conversion.
    """
    return value


def describe_bundle_tasks(DryRun=None, BundleIds=None, Filters=None):
    """
    Describes one or more of your bundling tasks.
    See also: AWS API Documentation

    :example: response = client.describe_bundle_tasks(
        DryRun=True|False,
        BundleIds=[
            'string',
        ],
        Filters=[
            {
                'Name': 'string',
                'Values': [
                    'string',
                ]
            },
        ]
    )

    :type DryRun: boolean
    :param DryRun: Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation .

    :type BundleIds: list
    :param BundleIds: One or more bundle task IDs.
            Default: Describes all your bundle tasks.
            (string) --

    :type Filters: list
    :param Filters: One or more filters.
            bundle-id - The ID of the bundle task.
            error-code - If the task failed, the error code returned.
            error-message - If the task failed, the error message returned.
            instance-id - The ID of the instance.
            progress - The level of task completion, as a percentage (for example, 20%).
            s3-bucket - The Amazon S3 bucket to store the AMI.
            s3-prefix - The beginning of the AMI name.
            start-time - The time the task started (for example, 2013-09-15T17:15:20.000Z).
            state - The state of the task (pending | waiting-for-shutdown | bundling | storing | cancelling | complete | failed ).
            update-time - The time of the most recent update for the task.
            (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) --

    :rtype: dict
    :return: {
        'BundleTasks': [
            {
                'InstanceId': 'string',
                'BundleId': 'string',
                'State': 'pending'|'waiting-for-shutdown'|'bundling'|'storing'|'cancelling'|'complete'|'failed',
                'StartTime': datetime(2015, 1, 1),
                'UpdateTime': datetime(2015, 1, 1),
                'Storage': {
                    'S3': {
                        'Bucket': 'string',
                        'Prefix': 'string',
                        'AWSAccessKeyId': 'string',
                        'UploadPolicy': b'bytes',
                        'UploadPolicySignature': 'string'
                    }
                },
                'Progress': 'string',
                'BundleTaskError': {
                    'Code': 'string',
                    'Message': 'string'
                }
            },
        ]
    }

    """
    pass


def add_data_to_hash(data, filename, hasher):
    """Contribute `filename`'s data to the `hasher`.

    `hasher` is a `coverage.misc.Hasher` instance to be updated with
    the file's data.  It should only get the results data, not the run
    data.

    """
    if data.has_arcs():
        hasher.update(sorted(data.arcs(filename) or []))
    else:
        hasher.update(sorted(data.lines(filename) or []))
    hasher.update(data.file_tracer(filename))


def packbits_decode(encoded, out=None):
    """Decompress PackBits encoded byte string.

    >>> packbits_decode(b'\\x80\\x80')  # NOP
    b''
    >>> packbits_decode(b'\\x02123')
    b'123'
    >>> packbits_decode(
    ...   b'\\xfe\\xaa\\x02\\x80\\x00\\x2a\\xfd\\xaa\\x03\\x80\\x00\\x2a\\x22\\xf7\\xaa')[:-4]
    b'\\xaa\\xaa\\xaa\\x80\\x00*\\xaa\\xaa\\xaa\\xaa\\x80\\x00*"\\xaa\\xaa\\xaa\\xaa\\xaa\\xaa'

    """
    out = []
    out_extend = out.extend
    i = 0
    try:
        while True:
            n = ord(encoded[i:i + 1]) + 1
            i += 1
            if n > 129:
                out_extend(encoded[i:i + 1] * (258 - n))
                i += 1
            elif n < 129:
                out_extend(encoded[i:i + n])
                i += n
    except TypeError:
        pass
    return bytes(out)


def serialise_colour(colour, context=None):
    """Serialise a Colour value.

    colour -- 'b' or 'w'

    """
    if colour not in ('b', 'w'):
        raise ValueError
    return colour.upper().encode('ascii')


def get_height(pic):
    """Return how many pixels high Picture pic is."""
    return pic.get_height()


def conv_output_length(input_length, filter_size, padding, stride, dilation=1):
    """Determines output length of a convolution given input length.

    # Arguments
        input_length: integer.
        filter_size: integer.
        padding: one of `"same"`, `"valid"`, `"full"`.
        stride: integer.
        dilation: dilation rate, integer.

    # Returns
        The output length (integer).
    """
    if input_length is None:
        return None
    assert padding in {'same', 'valid', 'full', 'causal'}
    dilated_filter_size = (filter_size - 1) * dilation + 1
    if padding == 'same':
        output_length = input_length
    elif padding == 'valid':
        output_length = input_length - dilated_filter_size + 1
    elif padding == 'causal':
        output_length = input_length
    elif padding == 'full':
        output_length = input_length + dilated_filter_size - 1
    return (output_length + stride - 1) // stride


def run(mp_proc, sep='\t'):
    """
    Lazily executes the mapred process and outputs into the console
    :param mp_proc:
    :param sep: optional k and v separator
    :return:
    """
    for k, v in mp_proc:
        print('%s%s%s' % (k, sep, v))


def create_route_long_name(relation, short_name):
    """Create a meaningful route name."""
    if relation.tags.get('from') and relation.tags.get('to'):
        return '{0}-to-{1}'.format(relation.tags.get('from'), relation.tags
            .get('to'))
    name = relation.tags.get('name') or relation.tags.get('alt_name'
        ) or 'OSM Route No. {}'.format(relation.id)
    if short_name and name.startswith(short_name):
        return name[len(short_name):]
    return name


def FpFs(A, Phi, Rp, r):
    """
    Planet-star flux ratio (Equation 11 from Robinson et al. 2016).

    :math:`\\frac{{F}_{p,\\lambda }}{{F}_{{\\rm{s}},\\lambda }}=A{\\rm{\\Phi }}(\\alpha ){\\left(\\displaystyle \\frac{{R}_{{\\rm{p}}}}{r}\\right)}^{2}`

    Parameters
    ----------
    A : float or array-like
        Planetary geometric albedo
    Phi : float
        Planetary phase function
    Rp : float
        Planetary radius [Earth radii]
    r : float
        Planetary orbital semi-major axis [AU]

    Returns
    -------
    FpFs : float or array-like
        Planet-star flux ratio
    """
    Re = 6371000.0
    ds = 149597900000.0
    return A * Phi * (Rp * Re / r / ds) ** 2.0


def _load_class(cls, d):
    """
  Loads additional properties into class `cls`.
  """
    for k, v in d.items():
        if isinstance(k, tuple):
            typ, k = k
            if typ == 'property':
                v = property(*v)
            elif typ == 'staticmethod':
                v = staticmethod(v)
            elif typ == 'classmethod':
                v = classmethod(v)
        setattr(cls, k, v)
    return cls


def check_interface_use_flag(interface_key, account_level):
    """
    根据调用策略，检验能否再次调用（需要重写）

    :param interface_key:
    :param account_level:
    :return:
    """
    return True


def downshift_lon(df):
    """Shift longitudes from (0, 360) -> (-180, 180) convention."""
    pass


@classmethod
def _timedelta_to_seconds(cls, td):
    """
        Converts a 'datetime.timedelta' object `td` into seconds contained in
        the duration.
        Note: We cannot use `timedelta.total_seconds()` because this is not
        supported by Python 2.6.
        """
    return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10 ** 6
        ) / 10 ** 6


def clean_availability(results, server):
    """
    Clean availability for autolookup script.

    :param results: Result dict.
    :type results: dict(str: str)

    :param server: Server, key for result dict.
    :type server: str
    """
    marker = 'PD' if server == 'p' else server.upper()
    rel = results[server.lower()]
    avail = marker if rel != 'SR not in system' and rel is not None else '  '
    return rel, avail


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

        :param TeamMergeRequestExpiredShownToSecondaryTeamDetails val:
        :rtype: EventDetails
        """
    return cls('team_merge_request_expired_shown_to_secondary_team_details',
        val)


def _solve_cuda(A, b, **kwargs):
    """ You could put some other solver here if you're feeling adventurous """
    raise NotImplementedError(
        'Please implement something fast and exciting here!')


def get_longest_version(versions):
    """Calculate the longest version length.

    :param versions: Dictionary of services and their version numbers.
    :return srv_longest, ver_longest: Tuple containing length of longest
                                      service and version.
    :rtype: tuple
    """
    srv_longest = 0
    ver_longest = 0
    for service, version in versions.items():
        srv_longest = len(service) if len(service
            ) > srv_longest else srv_longest
        ver_longest = len(version) if len(version
            ) > ver_longest else ver_longest
    return srv_longest, ver_longest


def structure_function_kolmogorov(separation, r0):
    """
        Compute the Kolmogorov phase structure function

        Parameters:
            separation (ndarray, float): float or array of data representing
                separations between points
            r0 (float): Fried parameter for atmosphere

        Returns:
            ndarray, float: Structure function for separation(s)
    """
    return 6.88 * (separation / r0) ** (5.0 / 3.0)


def unset_pks(obj):
    """
    Unsets the pk field of a model, including its parent's pks during
    multi-table inheritance. Normally we would say

       obj.pk = None
       obj.id = None

    but we can't know for sure what the name of the actually primary key field
    is called.  So we do this to set all the primary keys to None.
    """
    for field in obj._meta.fields:
        if field.primary_key:
            setattr(obj, field.attname, None)


def decodeP(p):
    """
    Translate a parameter into obj format

    Decompose a parameter.
    In this code. It only works for spline obj
    """
    try:
        ret = eval(p)
    except:
        ret = p
    return ret


def T1_tortuosity(lambda_par, vf_intra, vf_extra=None):
    """Tortuosity model for perpendicular extra-axonal diffusivity [1, 2, 3].
    If vf_extra=None, then vf_intra must be a nested volume fraction, in the
    sense that E_bundle = vf_intra * E_intra + (1 - vf_intra) * E_extra, with
    vf_intra + (1 - vf_intra) = 1.
    If both vf_intra and vf_extra are given, then they have be be normalized
    fractions, in the sense that vf_intra + vf_extra <= 1.

    Parameters
    ----------
    lambda_par : float,
        parallel diffusivity.
    vf_intra : float,
        intra-axonal volume fraction [0, 1].
    vf_extra : float, (optional)
        extra-axonal volume fraction [0, 1].

    Returns
    -------
    lambda_perp : float,
        Rotation matrix.

    References
    -------
    .. [1] Bruggeman, Von DAG. "Berechnung verschiedener physikalischer
        Konstanten von heterogenen Substanzen. I. Dielektrizitätskonstanten und
        Leitfähigkeiten der Mischkörper aus isotropen Substanzen." Annalen der
        physik 416.7 (1935): 636-664.
    .. [2] Sen et al. "A self-similar model for sedimentary rocks with
        application to the dielectric constant of fused glass beads."
        Geophysics 46.5 (1981): 781-795.
    .. [3] Szafer et al. "Theoretical model for water diffusion in tissues."
        Magnetic resonance in medicine 33.5 (1995): 697-712.
    """
    if vf_extra is None:
        lambda_perp = (1 - vf_intra) * lambda_par
    else:
        fraction_intra = vf_intra / (vf_intra + vf_extra)
        lambda_perp = (1 - fraction_intra) * lambda_par
    return lambda_perp


def name2id(name):
    """
    convert header to id (check gene #)
    """
    try:
        return '%s_%s' % (name.split()[0], name.split('seq=', 1)[1].split()[0])
    except:
        print('name error:', name)


def tree_path_parent():
    """Go to parent node tree

    """
    pass


def get_blocks(text):
    """Normalize lineends and split on double newline"""
    lines = text.strip().splitlines()
    text = '\n'.join(lines)
    return text.split('\n\n')


@classmethod
def get(cls, id_):
    """Получить один объект по ид.

        Args:
            id_: идентификатор записи для получения

        Returns:
            Возвращает найденный объект
            object

        """
    return cls.query().get(id_)


def theta_CO3_SO4_HMW84(T, P):
    """a-a': carbonate sulfate [HMW84]."""
    theta = 0.02
    valid = T == 298.15
    return theta, valid


@classmethod
def init_3d_from_quaternion(cls, q):
    """
        Convenience constructor for 3D rotations based on quaternion parameters.

        Parameters
        ----------
        q : ``(4,)`` `ndarray`
            The quaternion parameters.

        Returns
        -------
        rotation : :map:`Rotation`
            A 3D rotation transform.
        """
    r = cls.init_identity(n_dims=3)
    return r.from_vector(q)


def set_seed(seed):
    """Setup seed for numpy, random, torch

    Args:
        seed (int): any integer random seed

    """
    import random
    import numpy as np
    import torch
    random.seed(seed)
    torch.manual_seed(seed)
    np.random.seed(seed)


@classmethod
def topic(cls, **kwargs) ->str:
    """Get MQTT topic for this message type."""
    site_id = kwargs.get('site_id', '+')
    return f'rhasspy/nlu/{site_id}/trainSuccess'


def _color_settings_3d(rgb, value, opacity, colored):
    """Return color to color 3D view item.

    Args:
        rgb (list(float)): List of minimum values of each color in rgb ([r, g, b] from 0. to 1.).
        value (float): Value of data (from 0. to 1.).
        opacity (float): Value of opacity(from 0. to 1.).
        colored (bool): If colored or grayscale.

    Returns:
        tuple(float): Color in (r, g, b, a)

    """
    color = (1.0 + 0.6 * value, 1.0 + 0.6 * value, 1.0 + 0.6 * value, 0.5 *
        opacity)
    if colored:
        color = rgb[0] + 0.6 * value, rgb[1] + 0.6 * value, rgb[2
            ] + 0.6 * value, 0.5 * opacity
    return color


def _deref_repr(deref_obj):
    """Uses laurelin constant name representation for deref aliases"""
    try:
        intval = int(deref_obj)
        name = deref_obj.namedValues.getName(intval)
        if name == 'neverDerefAliases':
            return 'DerefAliases.NEVER'
        elif name == 'derefInSearching':
            return 'DerefAliases.SEARCH'
        elif name == 'derefFindingBaseObj':
            return 'DerefAliases.BASE'
        elif name == 'derefAlways':
            return 'DerefAliases.ALWAYS'
        else:
            return '{0}({1})'.format(deref_obj.__class__.__name__, repr(name))
    except Exception:
        return '{0}(<schema object>)'.format(deref_obj.__class__.__name__)


@classmethod
def RegisterDecrypter(cls, decrypter):
    """Registers a decrypter for a specific encryption method.

    Args:
      decrypter (type): decrypter class.

    Raises:
      KeyError: if the corresponding decrypter is already set.
    """
    encryption_method = decrypter.ENCRYPTION_METHOD.lower()
    if encryption_method in cls._decrypters:
        raise KeyError('Decrypter for encryption method: {0:s} already set.'
            .format(decrypter.ENCRYPTION_METHOD))
    cls._decrypters[encryption_method] = decrypter


def _check_response(status_code):
    """Checks the first digit of a status code returned by a GET, and
    assumes/asserts any 2xx/3xx status code is ok.
    """
    first_digit = status_code // 100
    assert first_digit in {2, 3}, 'Bad status code'


def relative_atomic_abundance(counts_edge: float, partial_cross_section_nm2:
    float) ->float:
    """Return the relative atomic concentration.

    partial_cross_section is in nm * nm.

    The return value units are atoms / (nm * nm) * spectrum intensity.
    """
    pass


def set_express_checkout(token='', **kwargs):
    """ SetExpressCheckout """


def boundary_slice(df, start, stop, right_boundary=True, left_boundary=True,
    kind='loc'):
    """Index slice start/stop. Can switch include/exclude boundaries.

    Examples
    --------
    >>> df = pd.DataFrame({'x': [10, 20, 30, 40, 50]}, index=[1, 2, 2, 3, 4])
    >>> boundary_slice(df, 2, None)
        x
    2  20
    2  30
    3  40
    4  50
    >>> boundary_slice(df, 1, 3)
        x
    1  10
    2  20
    2  30
    3  40
    >>> boundary_slice(df, 1, 3, right_boundary=False)
        x
    1  10
    2  20
    2  30

    Empty input DataFrames are returned

    >>> df_empty = pd.DataFrame()
    >>> boundary_slice(df_empty, 1, 3)
    Empty DataFrame
    Columns: []
    Index: []
    """
    if df.empty:
        return df
    if kind == 'loc' and not df.index.is_monotonic:
        if start is not None:
            if left_boundary:
                df = df[df.index >= start]
            else:
                df = df[df.index > start]
        if stop is not None:
            if right_boundary:
                df = df[df.index <= stop]
            else:
                df = df[df.index < stop]
        return df
    else:
        result = getattr(df, kind)[start:stop]
    if not right_boundary and stop is not None:
        right_index = result.index.get_slice_bound(stop, 'left', kind)
        result = result.iloc[:right_index]
    if not left_boundary and start is not None:
        left_index = result.index.get_slice_bound(start, 'right', kind)
        result = result.iloc[left_index:]
    return result


def modified_files(old_tree, new_tree):
    """Return a list of paths in the new tree with modified contents."""
    for f, (op, path), c, v, p, n, (ok, k), e in new_tree.iter_changes(old_tree
        ):
        if c and k == 'file':
            yield str(path)


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


@staticmethod
def _shrink_transverse_emittance(beam, geo_emittance_factor):
    """Account for the transverse geometrical emittance shrinking
        due to acceleration cooling.
        """
    beam.x *= geo_emittance_factor
    beam.xp *= geo_emittance_factor
    beam.y *= geo_emittance_factor
    beam.yp *= geo_emittance_factor


@classmethod
def from_redeemScript(cls, redeemScript):
    """Convert a redeemScript to a P2SH address

        Convenience function: equivalent to P2SHBitcoinAddress.from_scriptPubKey(redeemScript.to_p2sh_scriptPubKey())
        """
    return cls.from_scriptPubKey(redeemScript.to_p2sh_scriptPubKey())


def assert_called_once_with(_mock_self, *args, **kwargs):
    """assert that the mock was called exactly once and that that call was
        with the specified arguments."""
    self = _mock_self
    if not self.call_count == 1:
        msg = "Expected '%s' to be called once. Called %s times.%s" % (self
            ._mock_name or 'mock', self.call_count, self._calls_repr())
        raise AssertionError(msg)
    return self.assert_called_with(*args, **kwargs)


def _is_1d_harray(arr):
    """
    Check whether the array has single dimension like (x, ) or (1, x)
    """
    return len(arr.shape) < 2 or arr.shape[0] == 1


def get_section_dict(section):
    """
        Return a dict of configuration parameters for [section].

        :param section: The config [section] to generate a dict from (using
            that section keys).
        :returns: A dictionary of the config section.
        :rtype: ``dict``

        """


def __new__(mcs, name: str, bases: tuple, attrs: dict):
    """Create the class.

        Injects the 'reducers' attribute, a list of tuple matching token
        sequences to the name of the corresponding reduction methods.
        """
    reducers = []
    for key, value in attrs.items():
        if not hasattr(value, 'reducers'):
            continue
        for reduction in value.reducers:
            reducers.append((reduction, key))
    attrs['reducers'] = reducers
    return super().__new__(mcs, name, bases, attrs)


def add_list_parser(sub_parser):
    """
    Adds a sub-parser for the "list" sub-command to the parser provided.

    :param sub_parser: the parser to add to
    :type sub_parser: <class 'argparse.ArgumentParser'>
    """
    list_parser = sub_parser.add_parser('list', help='List file in remote')
    list_parser.add_argument('remote', help='remote to list')


def format_at(selector):
    """
    Return a formatter for the nodes denoted by selector
    :param selector:
    :return:
    """
    pass


def calculate_bearing_difference(bearing1, bearing2):
    """
    Calculate smallest difference from bearing 1 -> bearing2.
    :param bearing1: start bearing in degrees (0-360)
    :param bearing2: end bearing in degrees (0-360)
    :return: angle between -180 and +180 degrees.
    """
    difference = bearing2 - bearing1
    if -180 < difference < 180:
        return difference
    elif difference <= -180:
        return difference + 360
    elif difference >= 180:
        return difference - 360


def is_numeric(n):
    """
    Tests if an object is interpretable as a number.

    >>> is_numeric('1')
    True
    """
    try:
        float(n)
        return True
    except (ValueError, TypeError):
        return False


def _lsqfun_Dickson1981(massAcid, h, massSample, concAcid, f, alk,
    totalCarbonate, concTotals, eqConstants):
    """D81 equation (16)."""
    return massSample * (alk - totalCarbonate * (1 / (1 + f * h /
        eqConstants['C1']) + 1 / (1 + f * h / eqConstants['C2'])) -
        concTotals['B'] / (1 + f * h / eqConstants['B'])) + (massSample +
        massAcid) * (f * h - eqConstants['w'] / (f * h)) - massAcid * concAcid


def convert_bools_to_string(extra_env):
    """
    Converts all booleans of a dictionary to a string
    """
    for key in extra_env:
        if type(extra_env[key]) == bool:
            extra_env[key] = str(extra_env[key])
    return extra_env


def add(names):
    """ Create controlpanel children by names
        """


def _check_last_word_phrased(phrased_word, word):
    """Check if a word is the last word of a phrased word."""
    words_list = phrased_word.split('_')
    last_word = words_list[-1]
    return word == last_word


def get_number_of_tools(string_file):
    """Gets the total number of tools in a string.  Tools for which quantitiiy can be defined are only counted once.  The top drive is not included

    Parameters
    ----------
    string_file : str
        Full path to an Adams Drill string file

    Returns
    -------
    int
        Number of tools
    """
    with open(string_file, 'r') as fid:
        for line in fid:
            if line.lower().startswith(' stack_order '):
                num = int(line.replace(' ', '').split('=')[-1])
    return num


def getByID(objid):
    """
    We rebuild the object from its id.

    Args:
        objid (str):  object identifier

    Returns:
         Hecuba Object

    """
    """
               TODO
               Args:
                   objid (str):  object identifier
               Returns:
                    (Block| Storageobj)
               """
    from hecuba import log
    from hecuba.IStorage import build_remotely
    from hecuba import config
    import uuid
    query = 'SELECT * FROM hecuba.istorage WHERE storage_id = %s'
    if isinstance(objid, str):
        objid = uuid.UUID(objid)
    results = config.session.execute(query, [objid])
    if not results:
        raise RuntimeError('Object {} not found on hecuba.istorage'.format(
            objid))
    results = results[0]
    log.debug('IStorage API:getByID(%s) of class %s', objid, results.class_name
        )
    return build_remotely(results._asdict())


def zerocopy_to_dlpack(input):
    """Create a dlpack tensor that shares the input memory.

    Parameters
    ----------
    input : Tensor
        The input tensor

    Returns
    -------
    dlpack capsule
        A dlpack capsule that can be used by other framework.
    """
    pass


def hashable(v):
    """Determine whether `v` can be hashed."""
    try:
        hash(v)
    except:
        return False
    return True


def highlight_spelling_errors(token, words, is_correct):
    """
    Wrap bad words in  tags.
    :param token: e.g. SomethingWorng
    :param words: e.g. ['something', 'worng']
    :param is_correct: e.g. [True, False]
    :return: e.g. 'SomethingWorng'
    """
    result = token
    lowercase_result = result.lower()
    index = 0
    for w, i in zip(words, is_correct):
        index = lowercase_result.find(w, index)
        if not i:
            result = ''.join((result[:index], '', result[index:index +
                len(w)], '', result[index + len(w):]))
            lowercase_result = result.lower()
            index += 9
    return result


def get_model(sbml):
    """Get the model of a SBML

    Args:
        sbml (str): SBML file

    Returns:
        xml.etree.ElementTree.Element: SBML model
    """
    model_element = None
    for e in sbml:
        if e.tag[0] == '{':
            uri, tag = e.tag[1:].split('}')
        else:
            tag = e.tag
        if tag == 'model':
            model_element = e
            break
    return model_element


def get_function_handle(method, var):
    """
    Return a function handle to a given calculation method.

    Parameters
    ----------
    method : str
        Identifier of the calculation method to return a handle to.
    var : dict
        Local variables needed in the L method.

    Returns
    -------
    f_handle : function
        Handle to the calculation method defined in this globals scope.

    """
    return globals()['wrap_calculate_using_' + method](var)


def AbortExecution(*args, **kwargs):
    """ Stub Anduin function."""
    print('AbortExecution', args, kwargs)


def process(proc_data):
    """
    Final processing to conform to the schema.

    Parameters:

        proc_data:   (dictionary) raw structured data to process

    Returns:

        List of dictionaries. Structured data with the following schema:

        [
          {
            "state":            string,        # space/~ converted to null
            "remote":           string,
            "refid":            string,
            "st":               integer,
            "t":                string,
            "when":             integer,       # - converted to null
            "poll":             integer,
            "reach":            integer,
            "delay":            float,
            "offset":           float,
            "jitter":           float
          },
        ]

    """
    for entry in proc_data:
        if entry['s'] == '~':
            entry['s'] = None
        entry['state'] = entry.pop('s')
        int_list = ['st', 'when', 'poll', 'reach']
        for key in int_list:
            if key in entry:
                try:
                    entry[key] = int(entry[key])
                except ValueError:
                    entry[key] = None
        float_list = ['delay', 'offset', 'jitter']
        for key in float_list:
            if key in entry:
                try:
                    entry[key] = float(entry[key])
                except ValueError:
                    entry[key] = None
    return proc_data


def restore(token):
    """Get the saved state for a workflow or None if nothing was saved.

        :param token: A unique token identifying this workflow instance.
        :type token: str
        :return: The saved state associated with this name/token pair, or None
            if the pair isn't in the database.
        :rtype: ``IWorkflowState``
        """


def _check_proc_tree_schema(data):
    """Return true if expected process tree columns are present."""
    input_cols = set(data.columns)
    expected_cols = set(['new_process_lc', 'parent_proc_lc', 'source_index',
        'new_process_lc_par', 'source_index_par', 'parent_key', 'IsRoot',
        'IsLeaf', 'IsBranch', 'path', 'parent_index'])
    return expected_cols - input_cols


def dirinfo(obj):
    """return relevant __dir__ info for obj
    """
    return sorted(set(dir(type(obj)) + list(obj.__dict__.keys())))


@staticmethod
def getArgs(args='', fs=','):
    """Processing parameters
            args : parameters
        """
    return args.rsplit(fs) if args else False


def remove(s, i):
    """
    Quick trick to remove an item from a numpy array without
    creating a new object.  Rather than the array shape changing,
    the final value just gets repeated to fill the space.

    ~3.5x faster than numpy.delete
    """
    s[i:-1] = s[i + 1:]


@classmethod
def from_str(cls, string: str) ->'Characters':
    """Returns a new instance with control characters set to given string.
        :param string: The string to set the control characters to
        """
    if string[0:3] == 'UNA':
        string = string[3:9]
    assert len(string) >= 6
    characters = cls()
    characters.component_separator = string[0]
    characters.data_separator = string[1]
    characters.decimal_point = string[2]
    characters.escape_character = string[3]
    characters.reserved_character = string[4]
    characters.segment_terminator = string[5]
    return characters


def _unquote_single_value(quote_char, value):
    """Remove quote characters at the beginning and end if present."""
    if value[0] == quote_char and value[-1] == quote_char:
        return value[1:-1]
    else:
        return value


def ResolveProjectMacros(_path, _project):
    """
	This will iteratively resolve each project macro in a string until there are none left.  However, If either the '{' or '}' characters are desired in the path,
	they'll need to be escaped up to the correct number of times since each resolve pass will remove one set of those characters.
	"""
    while True:
        fixedPath = _path.format(project=_project)
        if fixedPath == _path:
            break
        _path = fixedPath
    return _path


@staticmethod
def _io_map_span_node(source_name, line_number):
    """
        Create an empty span node containing source name and line number as
        attributes.  This is used to attach source info to an AST location,
        and then track that location through AST transformations and
        conversions.
        """
    span_node = {'t': 'Span', 'c': [['', ['codebraid--temp'], [['trace',
        '{0}:{1}'.format(source_name, line_number)]]], []]}
    return span_node


def download_artifact(resource, bucket, key='alppbBuilder/alppb.zip',
    local_path='alppb.zip'):
    """
    Fetches the artifact from Amazon S3 built by alppb .

    Parameters
    ----------
    resource : boto3.resources.factory.s3.ServiceResource
        A boto3 Resource interface for S3.
    bucket : str
        Name of the bucket the artifact exists in.
    key: str
        The S3 key of the artifact to download from the bucket. Defaults to
        "alppbBuilder/alppb.zip".
    local_path: str
        The local path where the artifact will be downloaded. Defaults to the
        current directory alppb is being run from.

    Returns
    -------
    """
    print('Downloading built package(s) to {}...'.format(local_path))
    resource.meta.client.download_file(bucket, key, local_path)
    print('Download complete...')


def xmlSchema(filename, schema=u'', policy=u''):
    """Given a filename relative to the current module, return an
        interface representing the schema contained in that file. If there
        are multiple <schema /> blocks, return the unnamed one, unless
        a name is supplied, in which case the 'name' attribute of the schema
        will be matched to the schema name.

        The policy argument can be used to pick a different parsing policy.
        Policies must be registered as named utilities providing
        ISchemaPolicy.

        Raises a KeyError if the schema cannot be found.
        Raises an IOError if the file cannot be opened.
        """


def stabilize_2d_rotation_select():
    """Select tracks which are used for rotation stabilization

    """
    pass


@classmethod
def fields(cls):
    """
        List of field names for this table.

        Mostly for backwards compatibility in the code (that uses ``fields``).
        """
    fields = set(cls._iter_association_proxies())
    fields.update(cls.__table__.columns.keys())
    return fields - set(getattr(cls, '__private_fields__', ()))


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

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

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


def re_sampling(sel, feature, label):
    """
        Used to over-sampling unbalanced data
        """
    from imblearn.over_sampling import RandomOverSampler
    ros = RandomOverSampler(random_state=0)
    feature_resampled, label_resampled = ros.fit_resample(feature, label)
    from collections import Counter
    print(sorted(Counter(label_resampled).items()))
    return feature_resampled, label_resampled


def filer_actions(context):
    """
    Track the number of times the action field has been rendered on the page,
    so we know which value to use.
    """
    context['action_index'] = context.get('action_index', -1) + 1
    return context


@classmethod
def get_by_short_name(cls, short_name):
    """
        Return :class:`.Measure` instance with given short name by registry
        lookup.

        Parameters
        ----------
        short_name : str
            Short name, identifier in :attr:`measure_dict`.

        Returns
        -------
        measure : :class:`.Measure`
            The instance.
        """
    return cls.measure_dict.get(short_name)


def is_valid_response(response):
    """Returns ``True`` if response ``status_code`` is not an error type,
    returns ``False`` otherwise.

    :param response: :class:~`requests.Response` object to check
    :type response: :class:~`requests.Response`
    :returns: ``True`` if response ``status_code`` is not an error type,
              ``False`` otherwise.
    :rtype bool:
    """
    return 200 <= response.status_code <= 299


def to_sg(plato):
    """
    Convert from plato to specific gravity
    """
    return 1 + plato / (258.6 - plato / 258.2 * 227.1)


def get_marker(item, marker):
    """Get the marker in a way that's supported by the pytest version."""
    try:
        return item.get_marker(marker)
    except AttributeError:
        return item.get_closest_marker(marker)


def get_doc():
    """Get documentation of this resource

    :return: rst string
    :rtype: str
    """
    return """
    The ``actionforcecheck`` contains the checks requested and processed.

    To ask for a forced check for an host/service the client post on this endpoint to create a new
    re-check request that will be managed by the Alignak backend Broker module to build an
    external command notified to the Alignak framework.

    **Note** that the Alignak Web Services module allow to use more external commands.
    """


def pair(arg):
    """Check if `arg` is a pair (two elements tuple or list)."""
    return arg if isinstance(arg, (tuple, list)) and len(arg) == 2 else None


def start(issue):
    """Queues an IENLissue for sendout
        """


def delete_build(BuildId=None):
    """
    Deletes a build. This action permanently deletes the build record and any uploaded build files.
    To delete a build, specify its ID. Deleting a build does not affect the status of any active fleets using the build, but you can no longer create new fleets with the deleted build.
    See also: AWS API Documentation

    :example: response = client.delete_build(
        BuildId='string'
    )

    :type BuildId: string
    :param BuildId: [REQUIRED]
            Unique identifier for a build to delete.

    """
    pass


def get(tree, name):
    """ Return a float value attribute NAME from TREE.
    """
    if name in tree:
        value = tree[name]
    else:
        return float('nan')
    try:
        a = float(value)
    except ValueError:
        a = float('nan')
    return a


def lambd_CO2_Cl_HMW84(T, P):
    """n-a: carbon-dioxide chloride [HMW84]."""
    lambd = -0.005
    valid = T == 298.15
    return lambd, valid


def rand_shuffle(arr):
    """Random shuffle the data in the first dimension of the array.

    The shuffled data is stored in a new array.

    Parameters
    ----------
    arr : Tensor
        The data tensor

    Returns
    -------
    Tensor
        The result tensor
    """
    pass


def addHtmlBreaks(s, isXhtml=True):
    """Replace all returns by
 or
."""
    tag = {(True): '
\n', (False): '
\n'}[isXhtml]
    return s.replace('\n', tag)


def is_log_scale_matrix(matrix):
    """
    This method receives in input a matrix created as
    performance.sel(dataset=X, model=Y) with li and lj as axes.

    In case the first values is at least 2 times bigger than the second values,
    we return True and the matrix will be rescaled in
    plot_rank_confusion_matrix by applying log2; otherwise we return False
    and nothing happens.

    Parameters
    ----------
    matrix : xarray
         created as performance.sel(dataset=X, model=Y) with li and lj as axes

    Returns
    -------
    : bool
        True or False

    """
    flat = matrix.values.flatten()
    flat.sort()
    if flat[-1] / flat[-2] > 2:
        return True
    else:
        return False


def can_paginate(operation_name=None):
    """
    Check if an operation can be paginated.

    :type operation_name: string
    :param operation_name: The operation name. This is the same name
            as the method name on the client. For example, if the
            method name is create_foo, and you'd normally invoke the
            operation as client.create_foo(**kwargs), if the
            create_foo operation can be paginated, you can use the
            call client.get_paginator('create_foo').

    """
    pass


def do_nothing():
    """Simple default callback."""


def get_credential_method_description(session):
    """Provides a helpful message describing the current IAM execution context."""
    profile = ''
    try:
        profile = session.profile_name
    except:
        pass
    try:
        credentials = session.get_credentials()
        return '{} ({}{})'.format(credentials.method, 'profile {} -> '.
            format(profile) if profile != 'default' else '', credentials.
            access_key)
    except:
        return 'error describing session credentials'


@classmethod
def from_filename(cls, filename):
    """Read the struct from a file given its path."""
    if str(filename).endswith('.mat'):
        with open(str(filename), 'rb') as f:
            return cls.from_binary(f)
    with open(str(filename)) as f:
        string = f.read()
    return cls.from_string(string)


def remove_client_id_from_open_id_connect_provider(OpenIDConnectProviderArn
    =None, ClientID=None):
    """
    Removes the specified client ID (also known as audience) from the list of client IDs registered for the specified IAM OpenID Connect (OIDC) provider resource object.
    This action is idempotent; it does not fail or return an error if you try to remove a client ID that does not exist.
    See also: AWS API Documentation

    :example: response = client.remove_client_id_from_open_id_connect_provider(
        OpenIDConnectProviderArn='string',
        ClientID='string'
    )

    :type OpenIDConnectProviderArn: string
    :param OpenIDConnectProviderArn: [REQUIRED]
            The Amazon Resource Name (ARN) of the IAM OIDC provider resource to remove the client ID from. You can get a list of OIDC provider ARNs by using the ListOpenIDConnectProviders action.
            For more information about ARNs, see Amazon Resource Names (ARNs) and AWS Service Namespaces in the AWS General Reference .

    :type ClientID: string
    :param ClientID: [REQUIRED]
            The client ID (also known as audience) to remove from the IAM OIDC provider resource. For more information about client IDs, see CreateOpenIDConnectProvider .

    """
    pass


def EwkrwksT(k, r, s, d1, d2, ExxT, EggT, L):
    """
    Slower vesion of this function
    """
    K = L.shape[-1]
    N = ExxT.shape[0] // K
    D = L.shape[0]
    EgrgsT = EggT[r * N:(r + 1) * N, s * N:(s + 1) * N]
    wkrwksT = 0.0
    for i in range(K):
        for j in range(K):
            wkrwksT += ExxT[i * N:(i + 1) * N, j * N:(j + 1) * N] * L[d1, k, i
                ] * L[d2, k, j]
    return EgrgsT * wkrwksT


def set_g_colorbar_label(colorbar, unit, scale, extra=''):
    """
    Function sets label of the colorbar for gravity acceleration surface function.
    """
    if unit == 'cgs':
        if scale == 'linear':
            colorbar.set_label(extra + ' $g/[cm s^{-2}]$')
        elif scale == 'log':
            colorbar.set_label(extra + ' log(g/[cgs])')
    elif unit == 'SI':
        if scale == 'linear':
            colorbar.set_label(extra + ' $g/[m s^{-2}]$')
        elif scale == 'log':
            colorbar.set_label(extra + ' log(g/[SI])')


def get_position(content):
    """Return the position of a content, or -1 if the content is
        unknown or has no position.
        """


def lib2to3_to_dictnode(tree):
    """
    Transform a lib2to3 structure into a dictnode, as defined by dictnode_to_lxml.
    """
    from lib2to3.pygram import python_grammar
    from lib2to3.pgen2.token import tok_name
    code2name = tok_name.copy()
    del code2name[256]
    code2name.update(python_grammar.number2symbol)
    root = dict(name='ROOT', children=[], attrs={})
    stack = [(tree, root)]
    prev_node = root
    while stack:
        node, parent = stack.pop()
        node_type = code2name.get(node.type, node.type)
        attrs = {}
        if hasattr(node, 'value'):
            node_text = node.value
        else:
            node_text = ''
        if hasattr(node, '_prefix') and node._prefix:
            if prev_node is parent:
                if parent is root:
                    assert node_text == '', node_text
                    node_text = node._prefix
                else:
                    assert parent['text'] == '', parent
                    prev_node['text'] = node._prefix
            else:
                prev_node['tail'] = node._prefix
        dictnode = dict(name=node_type, text=node_text, attrs=attrs,
            children=[], tail='')
        parent['children'].append(dictnode)
        if hasattr(node, 'children'):
            for child in reversed(node.children):
                stack.append((child, dictnode))
        prev_node = dictnode
    prev_node['tail'] = ''
    assert len(root['children']) == 1, root['children']
    return root['children'][0]


def mid(x):
    """
    Midpoints of a given array

    :param x: array with dimension bigger 1
    :return: all the midpoints as numpy array (shape: x.size -1)
    """
    return (x[:-1] + x[1:]) / 2.0


def reshape_Y_T(Y, T):
    """
    Reshapes Y and T when Y.ndim = 2 and/or T.ndim = 1.

    Parameters
    ----------
    Y : array_like, shape (n, ) or (n, 1)
        Outcome for the treatment policy. Must be a vector or single-column matrix.

    T : array_like, shape (n, ) or (n, d_t)
        Treatment policy.

    Returns
    -------
    Y : array_like, shape (n, )
        Flattened outcome for the treatment policy.

    T : array_like, shape (n, 1) or (n, d_t)
        Reshaped treatment policy.

    """
    assert len(Y) == len(T)
    assert Y.ndim <= 2
    if Y.ndim == 2:
        assert Y.shape[1] == 1
        Y = Y.flatten()
    if T.ndim == 1:
        T = T.reshape(-1, 1)
    return Y, T


@staticmethod
def __int(x: str):
    """Convert str to int or None"""
    if x == '':
        return None
    if x.startswith('0x'):
        return int(x, 0)
    return int(x)


def frame_jump():
    """Place the cursor on the midpoint of selected keyframes

    """
    pass


def try_import_dali():
    """Try import NVIDIA DALI at runtime.
    """
    try:
        dali = __import__('nvidia.dali', fromlist=['pipeline', 'ops', 'types'])
        dali.Pipeline = dali.pipeline.Pipeline
    except ImportError:

        class dali:

            class Pipeline:

                def __init__(self):
                    raise NotImplementedError(
                        'DALI not found, please check if you installed it correctly.'
                        )
    return dali


def remove_translation(language):
    """
        remove translation if exists (unregister the translation)
        """


def set_level(request, level):
    """
    Set the minimum level of messages to be recorded, and return ``True`` if
    the level was recorded successfully.

    If set to ``None``, use the default level (see the get_level() function).
    """
    if not hasattr(request, '_messages'):
        return False
    request._messages.level = level
    return True


def evalUnits(unitStr):
    """
    Evaluate a unit string into ([numerators,...], [denominators,...])
    Examples:
        N m/s^2   =>  ([N, m], [s, s])
        A*s / V   =>  ([A, s], [V,])
    """
    pass


def write_class(ID, label, synonyms=None, father=None):
    """
    write a class oin OBO format (inspired by CELDA ontology)
    :param ID: str ID of class
    :param label: str class label
    :param synonyms: list synonyms
    :param father: str ID of class father
    :return: a formated class
    """
    if synonyms != None and father != None:
        all_fathers = ''
        for i in range(len(father)):
            all_fathers = all_fathers + father[i]
        new_class = ['\n', '\n', '\n', '     <!--#' + ID + '-->\n', '\n',
            '     <owl:Class rdf:about="#' + ID + '">\n',
            '         <rdfs:label>' + label + '</rdfs:label>\n',
            """         <rdfs:subClassOf>
""",
            '         <owl:Restriction>\n',
            """             <owl:onProperty rdf:resource="&purl;obo/develops_from"/>
"""
            , '             <owl:someValuesFrom rdf:resource="' +
            all_fathers + '"/>\n', """         </owl:Restriction>
"""]
        for i in range(len(synonyms)):
            new_class.append('         <ru-meta:synonym xml:lang="en">' +
                synonyms[i] + """</ru-meta:synonym>
""")
        new_class.append('        </rdfs:subClassOf>\n')
        new_class.append('     </owl:Class>\n')
    elif synonyms != None and father == None:
        new_class = ['\n', '\n', '\n', '    <!--#' + ID + '-->\n', '\n',
            '    <owl:Class rdf:about="#' + ID + '">\n',
            '        <rdfs:label>' + label + '</rdfs:label>\n']
        for i in range(len(synonyms)):
            new_class.append('        <ru-meta:synonym xml:lang="en">' +
                synonyms[i] + """</ru-meta:synonym>
""")
        new_class.append('    </owl:Class>\n')
    elif synonyms == None and father != None:
        all_fathers = ''
        for i in range(len(father)):
            all_fathers = all_fathers + father[i]
        new_class = ['\n', '\n', '\n', '    <!--#' + ID + '-->\n', '\n',
            '    <owl:Class rdf:about="#' + ID + '">\n',
            '        <rdfs:label>' + label + '</rdfs:label>\n',
            """        <rdfs:subClassOf >
""",
            '        <owl:Restriction>\n',
            """            <owl:onProperty rdf:resource="&purl;obo/develops_from"/>
"""
            , '            <owl:someValuesFrom rdf:resource="' +
            all_fathers + '"/>\n', """        </owl:Restriction>
""",
            '        </rdfs:subClassOf>\n', '    </owl:Class>\n']
    else:
        new_class = ['\n', '\n', '\n', '    <!--#' + ID + '-->\n', '\n',
            '    <owl:Class rdf:about="#' + ID + '">\n',
            '        <rdfs:label>' + label + '</rdfs:label>\n',
            """    </owl:Class>
"""]
    return new_class


def material_slot_select():
    """Select by active material slot

    """
    pass


def call_method(obj, name):
    """
    Call the method *name* on *obj*.
    """
    return getattr(obj, name)()


def _hookitems(ui, _untrusted=False):
    """return all hooks items ready to be sorted"""
    hooks = {}
    for name, cmd in ui.configitems(b'hooks', untrusted=_untrusted):
        if name.startswith(b'priority.') or name.startswith(b'tonative.'):
            continue
        priority = ui.configint(b'hooks', b'priority.%s' % name, 0)
        hooks[name] = -priority, len(hooks), name, cmd
    return hooks


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


def eta_Mc_M(Mc, M):
    """
    Computes the symmetric-mass-ratio from the Chirp Mass and
    total mass
    input: Mc, M
    output: eta
    """
    return (Mc / M) ** (5.0 / 3.0)


def pack_message_other(code, data):
    """
    Method by which other modules messages are (re-)packed

    :param code: the code of the message
    :param data: the data to pack
    :return: dict, code and data
    """
    b_data = bytes(data, 'ascii')
    return {'code': code, 'data': b_data}


def process_task(bot, metadata):
    """Process a generic task"""
    task = metadata['task']
    bot.logger.debug('Processing task %s...' % task.hook.name)
    task.process(bot)


def parse_methyl_bed(path_to_bed):
    """Parse a 9+2 methyl bed file and yield each field
    :param path_to_bed: path to
    """
    with open(path_to_bed, 'r') as fh:
        for line in fh:
            (chromosome, start1, stop1, name, coverage1, strand, start2,
                stop2, color, coverage2, percentage) = line.split()
            yield chromosome, int(start1), int(stop1), name, int(coverage1
                ), strand, int(start2), int(stop2), color, int(coverage2), int(
                percentage)


def _same_filter(node1, node2, candidate_list):
    """
    Filter out candidates which do not adhere the same target composition
    request.
    """
    for candidate in list(candidate_list.keys()):
        n1_trg = ''
        n2_trg = ''
        for src, trg in candidate_list[candidate]:
            if n1_trg == '' and src == node1:
                n1_trg = trg
            elif n1_trg != '' and src == node2:
                if trg != n1_trg:
                    candidate_list.pop(candidate)
                    break
            if n2_trg == '' and src == node2:
                n2_trg = trg
            elif n2_trg != '' and src == node1:
                if trg != n2_trg:
                    candidate_list.pop(candidate)
                    break


@staticmethod
def make_json_pointer(path):
    """Make json pointer path from tuple.

        :param path: tuple with current path
        """
    return '/' + '/'.join(path)


def select_camera(extend: bool=False):
    """Select the active camera

    :param extend: Extend, Extend the selection
    :type extend: bool
    """
    pass


@classmethod
def __parse_location_and_options(cls, loc_opt_str):
    """Given a location string extract the location variable and the remote module options.

        Keyword Args:
            loc_opt_str (str): The string that represents the location
                and remaining option values

        Seperator used is `?`. Each of the options retrieved are then
        turned into a Dict for easy accessibility based on the `&` separator
        """
    split_location_options = loc_opt_str.split('?')
    location = split_location_options[0]
    options = {}
    if len(split_location_options) == 2:
        options = cls.__parse_options_dict(split_location_options[1])
    return [location, options]


@staticmethod
def generate(metadata, file_path):
    """Generates the metadata file."""
    with open(file_path, 'w') as stream:
        stream.write('"""Project metadata."""\n')
        for key, value in metadata.items():
            if isinstance(value, list):
                stream.write(key + ' = [\n')
                for item in value:
                    stream.write('    "' + str(item) + '",\n')
                stream.write(']\n')
            else:
                stream.write(key + ' = "' + value + '"\n')


@classmethod
def username_max_length(cls):
    """Return the max length for username"""
    raise NotImplementedError('Implement in subclass')


def _value_error(cond, str):
    """Throws ValueError if cond is False"""
    if not cond:
        raise ValueError(str)


@classmethod
def worldXY(cls):
    """Construct the world XY plane.

        Returns
        -------
        :class:`compas.geometry.Plane`
            The world XY plane.

        """
    return cls([0, 0, 0], [0, 0, 1])


def mkdummy(name: str, **attrs):
    """Make a placeholder object that uses its own name for its repr"""
    return type(name, (), dict(__repr__=lambda self: '<%s>' % name, **attrs))()


def sameuuid(a: str, b: str) ->bool:
    """Compare two UUIDs."""
    return a and b and a.lower() == b.lower()


ttwidgets//ttwidgets - Copy.pyfile:/ttwidgets - Copy.py:function:unquote/unquote

def unquote(s):
    """Remove any enclosing quotes for S."""
    if isinstance(s, str) and len(s) > 1:
        if s[0] in ('"', "'") and s[-1] == s[0]:
            q = s[0]
            if len(s) >= 6 and s[0:3].count(q) == 3 and s[-3:].count(q) == 3:
                count = 3
            else:
                count = 1
            s = s[count:-count]
    return s


def get_survey_cols(cols, s_cols, prefix):
    """
    Returns the names of the magnitudes in a specific survey

    :param cols:
    :param s_cols:
    :param prefix:
    :return:
    """
    out = []
    prefix_cond = len(prefix) == 0
    for i, c in enumerate(cols):
        for j, s in enumerate(s_cols):
            if s in c and prefix in c and not prefix_cond or prefix_cond and (
                c == s or 'mag' in c or 'Petro' in c):
                out.append(c)
                break
    cols_new = []
    for i, c in enumerate(cols):
        if c not in out:
            cols_new.append(c)
    return cols_new, out


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

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

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


def per_mode_mini(x):
    """Takes Numeric Code and returns String API code

    Input Values: 1:"Totals", 2:"PerGame"

    Used in:

    """
    measure = {(1): 'Totals', (2): 'PerGame'}
    try:
        return measure[x]
    except:
        raise ValueError('Please enter a number between 1 and ' + str(len(
            measure)))


def absorb(user):
    """Merge the given user to ourself.

        All IAddresses linked to `user` are relinked to ourself.  A
        memberships associated with `user` are changed to be memberships
        with ourself.  See `IPreferences.absorb()`.

        The user's `display_name`, `password`, and `is_server_owner` settings
        are absorbed into ours, but only if ours is unset and the given user's
        values are set.

        After being absorbed, the given user and its preferences are
        deleted.

        It is not an error if `user` is ourself, but it is a no-op.

        :param user: The user to merge into ourself.
        :type user: IUser
        :raises TypeError: if `user` is not a user.
        """


def display_right_roi(figure_class, im):
    """Displays the right roi plot

    Parameters
    ==========
    figure_class: (ROI_FigureClass)
        the roi_figureclass object
    im: (nd.array)
        the image array to be displayed

    Returns
    =======
    Nothing - displays the right roi image
    """
    vmin = int(figure_class.vmin_sum_tb.text)
    vmax = int(figure_class.vmax_sum_tb.text)
    figure_class.summed_roi_ax.imshow(im, vmin=vmin, vmax=vmax)


def decode_model(bit_list, accept_model_0=False):
    """Given the bits that encode the model, returns the associated letter.

       It decoding/checksum fails, None is returned. The list of bits must
       be a list of boolean variables.

       The special model 0 is not valid unless `accept_model_0` is set.

    """
    valid = False
    if len(bit_list) == 2 or len(bit_list) == 3:
        valid = True
    elif len(bit_list) >= 4:
        if bit_list[3] == bit_list[0] ^ bit_list[1] ^ (not bit_list[2]):
            valid = True
            for i in range(4, len(bit_list)):
                if bit_list[i] != bit_list[i - 4]:
                    valid = False
                    break
    if valid:
        return chr(65 + (int(bit_list[0]) | int(bit_list[1]) << 1 | int(
            bit_list[2]) << 2))
    elif accept_model_0 and max(bit_list) == False:
        return '0'
    else:
        return None


def copyfileobj(fsrc, fdst, length=16 * 1024):
    """copy data from file-like object fsrc to file-like object fdst"""
    while 1:
        buf = fsrc.read(length)
        if not buf:
            break
        fdst.write(buf)


def mute(unselected: bool=False):
    """Mute (un)selected strips

    :param unselected: Unselected, Mute unselected rather than selected strips
    :type unselected: bool
    """
    pass


def validate_name(name, reserved_names=()):
    """
        Checks the name passed for validity.  If the name is valid and is not
        present in ``reserved_names`` returns a validated name.  Otherwise a
        :exc:`ValueError` will be raised."""


def dbg_msg(options, msg):
    """Print a message if verbose is on."""
    if options['verbose']:
        print(msg)


def get_utilities_for(interface, context=None):
    """Return the utilities that provide an interface

        An iterable of utility name-value pairs is returned.
        """


@classmethod
def supports_device(cls, onnx_device_name):
    """Check whether the requested nGraph backend supports a particular ONNX device.

        During running ONNX backend tests this function is called on each item of ONNX defined
        devices list. Currently this list is hardcoded and contains only two entries:
         ('CPU', 'CUDA'). In order to check whether the requested nGraph backend stored as
         NgraphBackend class variable we have to map its name into ONNX device namespace and then
         verify whether the current version of nGraph library supports it.

        :param onnx_device_name: One of ONNX defined devices.
        :return: True if ONNX device is supported, otherwise False.
        """
    requested_backend_name_mapped_to_onnx_device = cls._get_onnx_device_name(
        cls.backend_name)
    return (onnx_device_name ==
        requested_backend_name_mapped_to_onnx_device and cls.
        supports_ngraph_device(cls.backend_name))


def ema(df, price, col, n):
    """
    Exponential Moving Average (EMA) is a Weighted Moving Average (WMA) that
    gives more weighting to recent price data than Simple Moving Average (SMA)
    does.

    The EMA formula is based on the previous day EMA value. Since we have to
    start our calculation somewhere, the initial value for our first EMA will
    actually be an SMA.

    Parameters:
        df (pd.DataFrame): DataFrame which contain the asset price.
        price (string): the column name of the price of the asset.
        col (string): the column name for the n-day exponential moving average results.
        n (int): the total number of periods.

    Returns:
        df (pd.DataFrame): Dataframe with n-day exponential moving average of the asset calculated.

    Example Strategy:
    Bullish

    AND [Daily SMA(20,Daily Volume) > 40000]
    AND [Daily SMA(60,Daily Close) > 20]

    AND [Daily SMA(150,Daily Close) > 5 days ago Daily SMA(150,Daily Close)]
    AND [Daily EMA(5,Daily Close) > Daily EMA(35,Daily Close)]
    AND [Yesterday's Daily EMA(5,Daily Close) < Yesterday's Daily EMA(35,Daily Close)]
    AND [Daily Volume > Daily SMA(200,Daily Volume)]

    Bearish:

    AND [Daily SMA(20,Daily Volume) > 40000]
    AND [Daily SMA(60,Daily Close) > 20]

    AND [Daily SMA(150,Daily Close) < 5 days ago Daily SMA(150,Daily Close)]
    AND [Daily EMA(5,Daily Close) < Daily EMA(35,Daily Close)]
    AND [Yesterday's Daily EMA(5,Daily Close) > Yesterday's Daily EMA(35,Daily Close)]
    AND [Daily Volume > Daily SMA(200,Daily Volume)]

    Citation: https://school.stockcharts.com/doku.php?id=technical_indicators:moving_averages

    """
    df = df.copy().reset_index(drop=True)
    if df.shape[0] < n:
        df[col] = None
        return df
    k = 2.0 / (n + 1)
    prev_ema = list(df[:n][price].rolling(window=n).mean())[-1]
    df.loc[n - 1, col] = prev_ema
    df.loc[n:, (col)] = 0.0
    emas = [(0.0) for i in range(n)]
    for row in df.loc[n:, ([price])].itertuples(index=False):
        emas.append(k * row[0] + (1 - k) * prev_ema)
        prev_ema = emas[-1]
    df[col] += emas
    return df


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

        :param PaperDocEditCommentType val:
        :rtype: EventType
        """
    return cls('paper_doc_edit_comment', val)


def matches(beginning, strings):
    """
    Returns every string from the given `strings` starting with the given
    `beginning`.
    """
    for string in strings:
        if string.startswith(beginning):
            yield string


def p_range_range(p):
    """range : unit_range
              | operator_range"""
    p[0] = p[1]


def format_time(value: float) ->str:
    """Convert time to nicer format"""
    if value <= 0.005:
        return f'{value * 1000000:.0f}us'
    elif value <= 0.1:
        return f'{value * 1000:.1f}ms'
    elif value > 86400:
        return f'{value / 86400:.2f}day'
    elif value > 1800:
        return f'{value / 3600:.2f}hr'
    elif value > 60:
        return f'{value / 60:.2f}min'
    return f'{value:.2f}s'


def view(A, offset=0):
    """
    Get a view on the diagonal elements of a 2D array.

    This is actually a view (!) on the diagonal of the array, so you can
    in-place adjust the view.

    :param :class:`ndarray` A: 2 dimensional numpy array
    :param int offset: view offset to give back (negative entries allowed)
    :rtype: :class:`ndarray` view of diag(A)

    >>> import numpy as np
    >>> X = np.arange(9).reshape(3,3)
    >>> view(X)
    array([0, 4, 8])
    >>> d = view(X)
    >>> d += 2
    >>> view(X)
    array([ 2,  6, 10])
    >>> view(X, offset=-1)
    array([3, 7])
    >>> subtract(X, 3, offset=-1)
    array([[ 2,  1,  2],
           [ 0,  6,  5],
           [ 6,  4, 10]])
    """
    from numpy.lib.stride_tricks import as_strided
    assert A.ndim == 2, 'only implemented for 2 dimensions'
    assert A.shape[0] == A.shape[1
        ], 'attempting to get the view of non-square matrix?!'
    if offset > 0:
        return as_strided(A[(0), offset:], shape=(A.shape[0] - offset,),
            strides=((A.shape[0] + 1) * A.itemsize,))
    elif offset < 0:
        return as_strided(A[-offset:, (0)], shape=(A.shape[0] + offset,),
            strides=((A.shape[0] + 1) * A.itemsize,))
    else:
        return as_strided(A, shape=(A.shape[0],), strides=((A.shape[0] + 1) *
            A.itemsize,))


def _keep_alive(x, memo):
    """Keeps a reference to the object x in the memo.

    Because we remember objects by their id, we have
    to assure that possibly temporary objects are kept
    alive by referencing them.
    We store a reference at the id of the memo, which should
    normally not be used unless someone tries to deepcopy
    the memo itself...
    """
    try:
        memo[id(memo)].append(x)
    except KeyError:
        memo[id(memo)] = [x]


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

        :param PaperApiCursorError val:
        :rtype: ListDocsCursorError
        """
    return cls('cursor_error', val)


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


def generic_find_fk_constraint_names(table, columns, referenced, insp):
    """Utility to find foreign-key constraint names in alembic migrations"""
    names = set()
    for fk in insp.get_foreign_keys(table):
        if fk['referred_table'] == referenced and set(fk['referred_columns']
            ) == columns:
            names.add(fk['name'])
    return names


def _cmp(a, b):
    """
    Port of Python 2's cmp function.
    """
    return (a > b) - (a < b)


def int_shape(x):
    """Returns the shape of tensor or variable as a tuple of int or None entries.

    # Arguments
        x: Tensor or variable.

    # Returns
        A tuple of integers (or None entries).

    # Examples
    ```python
        >>> from keras import backend as K
        >>> inputs = K.placeholder(shape=(2, 4, 5))
        >>> K.int_shape(inputs)
        (2, 4, 5)
        >>> val = np.array([[1, 2], [3, 4]])
        >>> kvar = K.variable(value=val)
        >>> K.int_shape(kvar)
        (2, 2)
    ```

    {{np_implementation}}
    """
    if hasattr(x, '_keras_shape'):
        return x._keras_shape
    try:
        if isinstance(x.shape, tuple):
            return x.shape
        return tuple(x.shape.as_list())
    except ValueError:
        return None


def psi_Ca_Cl_OH_HMW84(T, P):
    """c-a-a': calcium chloride hydroxide [HMW84]."""
    psi = -0.025
    valid = T == 298.15
    return psi, valid


@classmethod
def run_model(cls, onnx_model, inputs, device='CPU', **kwargs):
    """Prepare and run a computation on an ONNX model."""
    return cls.prepare(onnx_model, device, **kwargs).run(inputs)


def __mul__(L1, L2):
    """Take the dot product of two numeric lists.
		Not using Vector for this because it is limited to three dimensions.
		Lists must have the same number of elements."""
    return sum(map(lambda x, y: x * y, L1, L2))


def print_error_files(errors, max_marks):
    """Print the lines with files that generated errors"""
    fmt_error = '{0:<%d} {1:<10}' % (22 + max_marks)
    permission_error = False
    for filename in errors:
        error = errors[filename]
        if 'Permission denied' in error:
            error_string = 'Permission denied'
            permission_error = True
        else:
            error_string = error
        print(fmt_error.format(error_string, filename))
    return permission_error


def bufferMask(image, radius=1.5, kernelType='square', units='pixels'):
    """ Make a buffer around the masked pixels """
    masked = image.mask().Not()
    buffer = masked.focal_max(radius, kernelType, units)
    return image.updateMask(buffer.Not())


def jaccard(ann1, ann2):
    """
    The Jaccard distance [1] between the boolean volumes as point sets. The
    Jaccard distance is one minus the "intersection over union" score and is a
    value between 0 and 1. Distance 0 indicates perfect overlap
    (intersection/union = 1), while distance 1 indicates no overlap.

    [1]: https://en.wikipedia.org/wiki/Jaccard_index
    """
    A1 = ann1._as_set()
    A2 = ann2._as_set()
    I = len(A1.intersection(A2))
    return 1.0 - I * 1.0 / len(A1.union(A2))


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

        :param TeamMergeRequestReminderShownToPrimaryTeamType val:
        :rtype: EventType
        """
    return cls('team_merge_request_reminder_shown_to_primary_team', val)


@classmethod
def _java_loader_class(cls, clazz):
    """
        Returns the full class name of the Java ML instance.
        """
    return clazz.getJavaPackage()


def syncreq(proxy, handler, *args):
    """Performs a synchronous request on the given proxy object.
    Not intended to be invoked directly.

    :param proxy: the proxy on which to issue the request
    :param handler: the request handler (one of the ``HANDLE_XXX`` members of
                    ``rpyc.protocol.consts``)
    :param args: arguments to the handler

    :raises: any exception raised by the operation will be raised
    :returns: the result of the operation
    """
    conn = object.__getattribute__(proxy, '____conn__')
    return conn.sync_request(handler, proxy, *args)


def _has_governor(node, positions):
    """
    Check if governor exists (is not root)

    Return: bool
    """
    return bool(node[positions['g']])


def build_proc_info(release, config_name, hostname, proc, port):
    """
    Return a dictionary with exhaustive metadata about a proc.  This is saved
    as the proc.yaml file that is given to the runner.
    """
    build = release.build
    app = build.app
    proc_info = {'release_hash': release.hash, 'config_name': config_name,
        'settings': release.config_yaml or {}, 'env': release.env_yaml or {
        }, 'version': build.tag, 'build_md5': build.file_md5, 'build_url':
        build.file.url, 'buildpack_url': build.buildpack_url,
        'buildpack_version': build.buildpack_version, 'app_name': app.name,
        'app_repo_url': app.repo_url, 'app_repo_type': app.repo_type,
        'host': hostname, 'proc_name': proc, 'port': port, 'user': release.
        run_as or 'nobody', 'group': 'nogroup', 'volumes': release.volumes or
        [], 'mem_limit': release.mem_limit, 'memsw_limit': release.memsw_limit}
    if build.os_image is not None:
        proc_info.update({'image_name': build.os_image.name, 'image_url':
            build.os_image.file.url, 'image_md5': build.os_image.file_md5})
    return proc_info


@property
def name(cls):
    """Returns the name of the hasher"""
    return cls.__name__.rstrip('Hasher').lower()


@classmethod
def close(cls, appName):
    """ Closes the process associated with the specified app.

        As a class method, accessible as `App.class(appName)`.
        As an instance method, accessible as `App(appName).close()`.
        """
    return cls(appName).close()


@conf
def find_clang(conf):
    """
	Finds the program clang and executes it to ensure it really is clang
	"""
    cc = conf.find_program('clang', var='CC')
    conf.get_cc_version(cc, clang=True)
    conf.env.CC_NAME = 'clang'


def add_feature(list_1, list_2):
    """
    Adds second input data as features of the first. currently only works with two one-dimensional vectors

    :param list_1: first input of data as list
    :param list_2: second input of data as list
    :return: input data with corresponding feature in second list
    """
    if type(list_1) or type(list_2) is not list:
        list_1 = list(list_1)
        list_2 = list(list_2)
    if type(list_1) and type(list_2) is list:
        assert len(list_1) == len(list_2)
        concatenated_list = []
        i = 0
        while i < len(list_1):
            concatenated_list.append([list_1[i], list_2[i]])
            i += 1
        return concatenated_list


@staticmethod
def format_interval(t):
    """
        Formats a number of seconds as a clock time, [H:]MM:SS

        Parameters
        ----------
        t  : int
            Number of seconds.
        Returns
        -------
        out  : str
            [H:]MM:SS
        """
    mins, s = divmod(int(t), 60)
    h, m = divmod(mins, 60)
    if h:
        return '{0:d}:{1:02d}:{2:02d}'.format(h, m, s)
    else:
        return '{0:02d}:{1:02d}'.format(m, s)


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


def log_db_cmd(log, schema, cmd, args):
    """ Log database command (when tap_db ini option is used). """
    s_args = '()'
    if len(args):
        s_args = '(*{0})'.format(len(args))
    log.debug('{schema}/{cmd}{args}'.format(schema=schema, cmd=cmd, args=
        s_args))


def count_below(values, threshold):
    """Count number of values lying below some threshold"""
    return (values < threshold).sum()


def model_create(module, model_pars=None):
    """
      Create Instance of the model from loaded module
      model_pars : dict params
    """
    if model_pars is None:
        model_pars = module.get_pars()
    model = module.Model(**model_pars)
    return model


def topology_sorted_ids(tree):
    """Determine the topological order of the ids in a tree"""
    file_ids = list(tree)
    file_ids.sort(key=tree.id2path)
    return file_ids


def compute_triangle_circumcenters(X, ei_dot_ei, ei_dot_ej):
    """Computes the circumcenters of all given triangles.
    """
    alpha = ei_dot_ei * ei_dot_ej
    alpha_sum = alpha[0] + alpha[1] + alpha[2]
    beta = alpha / alpha_sum[None]
    a = X * beta[..., None]
    cc = a[0] + a[1] + a[2]
    return cc


@staticmethod
def make_refresh_header(base_header, header, refresh, last_refresh, now):
    """Updates the header with the 'refresh in' message"""
    header.value = base_header + 'refreshing in: ' + str(int(round(
        last_refresh + refresh - now)))


def getIpv4(addr):
    """ Get IPv4 address via parameter addr """
    return '.'.join(map(str, addr))


@staticmethod
def has_change_db_cmd(query):
    """Determines if the statement is a database switch such as 'use' or '\\c'
           Returns (True, DBName) or (False, None)
        """
    if query and isinstance(query, str):
        first_token = query.split()[0]
        if first_token.lower() in ('use', '\\c', '\\connect'):
            return True, query.split()[1].strip('"')
    return False, None


def _raise_exception(exception, exception_message):
    """ This function checks if a exception message is given.
    If there is no exception message, the default behaviour is maintained.
    If there is an exception message, the message is passed to the exception.
    """
    if not exception:
        exception = TimeoutError
    raise exception(exception_message)


def od_to_ms_300(od):
    """Convert an overall difficulty value into milliseconds to hit an object at
    maximum accuracy.

    Parameters
    ----------
    od : float
        The overall difficulty.

    Returns
    -------
    ms : float
        The number of milliseconds to hit an object at maximum accuracy.

    See Also
    --------
    :func:`slider.mod.ms_300_to_od`
    """
    return 79.5 - 6 * od


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

        :param PaperExternalViewDefaultTeamType val:
        :rtype: EventType
        """
    return cls('paper_external_view_default_team', val)


def p_words(p):
    """words : words WHITESPACE WORD
             | WORD"""
    if len(p) == 4:
        p[0] = p[1] + p[2] + p[3]
    elif len(p) == 2:
        p[0] = p[1]
    else:
        raise Exception('unexpected length %s' % len(p))


def is_none_or_int(obj):
    """Check if obj is None or an integer.

    :param obj: Object to check.
    :type obj: object
    :return: True if object is None or an integer.
    :rtype: bool
    """
    return obj is None or isinstance(obj, int) and obj >= 0


@staticmethod
def find_best_akaike(list_of_fits):
    """Return the best fit, based on Akaike information criterion"""
    res = sorted(list_of_fits, key=lambda x: x.aic)
    return res[0]


def draw_tail_navigable(context):
    """
    Draw a normal arrow to indicate association end navigability at
    association tail.
    """
    cr = context.cairo
    cr.line_to(0, 0)
    cr.stroke()
    cr.move_to(15, -6)
    cr.line_to(0, 0)
    cr.line_to(15, 6)


def reset_cache(GatewayARN=None):
    """
    Resets all cache disks that have encountered a error and makes the disks available for reconfiguration as cache storage. If your cache disk encounters a error, the gateway prevents read and write operations on virtual tapes in the gateway. For example, an error can occur when a disk is corrupted or removed from the gateway. When a cache is reset, the gateway loses its cache storage. At this point you can reconfigure the disks as cache disks. This operation is only supported in the cached volume,tape and file gateway architectures.
    See also: AWS API Documentation

    Examples
    Resets all cache disks that have encountered a error and makes the disks available for reconfiguration as cache storage.
    Expected Output:

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

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

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

    """
    pass


def dw_WriteAttributesFile(fname, noseg):
    """
    Generates a Delwaq atributes (*.atr) file.

    input:
    - fname : file name to write to
    - noseg : number of delwaq segments
    """
    line_length = 100
    n_lines = noseg // line_length
    remaining_length = noseg % line_length
    buff = ''
    buff += '         ; DELWAQ_COMPLETE_ATTRIBUTES\n'
    buff += '    2    ; two blocks with input\n'
    buff += '    1    ; number of attributes, they are :\n'
    buff += "    1    ;  '1' is active '0' is no\n"
    buff += '    1    ; data follows in this fil\n'
    buff += '    1    ; all data is given without defaults\n'
    buff += ';    layer:            1\n'
    for iline in range(n_lines):
        buff += ' '.join(['1' for _ in range(line_length)])
        buff += '\n'
    buff += ' '.join(['1' for _ in range(remaining_length)])
    buff += '\n'
    buff += '    1    ; number of attributes, they are :\n'
    buff += "    2    ;  '1' has surface '3' has bottom\n"
    buff += "         ;  '0' has both    '2' has none\n"
    buff += '    1    ; data follows in this file\n'
    buff += '    1    ; all data is given without defaults\n'
    buff += ';    layer:            1\n'
    for iline in range(n_lines):
        buff += ' '.join(['0' for _ in range(line_length)])
        buff += '\n'
    buff += ' '.join(['0' for _ in range(remaining_length)])
    buff += '\n'
    buff += '    0    ; no time dependent attributes\n'
    f = open(fname, 'w')
    f.write(buff)
    f.close()


def checkRegionalColumnTitles(esM, data):
    """
    Necessary if the data columns represent the location-dependent data:
    Check if the columns indices match the location indices of the energy system model.
    """
    if set(data.columns) != esM.locations:
        raise ValueError(
            """Location indices do not match the one of the specified energy system model.
"""
             + 'Data columns: ' + str(set(data.columns)) + '\n' +
            'Energy system model regions: ' + str(esM.locations))


def readwav(filename):
    """Read a WAV file and returns the data and sample rate

    ::

        from spectrum.io import readwav
        readwav()

    """
    from scipy.io.wavfile import read as readwav
    samplerate, signal = readwav(filename)
    return signal, samplerate


@classmethod
def batch_create(cls, session, private_ips):
    """Create the given private ips in batch

        :param session: The session to use for making this request.
        :type session: :class:`~openstack.session.Session`
        :param private_ips: A list of dict defined private ip.

        :returns: A list of the created private ips.
        """
    uri = cls.base_path
    body = {'privateips': private_ips}
    endpoint_override = cls.service.get_endpoint_override()
    response = session.post(uri, endpoint_filter=cls.service,
        endpoint_override=endpoint_override, json=body)
    body = response.json()
    result = []
    for each in body[cls.resources_key]:
        result.append(cls.new(**each))
    return result


def storage_method(meth):
    """
    Decorator to mark the decorated method as being a storage method,
    to be copied to the storage instance.
    """
    meth.storage_method = True
    return meth


def has_message_body(status):
    """
    According to the following RFC message body and length SHOULD NOT
    be included in responses status 1XX, 204 and 304.
    https://tools.ietf.org/html/rfc2616#section-4.4
    https://tools.ietf.org/html/rfc2616#section-4.3
    """
    return status not in (204, 304) and not 100 <= status < 200


def yes_no_question(default=None):
    """
    Asks the user a yes/no question and translates it into bool.

    :return: bool
    """
    yes = {'yes', 'y', 'ye', 'Y'}
    no = {'no', 'n', 'N'}
    choice = input().lower().strip()
    if choice == '':
        choice = default
    if choice in yes:
        return True
    elif choice in no:
        return False
    else:
        print("Please respond with 'yes' or 'no'")