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


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

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


def update_axes_image(image_axes, image):
    """Update the image displayed by an image plot.

    This sets the image plot's array and updates its shape appropriately

    Parameters
    ----------
    image_axes : `matplotlib.image.AxesImage`
        Image axes to update.
    image : array
        Image array.
    """
    image_axes.set_array(image)
    h, w = image.shape[:2]
    image_axes.set_extent((0, w, h, 0))


def log_parser(parser):
    """ Given a parser, add the options controlling log. """
    group = parser.add_argument_group('logging options')
    group.add_argument('-v', '--verbose', dest='verbose', action=
        'store_true', help='Output debug messages')
    group.add_argument('--quiet', '-q', dest='quiet', action='store_true',
        help='Only output error messages')
    group.add_argument('--time-stamp', dest='timestamp', action=
        'store_true', help='Add timestamps before each log message')
    group.add_argument('--color', choices=['always', 'never', 'auto'], help
        ="Colorize output, defaults to 'auto'")
    group.add_argument('--title', choices=['always', 'never', 'auto'], help
        ="Update terminal title, defaults to 'auto'")
    parser.set_defaults(verbose=False, quiet=False, color='auto', title='auto')


def set_testmode(testing):
    """Sets the package testing mode.
    """
    global testmode
    testmode = testing


def minimumCycle(lostTime, criticalCharge, degreeSaturation=1.0):
    """degree of saturation can be used as the peak hour factor too"""
    return lostTime / (1 - criticalCharge / degreeSaturation)


def enable_cloud_admin_access(session, confirm, return_type=None, **kwargs):
    """
    Enables the ability of a storage cloud administrator to access the VPSA
    GUI of this VPSA to assist in troubleshooting.  This does not grant access
    to any volume data.  Enabled by default.

    :type session: zadarapy.session.Session
    :param session: A valid zadarapy.session.Session object.  Required.

    :type confirm: bool
    :param confirm: If True, cloud admin access will be enabled.  This is a
        safeguard for this function since it requires no other arguments.

    :type return_type: str
    :param return_type: If this is set to the string 'json', this function
        will return a JSON string.  Otherwise, it will return a Python
        dictionary.  Optional (will return a Python dictionary by default).

    :rtype: dict, str
    :returns: A dictionary or JSON data set as a string depending on
        return_type parameter.
    """
    if not confirm:
        raise ValueError(
            'The confirm parameter is not set to True - cloud admin access will not be enabled.'
            )
    path = '/api/users/admin_access/enable.json'
    return session.post_api(path=path, return_type=return_type, **kwargs)


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

        :param FileMemberActionError val:
        :rtype: FileMemberActionIndividualResult
        """
    return cls('member_error', val)


def readfast(shallow=False):
    """Calls either ``read()`` or ``readdelta()``.

        The faster of the two options is called.
        """


def channelBindings(**kwargs):
    """
    Builds a gss_channel_bindings_struct which can be used to pass onto
    L{authGSSClientStep} to bind onto the auth. Details on Channel Bindings
    can be foud at https://tools.ietf.org/html/rfc5929. More details on the
    struct can be found at
    https://docs.oracle.com/cd/E19455-01/806-3814/overview-52/index.html

    @param initiator_addrtype: Optional integer used to set the
        initiator_addrtype, defaults to GSS_C_AF_UNSPEC if not set

    @param initiator_address: Optional byte string containing the
        initiator_address

    @param acceptor_addrtype: Optional integer used to set the
        acceptor_addrtype, defaults to GSS_C_AF_UNSPEC if not set

    @param acceptor_address: Optional byte string containing the
        acceptor_address

    @param application_data: Optional byte string containing the
        application_data. An example would be 'tls-server-end-point:{cert-hash}'
        where {cert-hash} is the hash of the server's certificate

    @return: A tuple of (result, gss_channel_bindings_struct) where result is
        the result code and gss_channel_bindings_struct is the channel bindings
        structure that can be passed onto L{authGSSClientStep}
    """


def process_add_on(add_on):
    """
    simple function to ensure that a query add on string starts with "?"
    """
    if add_on.startswith('&'):
        add_on = '?' + add_on[1:]
    if add_on and not add_on.startswith('?'):
        add_on = '?' + add_on
    return add_on


def units_converter(from_units='ip', **kwargs):
    """ Converts IP values to SI units

    Parameters
    ----------
    from_units: str
        specify system to convert from
    **kwargs : [t, v]

    Returns
    -------
    converted values in SI units
    """
    results = list()
    if from_units == 'ip':
        for key, value in kwargs.items():
            if 'tmp' in key or key == 'tr' or key == 'tdb':
                results.append((value - 32) * 5 / 9)
            if key in ['v', 'vr', 'vel']:
                results.append(value / 3.281)
            if key == 'area':
                results.append(value / 10.764)
            if key == 'pressure':
                results.append(value * 101325)
    elif from_units == 'si':
        for key, value in kwargs.items():
            if 'tmp' in key or key == 'tr' or key == 'tdb':
                results.append(value * 9 / 5 + 32)
            if key in ['v', 'vr', 'vel']:
                results.append(value * 3.281)
            if key == 'area':
                results.append(value * 10.764)
            if key == 'pressure':
                results.append(value / 101325)
    return results


def _get_descriptions(t_x):
    """
    Gets the descriptions of all people searched.
    :param t_x:
    :return:
    """
    result = t_x.run(
        'MATCH(n:Person) WHERE n.description=n.description RETURN n.description'
        )
    return result


@classmethod
def from_dict(cls, about_data, base_dir=''):
    """
        Return an About object loaded from a python dict.
        """
    about = cls()
    about.load_dict(about_data, base_dir=base_dir)
    return about


def sign(x):
    """
    np.sign(0) = 0 but here to avoid value 0,
    we redefine it as def sign(0) = 1
    """
    return 1.0 if x >= 0 else -1.0


@classmethod
def getSubsystems(cls):
    """Return the list of subsytems and their relative directory"""
    return cls._subSystems


def get_deletion_offset(alt_pos, trans_queue, changes):
    """Helper function to calculate original position in reference genome"""
    offset = 0
    for struct_var in changes:
        if struct_var[2] > alt_pos and struct_var[0] != 'TRANS':
            break
        elif struct_var[0] == 'DEL':
            offset += struct_var[3]
    for trans in trans_queue:
        if trans[2] > alt_pos:
            return offset
        offset += len(trans[1])
    return offset


def parse_int_header(dictionary, key):
    """Defensively parse an int header"""
    val = dictionary.get(key)
    if val is None or not isinstance(val, str):
        return None
    if not val.isdigit():
        return None
    return int(val)


def get_df_between_date(data_df, date_frm, date_to):
    """
    该函数仅用于 return_risk_analysis 中计算使用
    :param data_df:
    :param date_frm:
    :param date_to:
    :return:
    """
    if date_frm is not None and date_to is not None:
        new_data_df = data_df[(data_df.Date >= date_frm) & (data_df.Date <=
            date_to)]
    elif date_frm is not None:
        new_data_df = data_df[data_df.Date >= date_frm]
    elif date_to is not None:
        new_data_df = data_df[data_df.Date <= date_to]
    else:
        new_data_df = data_df
    new_data_df = new_data_df.reset_index(drop=True)
    return new_data_df


def get_subdir(index):
    """
    Return the sub-directory given the index dictionary.  The return
    value is obtained in the following order:

    1. when the 'subdir' key exists, it's value is returned
    2. if the 'arch' is None, or does not exist, 'noarch' is returned
    3. otherwise, the return value is constructed from the 'platform' key
       and the 'arch' key (where 'x86' is replaced by '32',
       and 'x86_64' by '64')
    """
    try:
        return index['subdir']
    except KeyError:
        arch = index.get('arch')
        if arch is None:
            return 'noarch'
        intel_map = {'x86': '32', 'x86_64': '64'}
        return '%s-%s' % (index.get('platform'), intel_map.get(arch, arch))


def _truncate_seq_pair(tokens_a, tokens_b, max_length):
    """Truncates a sequence pair in place to the maximum length."""
    while True:
        total_length = len(tokens_a) + len(tokens_b)
        if total_length <= max_length:
            break
        if len(tokens_a) > len(tokens_b):
            tokens_a.pop()
        else:
            tokens_b.pop()


def finiteInverse(a, p):
    """Compute 1/a mod p using the Euclidean algorithm."""
    x = [a % p, 1, 0]
    y = [p, 0, 1]
    while x[0] != 1:
        z = divmod(y[0], x[0])
        x, y = [z[1], y[1] - z[0] * x[1], y[2] - z[0] * x[2]], x
    return x[1] % p


@staticmethod
def is_enough_quality(value):
    """Return True if value is enough quality."""
    raise NotImplementedError


def getMutator(instance):
    """Return the mutator method used for changing the value of this field.
        """


def widget_name(widget):
    """
  Return the widget name. Try first to get avc_name attribute. If this
  fails, get Tk widget name keeping the last part only.
  """
    try:
        return widget.avc_name
    except:
        return str(widget).split('.')[-1]


def date_format(date):
    """Converts datetime to '%d.%m.%Y-%H:%M:%S' formatted string"""
    return date.strftime('%d.%m.%Y-%H:%M:%S')


def expand_range(text):
    """Return individual numbers for a range expressed as X-Y."""
    if '-' in text:
        range_list = sorted(text.split('-'))
        return [*map(str, range(int(range_list[0]), int(range_list[1]) + 1))]
    else:
        return text


def unassign_instance(InstanceId=None):
    """
    Unassigns a registered instance from all of it's layers. The instance remains in the stack as an unassigned instance and can be assigned to another layer, as needed. You cannot use this action with instances that were created with AWS OpsWorks Stacks.
    See also: AWS API Documentation

    :example: response = client.unassign_instance(
        InstanceId='string'
    )

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

    """
    pass


def entity_by_md5(syn, contentMd5, parentId=None, cmp=None):
    """Gets the first entity in a list of entities identified by md5.

    Optionally takes a comparison function to pass to sorted
    and a parent id for filtering.

    """
    res = syn.restGET('/entity/md5/%s' % (contentMd5,))['results']
    if cmp:
        res = sorted(res, cmp=cmp)
    if parentId:
        res = filter(lambda x: x['parentId'] == parentId, res)
    try:
        entity = syn.get(res[0]['id'], version=res[0]['versionNumber'])
    except KeyError:
        entity = None
    return entity


def _accumulate(sequence, func):
    """
    Python2 accumulate implementation taken from
    https://docs.python.org/3/library/itertools.html#itertools.accumulate
    """
    iterator = iter(sequence)
    total = next(iterator)
    yield total
    for element in iterator:
        total = func(total, element)
        yield total


def recv_exactly(recv_fn, size):
    """ Use the function to read and return exactly number of bytes desired.

    https://docs.python.org/3/howto/sockets.html#socket-programming-howto for
    more information about why this is necessary.

    :param recv_fn: Function that can return up to given bytes
        (i.e. socket.recv, file.read)
    :param size: Number of bytes to read.
    :return: Byte string with length size.
    :raises ValueError: Could not receive enough data (usually timeout).
    """
    recv_bytes = 0
    chunks = []
    while recv_bytes < size:
        chunk = recv_fn(size - recv_bytes)
        if len(chunk) == 0:
            break
        recv_bytes += len(chunk)
        chunks.append(chunk)
    response = b''.join(chunks)
    if len(response) != size:
        raise ValueError
    return response


@classmethod
def get_done_filename_for_attempt(cls, attempt):
    """
        Returns the done filename (.DONE.lock) based on `attempt`.
        """
    return cls.filename_with_attempt_prefix('DONE.lock', attempt)


def parse_address(address):
    """Parse and address on the format host:port.

    Returns a tuple (host, port). Raises ValueError if format is
    invalid or port is not an integer or out of range.
    """
    words = address.split(':')
    if len(words) != 2:
        raise ValueError('address must contain exactly one colon')
    host, port = words
    try:
        port = int(port)
    except ValueError:
        raise ValueError('port number must be an integer')
    if not 0 < port < 2 ** 16:
        raise ValueError('port number out of range')
    return host, port


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

        :param TeamSelectiveSyncSettingsChangedType val:
        :rtype: EventType
        """
    return cls('team_selective_sync_settings_changed', val)


def myrange(start, stop, step=1):
    """enumerates the values from start in steps of size step that are
    less than stop.
    """
    assert step > 0, 'only positive steps implemented in myrange'
    i = start
    while i < stop:
        yield i
        i += step


def dtype(x):
    """Returns the dtype of a Keras tensor or variable, as a string.

    # Arguments
        x: Tensor or variable.

    # Returns
        String, dtype of `x`.

    # Examples
    ```python
        >>> from keras import backend as K
        >>> K.dtype(K.placeholder(shape=(2,4,5)))
        'float32'
        >>> K.dtype(K.placeholder(shape=(2,4,5), dtype='float32'))
        'float32'
        >>> K.dtype(K.placeholder(shape=(2,4,5), dtype='float64'))
        'float64'
        # Keras variable
        >>> kvar = K.variable(np.array([[1, 2], [3, 4]]))
        >>> K.dtype(kvar)
        'float32_ref'
        >>> kvar = K.variable(np.array([[1, 2], [3, 4]]), dtype='float32')
        >>> K.dtype(kvar)
        'float32_ref'
    ```
    {{np_implementation}}
    """
    return x.dtype.base_dtype.name


def chunks(l, n):
    """Yield successive n-sized chunks from l.
    From https://stackoverflow.com/a/312464/11902188
    """
    for i in range(0, len(l), n):
        yield l[i:i + n]


def get_y() ->int:
    """Gives the reading of the magnetic force on the ``x`` axis, as a
    positive or negative integer, depending on the direction of the
    force.
    """


def get_fieldnames(records):
    """
    Extract fieldnames for CSV headers from list of results

    :param records: list
    :return: list
    """
    fieldnames = []
    ordered_fieldname = ('time_last', 'time_first', 'source', 'count',
        'bailiwick', 'rrname', 'rrtype', 'rdata')
    for record in records:
        keys = list(record.keys())
        for key in keys:
            if key not in fieldnames:
                fieldnames.append(key)
    fieldnames = sorted(fieldnames, key=lambda x: ordered_fieldname.index(x))
    return fieldnames


def _slice(start, stop, step):
    """
    Generate pairs so that you can slice from start to stop, step elements at a time
    :param start: The start of the generated series
    :param stop: The last of the generated series
    :param step: The difference between the first element of the returned pair and the second
    :return: A pair that you can use to slice
    """
    if step == 0:
        raise ValueError('slice() arg 3 must not be zero')
    if start == stop:
        raise StopIteration
    _previous = start
    _next = start + step
    while _next < stop:
        yield _previous, _next
        _previous += step
        _next += step
    yield _previous, stop


@classmethod
def force_type(cls, response, environ=None):
    """
        enforce that the wsgi response is a response object of the current type.

        :param object response: response object.

        :param environ: a wsgi environment object.

        :rtype: CoreResponse
        """
    response = cls.response_converter(response)
    return super().force_type(response, environ)


def generate_address(data):
    """
    generate a address dynamically by hashing.
    """
    if not isinstance(data, str):
        data = str(data)
    return hash(data) ^ hash(data) >> 2


def make_data_iterator(data_entries, *iterables):
    """Make an iterator from an iterable of data entries and constant values.

    All iterables should have the same number of entries. Any passed values
    that are not iterators, lists, or tuples will have that same value
    repeated for the entire length of `data_entries`.

    Parameters
    ----------
    data_entries : iterable
        Iterable of data entries.
    *iterables
        One or more iterables or constant values to serve as additional
        data entries. These are zipped into an iterator with `data_entries`.

    Returns
    -------
    iterator : Iterator of tuples, each with an item in `data_entries`
               followed by corresponding items in `iterables`.
    """
    from itertools import repeat, cycle
    from collections import Iterator
    new_iterables = [iter(data_entries)]
    for iterable in iterables:
        if isinstance(iterable, Iterator) or isinstance(iterable, list
            ) or isinstance(iterable, tuple):
            new_iterables.append(cycle(iterable))
        else:
            new_iterables.append(repeat(iterable))
    return zip(*new_iterables)


def get_horizon(vantage_height, h_constant=1.5):
    """
    gets the viewing distance to the horizon on earth by height of the eyes

    :param vantage_height: in feet
    :param h_constant: horizon constant :shrug:
    :return: returns horizon in miles
    """
    return (h_constant * vantage_height) ** 0.5


def does_dominate(g1, g2, delta1, delta2):
    """
    Returns true if g1 dominates g2 with the given relaxation.

    Parameters
    ----------
    g1 : tuple of float
        Objective values of a point
    g2 : tuple of float
        Objective values of a point
    delta1 : tuple of float
        Relaxation of 'g1'
    delta2 : tuple of float
        Relaxation of 'g2'

    Returns
    -------
    is_dom : bool
    """
    dim = len(g1)
    is_dom = True
    i = 0
    while i < dim and is_dom:
        if g2[i] + delta2[i] < g1[i] - delta1[i]:
            is_dom = False
        i = i + 1
    if is_dom:
        is_equal = True
        for i in range(dim):
            if not g1[i] - delta1[i] == g2[i] + delta2[i]:
                is_equal = False
        if is_equal:
            is_dom = False
    return is_dom


def p_expression_land(p):
    """expression : expression LAND expression"""
    p[0] = p[1] and p[3]


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

        :param NoExpirationLinkGenCreateReportType val:
        :rtype: EventType
        """
    return cls('no_expiration_link_gen_create_report', val)


def constraint_to_fcurve():
    """Create F-Curves for object which will copy object’s movement caused by this constraint

    """
    pass


def ShortCadenceStatistics(*args, **kwargs):
    """
  Computes and plots the CDPP statistics comparison between short cadence
  and long cadence de-trended light curves

  """
    raise NotImplementedError('This mission is not yet supported.')


def u16le_list_to_byte_list(data):
    """! @brief Convert a halfword array into a byte array"""
    byteData = []
    for h in data:
        byteData.extend([h & 255, h >> 8 & 255])
    return byteData


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

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


def encode_sortable_key(encoder, value):
    """Takes a key and calculates the length of its optimal byte representation"""
    encoded = encoder.encode_to_bytes(value)
    return len(encoded), encoded


def _config_info(mode, config):
    """Generate info about the config."""
    return {'mode': mode, 'views': len(config.get('views', []))}


def verification(base_url: str, verification_id: str=None) ->str:
    """
    Build the URL to communicate with the verification API.
    """
    if not verification_id:
        return '/'.join([base_url, 'verifications'])
    return '/'.join([base_url, 'verifications', verification_id])


def _format(msg, left_margin=0, right_margin=78):
    """ Format a message by inserting line breaks at appropriate places.  msg
    is the text of the message.  left_margin is the position of the left
    margin.  right_margin is the position of the right margin.  Returns the
    formatted message.
    """
    curs = left_margin
    fmsg = ' ' * left_margin
    for w in msg.split():
        l = len(w)
        if curs != left_margin and curs + l > right_margin:
            fmsg = fmsg + '\n' + ' ' * left_margin
            curs = left_margin
        if curs > left_margin:
            fmsg = fmsg + ' '
            curs = curs + 1
        fmsg = fmsg + w
        curs = curs + l
    return fmsg


@classmethod
def deserialize(cls, serialized):
    """
        Deserializes the provided JSON entity

        :params serialized: a Python dict or JSON text, assumed to be the
            serialization of a *Receipt* object
        :type: dict or str
        :rtype: Receipt
        """
    kwargs = {}
    if isinstance(serialized, dict):
        kwargs.update({'from_dict': serialized})
    elif isinstance(serialized, str):
        kwargs.update({'from_json': serialized})
    return cls(**kwargs)


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


def cocktail_shaker_sort(collection):
    """
    鸡尾酒排序法(即:定向冒泡排序法)
    :param collection:
    :return:
    """
    for i in range(len(collection) - 1, 0, -1):
        swapped = False
        for j in range(i, 0, -1):
            if collection[j] < collection[j - 1]:
                collection[j], collection[j - 1] = collection[j - 1
                    ], collection[j]
                swapped = True
        for j in range(i):
            if collection[j] > collection[j + 1]:
                collection[j], collection[j + 1] = collection[j + 1
                    ], collection[j]
                swapped = True
        if not swapped:
            return collection


def has_hdmx_table(tt):
    """Tests for the presence of a hdmx table in a TrueType font."""
    return 'hdmx' in tt


def pascal_row(n):
    """ Returns n-th row of Pascal's triangle
    """
    result = [1]
    x, numerator = 1, n
    for denominator in range(1, n // 2 + 1):
        x *= numerator
        x /= denominator
        result.append(x)
        numerator -= 1
    if n & 1 == 0:
        result.extend(reversed(result[:-1]))
    else:
        result.extend(reversed(result))
    return result


def network_is_xy(network):
    """Verify that a network lies in the XY plane.

    Parameters
    ----------
    network : Network
        A network object.

    Returns
    -------
    bool
        True if the Z coordinate of all vertices is zero.
        False otherwise.

    """
    z = None
    for key in network.nodes():
        if z is None:
            z = network.node_attribute(key, 'z') or 0.0
        elif z != network.node_attribute(key, 'z') or 0.0:
            return False
    return True


def itrace(Y, YOLD, YAPX, YP, BX, BY, BZ, BB, SGN, DS, NSTP):
    """
    Follow a geomagnetic field line until passing its apex
    Cartesian component magnetic field (partial) derivitives steer the trace

    This uses the 4-point Adams formula after initialization.
    First 7 iterations advance point by 3 steps.

    INPUTS:
     YAPX  = Matrix of cartesian coordinates of the three points
             about the apex.  Set in itrace.

    FLDCOMD has geomagnetic field at current trace point:
     BX    = X component (nT)
     BY    = Y component (nT)
     BZ    = Z component (nT)
     BB    = Magnitude   (nT)

    itrace has field line tracing variables determined in findApex:
     NSTP  = Step count.
     Y     = Array containing current tracing point cartesian coordinates.
     YOLD  = Array containing previous tracing point cartesian coordinates.
     SGN   = Determines direction of trace.
     DS    = Step size (arc length in km).

    REFERENCES:
     Stassinopoulos E. G. , Mead Gilbert D., X-841-72-17 (1971) GSFC,
     Greenbelt, Maryland
    """
    YP[0][3] = SGN * BX / BB
    YP[1][3] = SGN * BY / BB
    YP[2][3] = SGN * BZ / BB
    D2 = DS / 2.0
    D6 = DS / 6.0
    D12 = DS / 12.0
    D24 = DS / 24.0
    if NSTP <= 7:
        for I in range(0, 3):
            if NSTP == 1:
                YP[I][0] = YP[I][3]
                YOLD[I] = Y[I]
                YAPX[I][0] = Y[I]
                Y[I] = YOLD[I] + DS * YP[I][0]
            elif NSTP == 2:
                YP[I][1] = YP[I][3]
                Y[I] = YOLD[I] + D2 * (YP[I][1] + YP[I][0])
            elif NSTP == 3:
                Y[I] = YOLD[I] + D6 * (2.0 * YP[I][3] + YP[I][1] + 3.0 * YP
                    [I][0])
            elif NSTP == 4:
                YP[I][1] = YP[I][3]
                YAPX[I][1] = Y[I]
                YOLD[I] = Y[I]
                Y[I] = YOLD[I] + D2 * (3.0 * YP[I][1] - YP[I][0])
            elif NSTP == 5:
                Y[I] = YOLD[I] + D12 * (5.0 * YP[I][3] + 8.0 * YP[I][1] -
                    YP[I][0])
            elif NSTP == 6:
                YP[I][2] = YP[I][3]
                YOLD[I] = Y[I]
                YAPX[I][2] = Y[I]
                Y[I] = YOLD[I] + D12 * (23.0 * YP[I][2] - 16.0 * YP[I][1] +
                    5.0 * YP[I][0])
            elif NSTP == 7:
                YAPX[I][0] = YAPX[I][1]
                YAPX[I][1] = YAPX[I][2]
                Y[I] = YOLD[I] + D24 * (9.0 * YP[I][3] + 19.0 * YP[I][2] -
                    5.0 * YP[I][1] + YP[I][0])
                YAPX[I][2] = Y[I]
    else:
        for I in range(0, 3):
            YAPX[I][0] = YAPX[I][1]
            YAPX[I][1] = Y[I]
            YOLD[I] = Y[I]
            Y[I] = YOLD[I] + D24 * (55.0 * YP[I][3] - 59.0 * YP[I][2] +
                37.0 * YP[I][1] - 9.0 * YP[I][0])
            YAPX[I][2] = Y[I]
            for J in range(0, 3):
                YP[I][J] = YP[I][J + 1]


def compute_Rn(albedo_c, albedo_s, T_air, T_c, T_s, e_atm, Rs_c, Rs_s, F):
    """Compute Soil and Canopy Net Radiation

    Parameters
    ----------
    albedo_c : ee.Image
    albedo_s : ee.Image
    T_air : ee.Image
        Air temperature (Kelvin).
    T_c : ee.Image
        Canopy temperature (Kelvin).
    T_s : ee.Image
        Soil temperature (Kelvin).
    e_atm : ee.Image
    Rs_c : ee.Image
    Rs_s : ee.Image
    F : ee.Image

    Returns
    -------
    Rn_s : ee.Image
        Soil net radiation (W m-2)
    Rn_c : ee.Image
        Canopy net radiation (W m-2)
    Rn : ee.Image
        Net radiation (W m-2)

    """
    kL = 0.95
    eps_s = 0.94
    eps_c = 0.99
    L_c = T_c.expression('eps_c * 0.0000000567 * (T_c ** 4)', {'eps_c':
        eps_c, 'T_c': T_c})
    L_s = T_s.expression('eps_s * 0.0000000567 * (T_s ** 4)', {'eps_s':
        eps_s, 'T_s': T_s})
    Rle = T_air.expression('e_atm * 0.0000000567 * (T_air ** 4)', {'e_atm':
        e_atm, 'T_air': T_air})
    Rn_c = albedo_c.expression(
        '((1 - albedo_c) * Rs_c) + ((1 - exp(-kL * F)) * (Rle + Ls - 2 * L_c))'
        , {'albedo_c': albedo_c, 'F': F, 'kL': kL, 'L_c': L_c, 'L_s': L_s,
        'Rle': Rle, 'Rs_c': Rs_c})
    Rn_s = albedo_s.expression(
        '((1 - albedo_s) * Rs_s) + ((exp(-kL * F)) * Rle) + ((1 - exp(-kL * F)) * L_c) - L_s'
        , {'albedo_s': albedo_s, 'F': F, 'kL': kL, 'Lc': L_c, 'Ls': L_s,
        'Rle': Rle, 'Rs_s': Rs_s})
    Rn = Rn_s.expression('Rn_s + Rn_c', {'Rn_s': Rn_s, 'Rn_c': Rn_c})
    return Rn_s, Rn_c, Rn


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

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


def _filter_non_json_lines(data):
    """
    Used to filter unrelated output around module JSON output, like messages from
    tcagetattr, or where dropbear spews MOTD on every single command (which is nuts).

    Filters leading lines before first line-starting occurrence of '{' or '[', and filter all
    trailing lines after matching close character (working from the bottom of output).
    """
    warnings = []
    lines = data.splitlines()
    for start, line in enumerate(lines):
        line = line.strip()
        if line.startswith(u'{'):
            endchar = u'}'
            break
        elif line.startswith(u'['):
            endchar = u']'
            break
    else:
        raise ValueError('No start of json char found')
    lines = lines[start:]
    for reverse_end_offset, line in enumerate(reversed(lines)):
        if line.strip().endswith(endchar):
            break
    else:
        raise ValueError('No end of json char found')
    if reverse_end_offset > 0:
        trailing_junk = lines[len(lines) - reverse_end_offset:]
        warnings.append(
            'Module invocation had junk after the JSON data: %s' % '\n'.
            join(trailing_junk))
    lines = lines[:len(lines) - reverse_end_offset]
    return '\n'.join(lines), warnings


def stub_list():
    """Returns empty "list".

    Returns:
        list: Empty list.

    Example:

        >>> stub_list()
        []

    .. versionadded:: 4.0.0
    """
    return []


def _startswith(prop_value, cmp_value, ignore_case=False):
    """
    Helper function that take two arguments and checks if :param prop_value:
    startswith :param cmp_value:

    :param prop_value: Property value that you are checking.
    :type prop_value: :class:`str`
    :param cmp_value: Value that you are checking if it is in the property
        value startswith.
    :type cmp_value: :class:`str`
    :param ignore_case: True to run using incase sensitive.
    :type ignore_case: :class:`bool`
    :returns: True if :param prop_value: startswith :param cmp_value:
    :rtype: class:`bool`
    """
    if ignore_case is True:
        prop_value = prop_value.lower()
        cmp_value = cmp_value.lower()
    return prop_value.startswith(cmp_value)


def register_custom_short_path(short_path, content):
    """ Register a custom short path for content.
        """


def rint(data=None, name=None, attr=None, out=None, **kwargs):
    """Returns element-wise rounded value to the nearest integer of the input.

    .. note::
       - For input ``n.5`` ``rint`` returns ``n`` while ``round`` returns ``n+1``.
       - For input ``-n.5`` both ``rint`` and ``round`` returns ``-n-1``.

    Example::

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

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

       - rint(default) = default
       - rint(row_sparse) = row_sparse
       - rint(csr) = csr

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

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

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

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


@classmethod
def from_socket(cls, socket, io_loop=None):
    """Create an async socket from an existing Socket"""
    return cls(_from_socket=socket, io_loop=io_loop)


def is_simple_bool(typehint) ->bool:
    """Check if typehint is bool or Union[None, bool]."""
    if typehint is bool:
        return True
    if hasattr(typehint, '__args__') and bool in typehint.__args__:
        return True
    return False


@classmethod
def add_project_levels(cls, project):
    """ Add project sub levels extra items """
    eitem_path = ''
    eitem_project_levels = {}
    if project is not None:
        subprojects = project.split('.')
        for i in range(0, len(subprojects)):
            if i > 0:
                eitem_path += '.'
            eitem_path += subprojects[i]
            eitem_project_levels['project_' + str(i + 1)] = eitem_path
    return eitem_project_levels


def make_header(text, size=80, symbol='-'):
    """Unified way to make header message to CLI.

    :param text: what text to write
    :param size: Length of header decorative line
    :param symbol: What symbol to use to create header
    """
    header = symbol * size + '\n'
    header += '%s\n' % text
    header += symbol * size + '\n'
    return header


def getNumberOfGames(prompt):
    """Obtain the number of required games for a bench test."""
    return int(input(prompt))


def text(el, strip=True):
    """
    Return the text of a ``BeautifulSoup`` element
    """
    if not el:
        return ''
    text = el.text
    if strip:
        text = text.strip()
    return text


def stopped(header):
    """ Test if header stopped sucessfully."""
    try:
        status = header.stop['exit_status']
    except KeyError:
        status = 'Python crash before exit'
    if status == 'success':
        return True
    else:
        return False


def edge_rotate(use_ccw: bool=False):
    """Rotate selected edge or adjoining faces

    :param use_ccw: Counter Clockwise
    :type use_ccw: bool
    """
    pass


def uniform(record_list):
    """Generate uniform abundance distribution from a number of records

    Args:
        record_list (list): a list of record.id

    Returns:
        dict: a dictionary with records as keys, abundance as values
    """
    abundance_dic = {}
    n_records = len(record_list)
    for record in record_list:
        abundance_dic[record] = 1 / n_records
    return abundance_dic


@classmethod
def init_artifact(cls, context, values):
    """Initialize an empty versioned object with values.

        Initialize vo object with default values and values specified by user.
        Also reset all changes of initialized object so user can track own
        changes.

        :param context: user context
        :param values: values needs to be set
        :return: artifact with initialized values
        """
    af = cls(context)
    default_fields = []
    for field in af.fields:
        if field not in values:
            default_fields.append(field)
    if default_fields:
        af.obj_set_defaults(*default_fields)
    for name, value in values.items():
        setattr(af, name, value)
    return af


def mp_make_fraction(p, q):
    """The make fraction routine produces the fraction equivalent of p/q, given
    integers p and q; it computes the integer f = floor(2**28 p/q + 1/2), when
    p and q are positive.

    In machine language this would simply be (2**28*p)div q"""
    return p / q


def get_type(type_name):
    """Return the type of the given node type string (without *? modifier)."""
    if type_name[-1] == '*' or type_name[-1] == '?':
        return type_name[:-1]
    return type_name


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

        Non dynamic discovery of type for:
            * data.extensions

        :param es_major: major version of Elasticsearch, as string
        :returns:        dictionary with a key, 'items', with the mapping
        """
    mapping = """
         {
            "dynamic":true,
                "properties": {
                    "data": {
                        "properties": {
                            "extensions": {
                                "dynamic":false,
                                "properties": {}
                            },
                            "ancestors": {
                                "properties": {
                                    "extensions": {
                                        "dynamic":false,
                                        "properties": {}
                                    }
                                }
                            },
                            "body": {
                                "dynamic":false,
                                "properties": {}
                            }
                        }
                    }
                }
        }
        """
    return {'items': mapping}


@staticmethod
def _init_common_arguments(argparser):
    """Inits command line arugments for the script
        Returns argparser object
        """
    argparser.add_argument('--fileformat', help=
        'File format to fetch. Default is CSV')
    argparser.add_argument('id', help='ID to fetch from open.canada.ca')


def get_delimited(s, offset, delim):
    """ Collect text from the string `s` from position `offset` up
      to the first occurence of delimiter `delim`; return the text
      excluding the delimiter and the offset after the delimiter.
  """
    pos = s.find(delim, offset)
    if pos < offset:
        raise ValueError('delimiter %r not found after offset %d' % (delim,
            offset))
    return s[offset:pos], pos + len(delim)


@classmethod
def _create_column_info(cls, name: str, data_type: str) ->dict:
    """
        Create column info object
        :param name: column name
        :param data_type: column data type
        :return: column info object
        """
    return {'name': name, 'type': f'{data_type}'}


def nfa_intersection(nfa_1: dict, nfa_2: dict) ->dict:
    """ Returns a NFA that reads the intersection of the NFAs in
    input.

    Let :math:`A_1 = (Σ,S_1,S_1^0,ρ_1,F_1)` and :math:`A_2 =(Σ,
    S_2,S_2^0,ρ_2,F_2)` be two NFAs.
    There is a NFA :math:`A_∧` that runs simultaneously both
    :math:`A_1` and :math:`A_2` on the input word,
    so :math:`L(A_∧) = L(A_1)∩L(A_2)`.
    It is defined as:

    :math:`A_∧ = ( Σ , S , S_0 , ρ , F )`

    where

    • :math:`S = S_1 × S_2`
    • :math:`S_0 = S_1^0 × S_2^0`
    • :math:`F = F_1 × F_2`
    • :math:`((s,t), a, (s_X , t_X)) ∈ ρ` iff :math:`(s, a,s_X )
      ∈ ρ_1` and :math:`(t, a, t_X ) ∈ ρ_2`

    :param dict nfa_1: first input NFA;
    :param dict nfa_2: second input NFA;
    :return: *(dict)* representing the intersected NFA.
    """
    intersection = {'alphabet': nfa_1['alphabet'].intersection(nfa_2[
        'alphabet']), 'states': set(), 'initial_states': set(),
        'accepting_states': set(), 'transitions': dict()}
    for init_1 in nfa_1['initial_states']:
        for init_2 in nfa_2['initial_states']:
            intersection['initial_states'].add((init_1, init_2))
    intersection['states'].update(intersection['initial_states'])
    boundary = set()
    boundary.update(intersection['initial_states'])
    while boundary:
        state_nfa_1, state_nfa_2 = boundary.pop()
        if state_nfa_1 in nfa_1['accepting_states'] and state_nfa_2 in nfa_2[
            'accepting_states']:
            intersection['accepting_states'].add((state_nfa_1, state_nfa_2))
        for a in intersection['alphabet']:
            if (state_nfa_1, a) not in nfa_1['transitions'] or (state_nfa_2, a
                ) not in nfa_2['transitions']:
                continue
            s1 = nfa_1['transitions'][state_nfa_1, a]
            s2 = nfa_2['transitions'][state_nfa_2, a]
            for destination_1 in s1:
                for destination_2 in s2:
                    next_state = destination_1, destination_2
                    if next_state not in intersection['states']:
                        intersection['states'].add(next_state)
                        boundary.add(next_state)
                    intersection['transitions'].setdefault(((state_nfa_1,
                        state_nfa_2), a), set()).add(next_state)
                    if destination_1 in nfa_1['accepting_states'
                        ] and destination_2 in nfa_2['accepting_states']:
                        intersection['accepting_states'].add(next_state)
    return intersection


@classmethod
def gauge(cls, metric_name, value, tags=None, **kwargs):
    """
        Record a gauge value (for a gauge, the latest value within any one
        minute is the value stored).

        Args:
            metric_name (str): name of the metric to be stored
            value (int or float): the value of the metric
            tags (list or dict): miscellaneous tags to describe the value
        """
    cls.stats().gauge(cls.get_metric_name(metric_name), value=value, tags=
        cls._convert_tags(tags), **kwargs)


def svg(filepath: str='', filter_glob: str='*.svg'):
    """Load a SVG file

    :param filepath: File Path, Filepath used for importing the file
    :type filepath: str
    :param filter_glob: filter_glob
    :type filter_glob: str
    """
    pass


@staticmethod
def _construct_struct_name(date):
    """
        Construct a name based on a given date, that will be used as a key
        identifier.

        :Parameters:
           - `date`: Date to use as part of the construct key.
        """
    tmp = ''.join(str(date.date()).rsplit('-'))
    return 'usage_data:{0}'.format(tmp)


@staticmethod
def positional_to_model(value):
    """Converts a positional argument to a model value"""
    return value


def get_jquery_min_js():
    """
    Return the location of jquery.min.js. It's an entry point to adapt the path
    when it changes in Django.
    """
    return 'admin/js/vendor/jquery/jquery.min.js'


def _create_arcus_dbuser(cursor, password):
    """ Create the arcus user in the DB """
    cursor.execute('SELECT user FROM mysql.user;')
    users = cursor.fetchall()
    if (bytearray(b'arcus'),) in users:
        return False
    create_cmd = 'CREATE USER arcus IDENTIFIED BY "{}"'.format(password)
    cursor.execute(create_cmd)
    grant_cmd = 'GRANT ALL privileges ON arcus.* TO "arcus";'
    cursor.execute(grant_cmd)
    return True


def check_for_custom_activations(layer_attributes):
    """
    Check if the layer contains a custom activation function, and deal with it
    appropriately.

    Parameters
    ----------

    layer_attributes: dict
        A dictionary containing the attributes of the layer.
    """
    if 'activation' not in layer_attributes.keys():
        return


def crc(s):
    """Function for computing the CRC used in the protocol.  I haven't looked
    at it closely enough to really see what it's doing..."""
    s += '\x00\x00'
    p = 0
    r1 = ord(s[p])
    p += 1
    r2 = ord(s[p])
    p += 1
    for i in range(len(s) - 2):
        r3 = ord(s[p])
        p += 1
        for j in range(8):
            r4 = r1
            r1 = r1 << 1 & 255
            if r2 & 128 != 0:
                r1 = r1 + 1 & 255
            r2 = r2 << 1 & 255
            if r3 & 128 != 0:
                r2 = r2 + 1 & 255
            r3 = r3 << 1 & 255
            if r4 & 128 != 0:
                r1 = r1 ^ 16
                r2 = r2 ^ 65
    return r1 << 8 | r2


def getfileextension(filename):
    """
    uses file name to get extension
    :param filename:
    :return:
    """
    a = filename.rfind('.')
    return filename[a:]


def full_dict(ldict, keys):
    """Return Comparison Dictionaries
       from list dict on keys
       keys: a list of keys that when
       combined make the row in the list unique
    """
    if type(keys) == str:
        keys = [keys]
    else:
        keys = keys
    cmp_dict = {}
    for line in ldict:
        index = []
        for key in keys:
            index.append(str(line.get(key, '')))
        index_str = '-'.join(index)
        cmp_dict[index_str] = line
    return cmp_dict


@staticmethod
def setup_command_line(parser):
    """Setup the command line options for an and of literals

        Arguments:
        - `parser`: parser to load with options.
        """
    parser.add_argument('P', metavar='<P>', type=int, help='positive literals')
    parser.add_argument('N', metavar='<N>', type=int, help='negative literals')


def get_center_and_radius(_, ax):
    """Return center, radius, both are (x, y) tuples
    Param: event, ax
    """
    xlim = ax.get_xlim()
    ylim = ax.get_ylim()
    rx = (xlim[1] - xlim[0]) * 0.5
    ry = (ylim[1] - ylim[0]) * 0.5
    cx = xlim[0] + rx
    cy = ylim[0] + ry
    return (cx, cy), (rx, ry)


def nested_set(data, keys, value):
    """
    Set `data[key1][key2]...[keyN] = value`
    """
    if not keys:
        raise TypeError('At least one key is required')
    for key in keys[:-1]:
        data = data[key]
    data[keys[-1]] = value


def expand_indent(line):
    """Return the amount of indentation.

    Tabs are expanded to the next multiple of 8.

    >>> expand_indent('    ')
    4
    >>> expand_indent('\\t')
    8
    >>> expand_indent('       \\t')
    8
    >>> expand_indent('        \\t')
    16
    """
    if '\t' not in line:
        return len(line) - len(line.lstrip())
    result = 0
    for char in line:
        if char == '\t':
            result = result // 8 * 8 + 8
        elif char == ' ':
            result += 1
        else:
            break
    return result


def __call__():
    """Return the rendered calendar."""


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 dgl_graph_compact(*graph_data, **kwargs):
    """This operator compacts a CSR matrix generated by
    dgl_csr_neighbor_uniform_sample and dgl_csr_neighbor_non_uniform_sample.
    The CSR matrices generated by these two operators may have many empty
    rows at the end and many empty columns. This operator removes these
    empty rows and empty columns.

    Example:

       .. code:: python

      shape = (5, 5)
      data_np = np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20], dtype=np.int64)
      indices_np = np.array([1,2,3,4,0,2,3,4,0,1,3,4,0,1,2,4,0,1,2,3], dtype=np.int64)
      indptr_np = np.array([0,4,8,12,16,20], dtype=np.int64)
      a = mx.nd.sparse.csr_matrix((data_np, indices_np, indptr_np), shape=shape)
      seed = mx.nd.array([0,1,2,3,4], dtype=np.int64)
      out = mx.nd.contrib.dgl_csr_neighbor_uniform_sample(a, seed, num_args=2, num_hops=1,
              num_neighbor=2, max_num_vertices=6)
      subg_v = out[0]
      subg = out[1]
      compact = mx.nd.contrib.dgl_graph_compact(subg, subg_v,
              graph_sizes=(subg_v[-1].asnumpy()[0]), return_mapping=False)

      compact.asnumpy()
      array([[0, 0, 0, 1, 0],
             [2, 0, 3, 0, 0],
             [0, 4, 0, 0, 5],
             [0, 6, 0, 0, 7],
             [8, 9, 0, 0, 0]])

    Defined in src/operator/contrib/dgl_graph.cc:L1582

    Parameters
    ----------
    graph_data : NDArray[]
        Input graphs and input vertex Ids.
    return_mapping : boolean, required
        Return mapping of vid and eid between the subgraph and the parent graph.
    graph_sizes : tuple of <long>, required
        the number of vertices in each graph.

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

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


def mapcat(f, *colls):
    """
    Returns a generator representing the result of applying concat to the
    result of applying ``map`` to ``f`` and ``colls``. Thus function ``f``
    should return a collection.
    """
    for coll in map(f, *colls):
        for e in coll:
            yield e


def get_indices(x, target):
    """Return the pair of indices that bound a target value in a monotonically
    increasing vector.

    **Arguments:**

    - *x*: Vector

    - *target*: Target value

    **Example:**

    >>> get_indices([0, 1, 2], 1.6)
    (1, 2)
    """
    if target <= x[0]:
        return 0, 0
    if target >= x[-1]:
        i = len(x) - 1
        return i, i
    else:
        i_1 = 0
        i_2 = len(x) - 1
        while i_1 < i_2 - 1:
            i_mid = int((i_1 + i_2) / 2)
            if x[i_mid] == target:
                return i_mid, i_mid
            elif x[i_mid] > target:
                i_2 = i_mid
            else:
                i_1 = i_mid
    return i_1, i_2


def domain_to_filename(domain):
    """All '/' are turned into '-', no trailing. schema's
    are gone, only the raw domain + ".txt" remains
    """
    filename = domain.replace('/', '-')
    if filename[-1] == '-':
        filename = filename[:-1]
    filename += '.txt'
    return filename


def dbh_directory(path, contenttype, extension, roottag, nsurl):
    """ Generic Directory Handler - Returns directory_generic for all inode/directory """
    if contenttype.startswith('inode/directory') or contenttype.startswith(
        'application/x-directory') or contenttype.startswith('directory'):
        return 'db_directory'
    else:
        return False


def agent(request):
    """
    A context processor that sets the template context variable ``agent`` to
    the value of ``request.agent``.
    """
    return {'agent': getattr(request, 'agent', None)}


def create_state_response(record):
    """Create the state response body from a record."""
    return {'job_id': record.job_id, 'state': record.state, 'task': record.
        task, 'task_percent': str(record.task_percent), 'complete': bool(
        record.complete), 'updated': str(record.updated), 'created': str(
        record.created), 'exception': str(record.exception)}


def theta_H_Me4N_PK74(T, P):
    """c-c': hydrogen tetramethylammonium [PK74]."""
    theta = 0.0
    valid = T == 298.15
    return theta, valid


def add_modules_to_metadata(modules, metadata):
    """
    modules is dict of otus, metadata is a dictionary of dictionaries where outer dict keys
    are features, inner dict keys are metadata names and values are metadata values
    """
    for module_, otus in modules.items():
        for otu in otus:
            if str(otu) in metadata:
                metadata[str(otu)]['module'] = module_
            else:
                metadata[str(otu)] = dict()
                metadata[str(otu)]['module'] = module_
    return metadata


def ndim(x):
    """Returns the number of axes in a tensor, as an integer.

    # Arguments
        x: Tensor or variable.

    # Returns
        Integer (scalar), number of axes.

    # Examples
    ```python
        >>> from keras import backend as K
        >>> inputs = K.placeholder(shape=(2, 4, 5))
        >>> val = np.array([[1, 2], [3, 4]])
        >>> kvar = K.variable(value=val)
        >>> K.ndim(inputs)
        3
        >>> K.ndim(kvar)
        2
    ```
    """
    dims = x.get_shape()._dims
    if dims is not None:
        return len(dims)
    return None


def get_driver(url='neo4j'):
    """
    Get the driver to the network connection
    :return: the driver for the graphdabase
    """
    from neo4j.v1 import GraphDatabase
    driver = GraphDatabase.driver('bolt://' + url + ':7687')
    return driver


@classmethod
def topic(cls, **kwargs) ->str:
    """Get MQTT topic for this message type."""
    return 'hermes/error/audioServer/play'


def PolsSickHosp(t):
    """Number of policies: Sickness Hospitalization"""
    return 0


def obtain_input(message_text):
    """Perform input command as a function so it can be mocked."""
    return input(message_text)


@classmethod
def from_pygments_lexer_cls(cls, lexer_cls: 'PygmentsLexerCls') ->'RegexSync':
    """
        Create a :class:`.RegexSync` instance for this Pygments lexer class.
        """
    patterns = {'Python': '^\\s*(class|def)\\s+', 'Python 3':
        '^\\s*(class|def)\\s+', 'HTML': '<[/a-zA-Z]', 'JavaScript':
        '\\bfunction\\b'}
    p = patterns.get(lexer_cls.name, '^')
    return cls(p)


def check_valid_pipeline(steps):
    """
    Helper function to check whether a pipeline is constructed properly. Taken
    from original sklearn pipeline source code with minor modifications,
    which are commented below.
    """
    names, estimators = zip(*steps)
    transforms = estimators[:-1]
    estimator = estimators[-1]
    for t in transforms:
        if not hasattr(t, 'fit') and hasattr(t, 'transform'):
            raise TypeError(
                "All intermediate steps of the chain should be transforms and implement fit and transform '%s' (type %s) doesn't)"
                 % (t, type(t)))
    if not hasattr(estimator, 'fit'):
        raise TypeError(
            "Last step of chain should implement fit '%s' (type %s) doesn't)" %
            (estimator, type(estimator)))


def get_crz():
    """Z Reduction Counter

        @returns: the last document crz
        @rtype: integer
        """


def stripPathCruft(path):
    """Strip cruft from a path name."""
    if not path:
        return path
    if len(path) > 2 and (path[0] == '<' and path[-1] == '>' or path[0] ==
        '"' and path[-1] == '"' or path[0] == "'" and path[-1] == "'"):
        path = path[1:-1].strip()
    return path


def parse_person(persons):
    """
    https://getcomposer.org/doc/04-schema.md#authors
    A "person" is an object with a "name" field and optionally "url" and "email".

    Yield  a name, email, url tuple for a person object
    A person can be in the form:
        "authors": [
            {
                "name": "Nils Adermann",
                "email": "naderman@naderman.de",
                "homepage": "http://www.naderman.de",
                "role": "Developer"
            },
            {
                "name": "Jordi Boggiano",
                "email": "j.boggiano@seld.be",
                "homepage": "http://seld.be",
                "role": "Developer"
            }
        ]

    Both forms are equivalent.
    """
    if isinstance(persons, list):
        for person in persons:
            name = person.get('name')
            role = person.get('role')
            email = person.get('email')
            url = person.get('homepage')
            yield name and name.strip(), role and role.strip(
                ), email and email.strip('<> '), url and url.strip('() ')
    else:
        raise ValueError('Incorrect PHP composer persons: %(persons)r' %
            locals())


def update_backward_window(turn_from, tick_from, turn_to, tick_to, updfun,
    branchd):
    """Iterate backward over a window of time in ``branchd`` and call ``updfun`` on the values"""
    if turn_from in branchd:
        for future_state in reversed(branchd[turn_from][:tick_from]):
            updfun(*future_state)
    for midturn in range(turn_from - 1, turn_to, -1):
        if midturn in branchd:
            for future_state in reversed(branchd[midturn][:]):
                updfun(*future_state)
    if turn_to in branchd:
        for future_state in reversed(branchd[turn_to][tick_to + 1:]):
            updfun(*future_state)


def ddupe_with_precision(orig_df, precision=10):
    """
    round original DataFrame to a given precision, drop_duplicates,
        return original dataframe with those rows indexed.
    """
    return orig_df.loc[orig_df.round(precision).drop_duplicates().index]


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 get_onto_for_testing(TEST_ONLINE=False):
    """Wrapper for util script used in viz main methods"""
    if TEST_ONLINE:
        from ontospy import Ontospy
        g = Ontospy('http://cohere.open.ac.uk/ontology/cohere.owl#')
    else:
        from ontospy.core.manager import get_random_ontology
        uri, g = get_random_ontology(50)
    return g


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


def delete_alarms(AlarmNames=None):
    """
    Deletes the specified alarms. In the event of an error, no alarms are deleted.
    See also: AWS API Documentation

    :example: response = client.delete_alarms(
        AlarmNames=[
            'string',
        ]
    )

    :type AlarmNames: list
    :param AlarmNames: [REQUIRED]
            The alarms to be deleted.
            (string) --

    """
    pass


def tag_resources(ResourceARNList=None, Tags=None):
    """
    Applies one or more tags to the specified resources. Note the following:
    See also: AWS API Documentation

    :example: response = client.tag_resources(
        ResourceARNList=[
            'string',
        ],
        Tags={
            'string': 'string'
        }
    )

    :type ResourceARNList: list
    :param ResourceARNList: [REQUIRED]
            A list of ARNs. An ARN (Amazon Resource Name) uniquely identifies a resource. You can specify a minimum of 1 and a maximum of 20 ARNs (resources) to tag. An ARN can be set to a maximum of 1600 characters. For more information, see Amazon Resource Names (ARNs) and AWS Service Namespaces in the AWS General Reference .
            (string) --

    :type Tags: dict
    :param Tags: [REQUIRED]
            The tags that you want to add to the specified resources. A tag consists of a key and a value that you define.
            (string) --
            (string) --

    :rtype: dict
    :return: {
        'FailedResourcesMap': {
            'string': {
                'StatusCode': 123,
                'ErrorCode': 'InternalServiceException'|'InvalidParameterException',
                'ErrorMessage': 'string'
            }
        }
    }

    :returns:
    ResourceARNList (list) -- [REQUIRED]
    A list of ARNs. An ARN (Amazon Resource Name) uniquely identifies a resource. You can specify a minimum of 1 and a maximum of 20 ARNs (resources) to tag. An ARN can be set to a maximum of 1600 characters. For more information, see Amazon Resource Names (ARNs) and AWS Service Namespaces in the AWS General Reference .

    (string) --

    Tags (dict) -- [REQUIRED]
    The tags that you want to add to the specified resources. A tag consists of a key and a value that you define.

    (string) --
    (string) --

    """
    pass


def _get_item_properties(item, fields):
    """Return a tuple containing the item properties."""
    row = []
    for field in fields:
        row.append(item.get(field, ''))
    return tuple(row)


def __call__(timestamp, request):
    """
        Generate a line for the access log.

        @param timestamp: The time at which the request was completed in the
            standard format for access logs.
        @type timestamp: L{unicode}

        @param request: The request object about which to log.
        @type request: L{twisted.web.server.Request}

        @return: One line describing the request without a trailing newline.
        @rtype: L{unicode}
        """


def _set_cipher(db_handle, cipher='aes-256-cbc'):
    """
    Set the cipher and mode to use for symmetric encryption.

    SQLCipher uses aes-256-cbc as the default cipher and mode of
    operation. It is possible to change this, though not generally
    recommended, using PRAGMA cipher.

    SQLCipher makes direct use of libssl, so all cipher options available
    to libssl are also available for use with SQLCipher. See `man enc` for
    OpenSSL's supported ciphers.

    Implementation Notes:

    * PRAGMA cipher must be called after PRAGMA key and before the first
        actual database operation or it will have no effect.

    * If a non-default value is used PRAGMA cipher to create a database,
        it must also be called every time that database is opened.

    * SQLCipher does not implement its own encryption. Instead it uses the
        widely available and peer-reviewed OpenSSL libcrypto for all
        cryptographic functions.

    :param db_handle: A handle to the SQLCipher database.
    :type db_handle: pysqlcipher.Connection
    :param cipher: The cipher and mode to use.
    :type cipher: str
    """
    db_handle.cursor().execute("PRAGMA cipher = '%s'" % cipher)


def encode(strs):
    """Encodes a list of strings to a single string.
    :type strs: List[str]
    :rtype: str
    """
    res = ''
    for string in strs.split():
        res += str(len(string)) + ':' + string
    return res


def unsubscribe_from_event(resourceArn=None, event=None, topicArn=None):
    """
    Disables the process of sending Amazon Simple Notification Service (SNS) notifications about a specified event to a specified SNS topic.
    See also: AWS API Documentation

    Examples
    Disables the process of sending Amazon Simple Notification Service (SNS) notifications about a specified event to a specified SNS topic.
    Expected Output:

    :example: response = client.unsubscribe_from_event(
        resourceArn='string',
        event='ASSESSMENT_RUN_STARTED'|'ASSESSMENT_RUN_COMPLETED'|'ASSESSMENT_RUN_STATE_CHANGED'|'FINDING_REPORTED'|'OTHER',
        topicArn='string'
    )

    :type resourceArn: string
    :param resourceArn: [REQUIRED]
            The ARN of the assessment template that is used during the event for which you want to stop receiving SNS notifications.

    :type event: string
    :param event: [REQUIRED]
            The event for which you want to stop receiving SNS notifications.

    :type topicArn: string
    :param topicArn: [REQUIRED]
            The ARN of the SNS topic to which SNS notifications are sent.

    :return: response = client.unsubscribe_from_event(
        event='ASSESSMENT_RUN_COMPLETED',
        resourceArn='arn:aws:inspector:us-west-2:123456789012:target/0-nvgVhaxX/template/0-7sbz2Kz0',
        topicArn='arn:aws:sns:us-west-2:123456789012:exampletopic',
    )

    print(response)

    """
    pass


def get_norm_socre(template, score, qcat_config):
    """
    Normalize alignment score

    :param template: Barcoding adapter
    :param score: Alignment score
    :param qcat_config: Config
    :return: Normalized score
    """
    bc_len = template.get_barcode_length(0) + template.get_barcode_length(1)
    a_len = template.get_adapter_length()
    return score * 100.0 / ((a_len - bc_len) * qcat_config.match + bc_len *
        qcat_config.nmatch)


def get_server_tasks():
    """Get a list of tasks that the server will be responsible to run

        A task is a object implementing :class:`.IPluginTask`.

        :returns: a list of tasks
        """
    pass


def timedelta_to_seconds(td):
    """
    Converts a timedelta instance to seconds.
    """
    return td.seconds + td.days * 24 * 60 * 60


def unenforce_placement_group():
    """Enforces all tasks to be launched into placement group."""
    global enforce_placement_group_val
    enforce_placement_group_val = False


def join_schema_func(func):
    """Join the schema and function, if needed, to form a qualified name

    :param func: a schema, function tuple, or just an unqualified function name
    :returns: a possibly-qualified schema.function string
    """
    if isinstance(func, tuple):
        return '%s.%s' % func
    else:
        return func


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

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

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


def get_resource_attributes(attrs):
    """
    Gets the attributes required to render occi compliant compute
    resource information.
    """
    attrs = {'occi.compute.cores': 'immutable', 'occi.compute.memory':
        'immutable', 'org.openstack.compute.swap': 'immutable',
        'org.openstack.compute.storage.root': 'immutable',
        'org.openstack.compute.storage.ephemeral': 'immutable'}
    return attrs


def main_utility_demand_a(user):
    """Only include avatar activation if the account has avatars."""
    return user.account.get('avatars')


@classmethod
def to_hg_scheme_url(cls, url):
    """
        convert a URL to local mercurial URL schemes

        example::

            # schemes.gh = git://github.com/
            >> remote_url = git://github.com/westurner/dotfiles'
            >> to_hg_scheme_url(remote_url)
            << gh://westurner/dotfiles

        """
    regexes = cls._get_url_scheme_regexes()
    for scheme_key, pattern, regex in regexes:
        match = regex.match(url)
        if match is not None:
            groups = match.groups()
            if len(groups) == 2:
                return u''.join(scheme_key, '://', pattern.replace('{1}',
                    groups[0]), groups[1])
            elif len(groups) == 1:
                return u''.join(scheme_key, '://', pattern, groups[0])


def _status_decode(status):
    """Decode a 1 byte status into logical and physical statuses."""
    logical_status = (status & 12) >> 2
    physical_status = status & 3
    return logical_status, physical_status


def enforce_placement_group():
    """Enforces all tasks to be launched into placement group."""
    global enforce_placement_group_val
    enforce_placement_group_val = True


def __contains__(rev):
    """Whether a revision number exists."""


def encode_params(decoded_data: str) ->str:
    """ Prepare data for Spreader Interop """
    return decoded_data.replace('|', '|').replace('\r\n', '
')


def save_py_as_rtseq(toplevelfunc, dest_folder):
    """
    Saves a Python function as an RT sequence that is compatible with the Stimulus Profile Editor.

    Args:
        toplevelfunc: the Python function you want to save.
        dest_folder[str]: the folder you want to save the sequence and all its dependencies in.

    Returns:
        The full path to the main sequence file.

    Raises:
        :class:`niveristand.errors.TranslateError`: if the function is not successfully translated.

    """
    from niveristand.clientapi import RealTimeSequence
    seq = RealTimeSequence(toplevelfunc)
    filename = seq.save(dest_folder)
    return filename


def sync():
    """Synchronize computation.

    In DL frameworks such as MXNet and TensorFlow, the computation in operators
    are done asynchronously. This is to synchronize computation and makes sure
    that all computation is complete after this function call.
    """
    pass


def parent():
    """ Returns the feed item parent """


def lower(value):
    """
    Convert value to lowercase if possible

    For example::

        >>> print(lower('HELLO'))
        hello
        >>> print(lower(5))
        5
    """
    try:
        return value.lower()
    except AttributeError:
        return value


def _detect_pybcrypt():
    """
    internal helper which tries to distinguish pybcrypt vs bcrypt.

    :returns:
        True if cext-based py-bcrypt,
        False if ffi-based bcrypt,
        None if 'bcrypt' module not found.

    .. versionchanged:: 1.6.3

        Now assuming bcrypt installed, unless py-bcrypt explicitly detected.
        Previous releases assumed py-bcrypt by default.

        Making this change since py-bcrypt is (apparently) unmaintained and static,
        whereas bcrypt is being actively maintained, and it's internal structure may shift.
    """
    try:
        import bcrypt
    except ImportError:
        return None
    try:
        from bcrypt._bcrypt import __version__
    except ImportError:
        return False
    return True


@classmethod
def use(cls, server_url, timestamp, salt):
    """Create a Nonce instance"""
    raise NotImplementedError('Implement in subclass')


def get_parser_from_config(base_config, attributes, default_parser):
    """
    Checks the various places that the parser option could be set and returns
    the value with the highest precedence, or `default_parser` if no parser was found
    @param base_config: a set of log config options for a logfile
    @param attributes: a set of attributes to apply to a logfile
    @param default_parser: the default parser if no parser setting is found in base_config or attributes
    """
    if 'attributes' in base_config and 'parser' in base_config['attributes']:
        return base_config['attributes']['parser']
    if 'parser' in base_config:
        return base_config['parser']
    if 'parser' in attributes:
        return attributes['parser']
    return default_parser


def getfunc(obj, name=''):
    """Get the function corresponding to name from obj, not the method."""
    if name:
        obj = getattr(obj, name)
    return getattr(obj, '__func__', obj)


@staticmethod
def _get_contract_code():
    """
        Returns the APIC class name for this contract.
        Meant to be overridden by inheriting classes.
        """
    raise NotImplementedError


def create_silence(length):
    """Create a piece of silence."""
    data = bytearray(length)
    i = 0
    while i < length:
        data[i] = 128
        i += 1
    return data


def _slice_required_len(slice_obj):
    """
    Calculate how many items must be in the collection to satisfy this slice

    returns `None` for slices may vary based on the length of the underlying collection
    such as `lst[-1]` or `lst[::]`
    """
    if slice_obj.step and slice_obj.step != 1:
        return None
    if slice_obj.start is None and slice_obj.stop is None:
        return None
    if slice_obj.start and slice_obj.start < 0:
        return None
    if slice_obj.stop and slice_obj.stop < 0:
        return None
    if slice_obj.stop:
        if slice_obj.start and slice_obj.start > slice_obj.stop:
            return 0
        return slice_obj.stop
    return slice_obj.start + 1


def escape_html(text: str):
    """
    return escaped text
    :param text: text to escape
    :return:
    """
    return text.replace('<', '<').replace('>', '>')


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

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

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


def upsert_char(data, newdata, who):
    """
    Similar to upsert_box(), only for a character.
    """
    pass


def _all_valid(links):
    """Iterates over all links, forgetting emtpy registers."""
    for k, v in links.items():
        for i in v:
            yield k, i


def buy_a_for_value(product_listA, give_product, bean):
    """

    :param product_listA: 所有买A赠A的商品列表
    :param bean 活动
    :return: [商品循环值,赠品循环值 ,最大赠数]

    """
    sum_pro = 0
    give_pro_sum = 0
    cursor_max_times = 0
    for_pro = 0
    for_give_pro = 0
    give_pro_number = 0
    value_num = 0
    if bean.value_num == 0:
        value_num = 1
    if bean.max_times == 0:
        bean.max_times = 1
    value_num = bean.value_num
    for product in product_listA:
        sum_pro += product.notOccupiedThree()
    while True:
        if cursor_max_times == bean.max_times:
            return for_pro, for_give_pro, give_pro_number
        if not sum_pro - value_num >= 0:
            return for_pro, for_give_pro, give_pro_number
        sum_pro -= value_num
        for_pro += value_num
        if not sum_pro - bean.give_value >= 0:
            for_give_pro += sum_pro
            give_pro_number += bean.give_value
            return for_pro, for_give_pro, give_pro_number
        sum_pro -= bean.give_value
        for_give_pro += bean.give_value
        give_pro_number += bean.give_value
        cursor_max_times += 1


@classmethod
def parse(cls, string):
    """ Parse zeo++ .res format

        Example res string:

        HKUST-1.res    13.19937 6.74621  13.19937

        Containing the diameters of
         * the largest included sphere
         * the largest free sphere
         * the largest included sphere along free sphere path

        parameters
        ----------
        string: string
          string in res format

        return
        ------
        res: dict
          dictionary of output values
        """
    res = {}
    values = string.split()
    if len(values) != 4:
        raise ValueError('Found more than 4 fields in .res format')
    for i in (0, 1, 2):
        keyword = cls.keywords[i]
        res[keyword] = float(values[i + 1])
        res[keyword + '_unit'] = 'A'
    return res


@staticmethod
def __partition_date_to_path_array(partition_dt):
    """Converts a partition date to an array of partition names
        """
    return [partition_dt.strftime('y%Y'), partition_dt.strftime('m%m'),
        partition_dt.strftime('d%d')]


def ElementWiseSum(*args, **kwargs):
    """Adds all input arguments element-wise.

    .. math::
       add\\_n(a_1, a_2, ..., a_n) = a_1 + a_2 + ... + a_n

    ``add_n`` is potentially more efficient than calling ``add`` by `n` times.

    The storage type of ``add_n`` output depends on storage types of inputs

    - add_n(row_sparse, row_sparse, ..) = row_sparse
    - add_n(default, csr, default) = default
    - add_n(any input combinations longer than 4 (>4) with at least one default type) = default
    - otherwise, ``add_n`` falls all inputs back to default storage and generates default storage

    Defined in src/operator/tensor/elemwise_sum.cc:L155
    This function support variable length of positional input.

    Parameters
    ----------
    args : Symbol[]
        Positional input arguments

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

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


def proper_ptgrp(cryst_ptgrp):
    """
    Returns the proper point group corresponding to a crystallographic point
    group

    Parameters
    ----------------
    cryst_ptgrp: string
    Crystallogrphic point group in Schoenflies notation

    Returns
    ----------
    proper_ptgrp: string
    Proper point group in Schoenflies notation
    """
    if cryst_ptgrp in ['D3', 'D3d']:
        proper_ptgrp = 'D3'
    if cryst_ptgrp in ['D4', 'D4h']:
        proper_ptgrp = 'D4'
    if cryst_ptgrp in ['D6', 'D6h']:
        proper_ptgrp = 'D6'
    if cryst_ptgrp in ['O', 'Oh']:
        proper_ptgrp = 'O'
    return proper_ptgrp


def get_accuracy(n):
    """
    Get the accuracy from a confusion matrix n.

    The mean accuracy is calculated as

    .. math::

        t_i &= \\sum_{j=1}^k n_{ij}\\\\
        acc(n) &= \\frac{\\sum_{i=1}^k n_{ii}}{\\sum_{i=1}^k n_{ii}}

    Parameters
    ----------
    n : dict
        Confusion matrix which has integer keys 0, ..., nb_classes - 1;
        an entry n[i][j] is the count how often class i was classified as
        class j.

    Returns
    -------
    float
        accuracy (in [0, 1])

    References
    ----------
    .. [1] Martin Thoma (2016): A Survey of Semantic Segmentation,
       http://arxiv.org/abs/1602.06541

    Examples
    --------
    >>> n = {0: {0: 10, 1: 2}, 1: {0: 5, 1: 83}}
    >>> get_accuracy(n)
    0.93
    """
    return float(n[0][0] + n[1][1]) / (n[0][0] + n[1][1] + n[0][1] + n[1][0])


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

    The ".dev0" means dirty.

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


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


def get_encoder_type():
    """Return a short string that describes the type of this encoder.

        There is required to be a global table of encoder classes. This method
        returns an index into this table; the value at this index is an
        encoder class, and this encoder is an instance of that class.
        """


def is_retryable_error(error):
    """
    Determines whether the given error is retryable or not.
    :param error: (:class:`~hazelcast.exception.HazelcastError`), the given error.
    :return: (bool), ``true`` if the given error is retryable, ``false`` otherwise.
    """
    return hasattr(error, 'retryable')


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

        :param TeamMergeRequestReminderShownToSecondaryTeamDetails val:
        :rtype: EventDetails
        """
    return cls('team_merge_request_reminder_shown_to_secondary_team_details',
        val)


def locateResource(request):
    """
        Locate a resource that will handle the request.

        @param request: The publish-subscribe request.
        @type request: L{wokkel.pubsub.PubSubRequest}
        """


def generate_client_identifier(request):
    """
    Returns a client identifier based on a request, used for help with fraud detection.
    """
    user_agent = request.META.get('HTTP_USER_AGENT', '')
    return 'useragent=%(user_agent)s' % {'user_agent': user_agent}


@staticmethod
def _get_bound_repr(bound):
    """Return a string representation of a boundary slice.

        Args:
            bound: A slice object.

        Returns:
            A string representing the slice.
        """
    return '{}:{}'.format(bound.start or '', bound.stop or '')


def generate_tss_flanks(tss, flank_distance: int=1000, flank_size: int=100):
    """Generate coordinates of TSS flanks

    Parameters
    ----------
    tss
        an iterable containing coordinates of TSS's
    flank_distance : int
        distance from tss of outer ends of flanks
    flank_size : int
        size of flanks (for determining average depth)

    Yields
    ------
    tuple
        The coordinates of a TSS flank and the corresponding TSS, in the form:
        chrom, flank_start, flank_end, tss_pos
    """
    for chrom, pos in tss:
        if pos >= flank_distance:
            yield chrom, pos - flank_distance, pos - flank_distance + flank_size, pos
            yield chrom, pos - 1, pos, pos
            yield chrom, pos + flank_distance - flank_size, pos + flank_distance, pos


def binary_partitions(n):
    """
    Generates the binary partition of n.

    A binary partition consists only of numbers that are
    powers of two. Each step reduces a 2**(k+1) to 2**k and
    2**k. Thus 16 is converted to 8 and 8.

    References
    ==========

    * TAOCP 4, section 7.2.1.5, problem 64

    Examples
    ========

    >>> for i in binary_partitions(5):
    ...     print(i)
    ...
    [4, 1]
    [2, 2, 1]
    [2, 1, 1, 1]
    [1, 1, 1, 1, 1]

    """
    from math import ceil, log
    pow = 2 ** ceil(log(n, 2))
    sum = 0
    partition = []
    while pow:
        if sum + pow <= n:
            partition.append(pow)
            sum += pow
        pow >>= 1
    last_num = len(partition) - 1 - (n & 1)
    while last_num >= 0:
        yield partition
        if partition[last_num] == 2:
            partition[last_num] = 1
            partition.append(1)
            last_num -= 1
            continue
        partition.append(1)
        partition[last_num] >>= 1
        x = partition[last_num + 1] = partition[last_num]
        last_num += 1
        while x > 1:
            if x <= len(partition) - last_num - 1:
                del partition[-x + 1:]
                last_num += 1
                partition[last_num] = x
            else:
                x >>= 1
    yield [1] * n


def robust_add(a, b):
    """Add numbers a and b, treating None as 0"""
    if a is None:
        a = 0
    if b is None:
        b = 0
    return a + b


def corrgroups60__gbm():
    """ Gradient Boosted Trees
    """
    import xgboost
    return xgboost.XGBRegressor(max_depth=6, n_estimators=50, learning_rate
        =0.1, n_jobs=8, random_state=0)


def rip_move_fill(MESH_OT_rip=None, TRANSFORM_OT_translate=None):
    """Rip-fill polygons and move the result

    :param MESH_OT_rip: Rip, Disconnect vertex or edges from connected geometry
    :param TRANSFORM_OT_translate: Translate, Translate (move) selected items
    """
    pass


def decode_support_levels(encoded: str, for_sheet: bool=False):
    """
    Decodes the support levels back into a human-readable format
    :param encoded: The encoded support level
    :param for_sheet: Changes the support levels into the format used in the
                      data sheet (e.g. C1 -> CC)
    :return: The decoded support level
    """
    if for_sheet:
        return encoded.replace('1', 'C').replace('2', 'B').replace('3', 'A')
    else:
        return encoded.replace('1', 'C+').replace('2', 'B+').replace('3', 'A+')


def SizeBenefitAccDth(t):
    """Accidental death benefit per policy"""
    return 0


def format_parameter(*args, **kwargs):
    """Format a parameter string

    >>> format_parameter(ex=['example', 'one'])
    '"ex=example:one"'
    >>> format_parameter('one', 'two', 'three')
    'one:two:three'

    You can mix the arguments und keyword arguments.
    """
    parameter_list = []
    for value in args:
        if value is not None:
            parameter_list.append(str(value))
    for key, value in kwargs.items():
        try:
            if not value:
                parameter_list.append(key)
            else:
                parameter_list.append('='.join([key, value]))
        except TypeError:
            values = ':'.join(kwargs[key])
            parameter_list.append('='.join([key, values]))
    result = ':'.join(parameter_list)
    if kwargs:
        return '"%s"' % result
    return result


def set_run_value(deployments_dict: dict, key_parts: list, value: str) ->None:
    """Create 'runs' list of dicts if it does not exist."""
    deployments_dict[key_parts[1]].setdefault('runs', [{}])[0][key_parts[2]
        ] = value


def _merge(arr, temp, left, mid, right):
    """
    Merges two sorted arrays and calculates the inversion count.

    Helper function for calculating inversions. This method is
    for internal use only.
    """
    i = k = left
    j = mid
    inv_count = 0
    while i < mid and j <= right:
        if arr[i] < arr[j]:
            temp[k] = arr[i]
            k += 1
            i += 1
        else:
            temp[k] = arr[j]
            k += 1
            j += 1
            inv_count += mid - i
    while i < mid:
        temp[k] = arr[i]
        k += 1
        i += 1
    if j <= right:
        k += right - j + 1
        j += right - j + 1
        arr[left:k + 1] = temp[left:k + 1]
    else:
        arr[left:right + 1] = temp[left:right + 1]
    return inv_count


def post_process(table, post_processors):
    """Applies the list of post processing methods if any"""
    table_result = table
    for processor in post_processors:
        table_result = processor(table_result)
    return table_result


def __iter__():
    """Creates an iterator for the contents of the batch."""


@classmethod
def ignore(cls, data):
    """"A subselection algorithm to keep all

        This algorithm doesn't do anything except mimic others.

        It will not discard any decoys and keep all!!

        Parameters
        ----------
        data : list, tuple
           A 1D array of scores

        Returns
        -------
        list
           The decoy indices to keep
        list
           The decoy indices to throw

        """
    data = cls._numpify(data)
    return cls.cutoff(data, cutoff=0)


def plotPanelScreenshot(panel, filename):
    """Capture a screenshot of the contents of the given :class:`.PlotPanel`
    or :class:`.PlotPanel`, saving it to the given ``filename``.
    """
    panel.getFigure().savefig(filename)


def _sub(lhs=None, rhs=None, out=None, name=None, **kwargs):
    """Subtracts arguments element-wise.

    The storage type of ``elemwise_sub`` output depends on storage types of inputs

       - elemwise_sub(row_sparse, row_sparse) = row_sparse
       - elemwise_sub(csr, csr) = csr
       - elemwise_sub(default, csr) = default
       - elemwise_sub(csr, default) = default
       - elemwise_sub(default, rsp) = default
       - elemwise_sub(rsp, default) = default
       - otherwise, ``elemwise_sub`` generates output with default storage

    Parameters
    ----------
    lhs : NDArray
        first input
    rhs : NDArray
        second input

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

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


def get_explicit_from_implicit(seekpath_output, reference_distance):
    """
    Given the output of ``get_path`` by seekpath, compute an "explicit" path,
    i.e. instead of just giving the endpoints and their coordinates, compute
    a full list of kpoints

    :param seekpath_output: a dictionary, the output of ``seekpath.get_path``

    :param reference_distance: a reference target distance between neighboring
        k-points in the path, in units of 1/ang. The actual value will be as
        close as possible to this value, to have an integer number of points in
        each path.
    """
    import numpy as np
    retdict = {}
    kpoints_rel = []
    kpoints_labels = []
    kpoints_linearcoord = []
    previous_linearcoord = 0.0
    segments = []
    for start_label, stop_label in seekpath_output['path']:
        start_coord = np.array(seekpath_output['point_coords'][start_label])
        stop_coord = np.array(seekpath_output['point_coords'][stop_label])
        start_coord_abs = np.dot(start_coord, seekpath_output[
            'reciprocal_primitive_lattice'])
        stop_coord_abs = np.dot(stop_coord, seekpath_output[
            'reciprocal_primitive_lattice'])
        segment_length = np.linalg.norm(stop_coord_abs - start_coord_abs)
        num_points = max(2, int(segment_length / reference_distance))
        segment_linearcoord = np.linspace(0.0, segment_length, num_points)
        segment_start = len(kpoints_labels)
        for i in range(num_points):
            if i == 0:
                if kpoints_labels:
                    if kpoints_labels[-1] == start_label:
                        segment_start -= 1
                        continue
            kpoints_rel.append(start_coord + (stop_coord - start_coord) *
                float(i) / float(num_points - 1))
            if i == 0:
                kpoints_labels.append(start_label)
            elif i == num_points - 1:
                kpoints_labels.append(stop_label)
            else:
                kpoints_labels.append('')
            kpoints_linearcoord.append(previous_linearcoord +
                segment_linearcoord[i])
        previous_linearcoord += segment_length
        segment_end = len(kpoints_labels)
        segments.append((segment_start, segment_end))
    retdict['kpoints_rel'] = np.array(kpoints_rel)
    retdict['kpoints_linearcoord'] = np.array(kpoints_linearcoord)
    retdict['kpoints_labels'] = kpoints_labels
    retdict['kpoints_abs'] = np.dot(retdict['kpoints_rel'], seekpath_output
        ['reciprocal_primitive_lattice'])
    retdict['segments'] = segments
    return retdict


@classmethod
def _get_validated_genome_version(cls, input_genome_build_version):
    """ Make sure genome version is acceptable """
    if input_genome_build_version is None:
        result = cls.DEFAULT_GENOME_VERSION
    elif input_genome_build_version not in cls.SUPPORTED_GENOME_BUILD_VERSIONS:
        str_of_acceptable_versions = ', '.join(cls.
            SUPPORTED_GENOME_BUILD_VERSIONS)
        raise ValueError(
            "Input genome build version '{0}' is not recognized. Supported builds are {1}"
            .format(input_genome_build_version, str_of_acceptable_versions))
    else:
        result = input_genome_build_version
    return result


def node_attribute_writer(model, target, value):
    """Write ``value`` to ``target`` node.attrs key on ``model``.
    """
    model.attrs[target] = value


def identify_initial_engine_temperature(engine_coolant_temperatures):
    """
    Identifies initial engine temperature [°C].

    :param engine_coolant_temperatures:
        Engine coolant temperature vector [°C].
    :type engine_coolant_temperatures: numpy.array

    :return:
        Initial engine temperature [°C].
    :rtype: float
    """
    return float(engine_coolant_temperatures[0])


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


def start(**kwargs):
    """Called to start the task.

        :keyword pipe_connection: the connection used to communicate
            with the stoqserver api. Will only be present if
            :attr:`.handle_actions` is ``True``
        """


def __pyexpander_helper3(*args, **kwargs):
    """a helper function needed at runtime.

    This evaluates unnamed and named arguments.
    """
    return args, kwargs


def can_edit(key):
    """Returns if the user has permission to edit the given feature"""


def arg_byref(args, offset=-1):
    """Returns the pointer argument's by-reference value."""
    return args[offset]._obj.value


@staticmethod
def _circleEquation(pt1, pt2, pt3):
    """Circle equation from 3 (x, y) points

        :return: Position of the center of the circle and the radius
        :rtype: Tuple[Tuple[float,float],float]
        """
    x, y, z = complex(*pt1), complex(*pt2), complex(*pt3)
    w = z - x
    w /= y - x
    c = (x - y) * (w - abs(w) ** 2) / 2.0j / w.imag - x
    return (-c.real, -c.imag), abs(c + x)


def _Plus(lhs=None, rhs=None, name=None, attr=None, out=None, **kwargs):
    """Adds arguments element-wise.

    The storage type of ``elemwise_add`` output depends on storage types of inputs

       - elemwise_add(row_sparse, row_sparse) = row_sparse
       - elemwise_add(csr, csr) = csr
       - elemwise_add(default, csr) = default
       - elemwise_add(csr, default) = default
       - elemwise_add(default, rsp) = default
       - elemwise_add(rsp, default) = default
       - otherwise, ``elemwise_add`` generates output with default storage

    Parameters
    ----------
    lhs : Symbol
        first input
    rhs : Symbol
        second input

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

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


def getMemberId():
    """This exists only for a basic user/group API compatibility
        """


def setHome(home):
    """Move to a different home."""


def pytest_bug_report_teststatus(report, report_bug):
    """
    Called before output
    :param report: Base pytest report
    :param report_bug: SkipBug or FailBug or PassBug
    """


def midiNoteToDegree(value):
    """Converts a MIDI note to an octave.degree notation."""
    oct = int(value / 12)
    deg = value % 12
    return '%d.%02d' % (oct, deg)


def create_circle(bm: 'bmesh.types.BMesh', cap_ends: bool, cap_tris: bool,
    segments: int, diameter: float, matrix: 'mathutils.Matrix', calc_uvs: bool
    ) ->dict:
    """Creates a Circle.

    :param bm: The bmesh to operate on.
    :type bm: 'bmesh.types.BMesh'
    :param cap_ends: whether or not to fill in the ends with faces
    :type cap_ends: bool
    :param cap_tris: fill ends with triangles instead of ngons
    :type cap_tris: bool
    :param segments: Undocumented.
    :type segments: int
    :param diameter: diameter of one end
    :type diameter: float
    :param matrix: matrix to multiply the new geometry with
    :type matrix: 'mathutils.Matrix'
    :param calc_uvs: calculate default UVs
    :type calc_uvs: bool
    :return:  verts: output vertstype list of (bmesh.types.BMVert)
    """
    pass


def get_coherent_next_tag(prev_label: str, cur_label: str) ->str:
    """
    Generate a coherent tag, given previous tag and current label.
    """
    if cur_label == 'O':
        return 'O'
    if prev_label == cur_label:
        return f'I-{cur_label}'
    else:
        return f'B-{cur_label}'


def list_dead_letter_source_queues(QueueUrl=None):
    """
    Returns a list of your queues that have the RedrivePolicy queue attribute configured with a dead letter queue.
    For more information about using dead letter queues, see Using Amazon SQS Dead Letter Queues in the Amazon SQS Developer Guide .
    See also: AWS API Documentation

    :example: response = client.list_dead_letter_source_queues(
        QueueUrl='string'
    )

    :type QueueUrl: string
    :param QueueUrl: [REQUIRED]
            The URL of a dead letter queue.
            Queue URLs are case-sensitive.

    :rtype: dict
    :return: {
        'queueUrls': [
            'string',
        ]
    }

    """
    pass


@classmethod
def get_query_for_field(cls, condition):
    """
        Returns Q object with query for parsed condition
        """
    field = cls.get_field_name_to_field().get(condition.name)
    if field is None:
        field = cls._field_source_to_search_field_instance.get(condition.name)
    if field is None:
        field_type = getattr(cls.get_full_mapping().get(condition.name),
            'field_type', None)
        field = cls._field_type_to_field_class.get(field_type, cls.
            _default_field)()
    return field.get_query(condition)


def circuit_new(circuit):
    """A new circuit has been created.  You'll always get one of
        these for every Circuit even if it doesn't go through the "launched"
        state."""


def make_client(instance):
    """Returns a client to the ClientManager

    Called to instantiate the requested client version.  instance has
    any available auth info that may be required to prepare the client.

    :param ClientManager instance: The ClientManager that owns the new client
    """
    return None


def findSources(target, maxDepth=1, filter=None):
    """Given a target, iterate over objects that point to it.

        maxDepth is the number of relationships through which the search
        should walk transitively.  It must be a positive integer.

        filter is an optional callable that takes a relationship and returns
        a boolean True value if it should be included, and a False if not.
        """


def has_level_label(label_flags, vmin):
    """
    Returns true if the ``label_flags`` indicate there is at least one label
    for this level.

    if the minimum view limit is not an exact integer, then the first tick
    label won't be shown, so we must adjust for that.
    """
    if label_flags.size == 0 or label_flags.size == 1 and label_flags[0
        ] == 0 and vmin % 1 > 0.0:
        return False
    else:
        return True


def propertx(fct):
    """
        Decorator to simplify the use of property.
        Like @property for attrs who need more than a getter.
        For getter only property use @property.

        adapted from http://code.activestate.com/recipes/502243/
    """
    arg = [None, None, None, None]
    for i, f in enumerate(fct()):
        arg[i] = f
    if not arg[3]:
        arg[3] = fct.__doc__
    return property(*arg)


@classmethod
def set_E_G_nu(cls, E, G, nu):
    """\\f[ G = \\frac{E}{2 (1+\\nu)} \\f]"""
    if G is None and E is None:
        raise ValueError('G=%s E=%s cannot both be None' % (G, E))
    elif E is not None and G is not None and nu is not None:
        pass
    elif E is not None and nu is not None:
        G = E / 2.0 / (1 + nu)
    elif G is not None and nu is not None:
        E = 2 * (1 + nu) * G
    elif G is not None and E is not None:
        nu = E / (2 * G) - 1.0
    elif G is None and nu is None:
        G = 0.0
        nu = 0.0
    elif E is None and nu is None:
        E = 0.0
        nu = 0.0
    else:
        msg = 'G=%s E=%s nu=%s' % (G, E, nu)
        raise ValueError(msg)
    return E, G, nu


def get_secure_cookie(name, value=None):
    """Returns a signed cookie if it validates, or None. Call to this
        method is valid only after :meth:`handle` is called. Refer to
        :class:`IHTTPCookie` interface specification to learn more about
        secure-signing cookies. """


def bool_str(v):
    """Convert a boolean to a string."""
    return 'Yes' if v else 'No'


def uninstall(context):
    """Uninstall script"""


@classmethod
def schema(cls):
    """Override this in a subclass to define model <=> API mappings"""
    raise NotImplementedError()


def resolve_path_variables_of_vs(context, path_with_vars):
    """ Evaluates paths with visual studio variables """
    path_with_vars = path_with_vars.replace('$(ProjectDir)', './')
    path_with_vars = path_with_vars.replace('$(SolutionDir)', context.
        solution_path)
    return path_with_vars


def read_asxml(path=None):
    """
    - Reads a big vasprun.xml file into memory once and then apply commands.
    If current folder contains `vasprun.xml` file, it automatically picks it.

    - **Parameters**
        - path     : Path/To/vasprun.xml

    - **Returns**
        - xml_data : Xml object to use in other functions
    """
    if path == None:
        path = './vasprun.xml'
    import xml.etree.ElementTree as ET
    if not path:
        return print('vasprun.xml not found.')
    else:
        tree = ET.parse(path)
        xml_data = tree.getroot()
        return xml_data