def _tef_P(P):
    """Define the boundary between Region 3e-3f, T=f(P)

    Parameters
    ----------
    P : float
        Pressure, [MPa]

    Returns
    -------
    T : float
        Temperature, [K]

    References
    ----------
    IAPWS, Revised Supplementary Release on Backward Equations for Specific
    Volume as a Function of Pressure and Temperature v(p,T) for Region 3 of the
    IAPWS Industrial Formulation 1997 for the Thermodynamic Properties of Water
    and Steam, http://www.iapws.org/relguide/Supp-VPT3-2016.pdf, Eq. 3

    Examples
    --------
    >>> _tef_P(40)
    713.9593992
    """
    return 3.727888004 * (P - 22.064) + 647.096


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


def _derg3(x):
    """Return the derivative function g3(x) for Trefethen transformation."""
    return 1 / 53089 * (40320 + 20160 * x ** 2 + 15120 * x ** 4 + 12600 * x **
        6 + 11025 * x ** 8)


def chromaticity_to_XYZ(white, red, green, blue):
    """From the "CalRGB Color Spaces" section of "PDF Reference", 6th ed."""
    xW, yW = white
    xR, yR = red
    xG, yG = green
    xB, yB = blue
    R = G = B = 1.0
    z = yW * ((xG - xB) * yR - (xR - xB) * yG + (xR - xG) * yB)
    YA = yR / R * ((xG - xB) * yW - (xW - xB) * yG + (xW - xG) * yB) / z
    XA = YA * xR / yR
    ZA = YA * ((1 - xR) / yR - 1)
    YB = -yG / G * ((xR - xB) * yW - (xW - xB) * yR + (xW - xR) * yB) / z
    XB = YB * xG / yG
    ZB = YB * ((1 - xG) / yG - 1)
    YC = yB / B * ((xR - xG) * yW - (xW - xG) * yR + (xW - xR) * yG) / z
    XC = YC * xB / yB
    ZC = YC * ((1 - xB) / yB - 1)
    XW = XA * R + XB * G + XC * B
    YW = YA * R + YB * G + YC * B
    ZW = ZA * R + ZB * G + ZC * B
    return (XW, YW, ZW), (XA, YA, ZA), (XB, YB, ZB), (XC, YC, ZC)


def vlookup_day(value, df, column):
    """
    Returns the dataframe index of a given value
    """
    return df[column].loc[value]


def build_instance(Model, data, db):
    """
    Build a model instance.

    If the model instance doesn't have a primary key and the model supports
    natural keys, try to retrieve it from the database.
    """
    obj = Model(**data)
    if obj.pk is None and hasattr(Model, 'natural_key') and hasattr(Model.
        _default_manager, 'get_by_natural_key'):
        natural_key = obj.natural_key()
        try:
            obj.pk = Model._default_manager.db_manager(db).get_by_natural_key(*
                natural_key).pk
        except Model.DoesNotExist:
            pass
    return obj


def process_soa(data, template):
    """
    Replace {SOA} in template with a set of serialized SOA records
    """
    record = template[:]
    if data is not None:
        assert len(data) == 1, 'Only support one SOA RR at this time'
        data = data[0]
        soadat = []
        domain_fields = ['mname', 'rname']
        param_fields = ['serial', 'refresh', 'retry', 'expire', 'minimum']
        for f in (domain_fields + param_fields):
            assert f in list(data.keys()), "Missing '%s' (%s)" % (f, data)
        data_name = str(data.get('name', '@'))
        soadat.append(data_name)
        if data.get('ttl') is not None:
            soadat.append(str(data['ttl']))
        soadat.append('IN')
        soadat.append('SOA')
        for key in domain_fields:
            value = str(data[key])
            soadat.append(value)
        soadat.append('(')
        for key in param_fields:
            value = str(data[key])
            soadat.append(value)
        soadat.append(')')
        soa_txt = ' '.join(soadat)
        record = record.replace('{soa}', soa_txt)
    else:
        record = record.replace('{soa}', '')
    return record


def describe_interconnects(interconnectId=None):
    """
    Returns a list of interconnects owned by the AWS account.
    If an interconnect ID is provided, it will only return this particular interconnect.
    See also: AWS API Documentation

    :example: response = client.describe_interconnects(
        interconnectId='string'
    )

    :type interconnectId: string
    :param interconnectId: The ID of the interconnect.
            Example: dxcon-abc123

    :rtype: dict
    :return: {
        'interconnects': [
            {
                'interconnectId': 'string',
                'interconnectName': 'string',
                'interconnectState': 'requested'|'pending'|'available'|'down'|'deleting'|'deleted',
                'region': 'string',
                'location': 'string',
                'bandwidth': 'string',
                'loaIssueTime': datetime(2015, 1, 1),
                'lagId': 'string',
                'awsDevice': 'string'
            },
        ]
    }

    """
    pass


def offset2line(offset, linestarts):
    """linestarts is expected to be a *list) of (offset, line number)
    where both offset and line number are in increasing order.
    Return the closes line number at or below the offset.
    If offset is less than the first line number given in linestarts,
    return line number 0.
    """
    if len(linestarts) == 0 or offset < linestarts[0][0]:
        return 0
    low = 0
    high = len(linestarts) - 1
    mid = (low + high + 1) // 2
    while low <= high:
        if linestarts[mid][0] > offset:
            high = mid - 1
        elif linestarts[mid][0] < offset:
            low = mid + 1
        else:
            return linestarts[mid][1]
        mid = (low + high + 1) // 2
        pass
    if mid >= len(linestarts):
        return linestarts[len(linestarts) - 1][1]
    return linestarts[high][1]


def _buildhdr(keymap, rec):
    """
    Map attributes in rec into a dictionary, with keyname translations applied.

    Raises
    ------
    AttributeError
        rec does not have attributes (is None?)

    """
    hdr = {}
    for key1, key2 in keymap.items():
        try:
            hdr[key1] = getattr(rec, key2)
        except AttributeError:
            pass
    return hdr


@staticmethod
def __get_class(clazz):
    """
        Loads Python class from its name.
        """
    parts = clazz.split('.')
    module = '.'.join(parts[:-1])
    m = __import__(module)
    for comp in parts[1:]:
        m = getattr(m, comp)
    return m


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


def event_receiver(event_type, details):
    """This is the callback that (in this example) doesn't do much..."""
    print("Recieved event '%s'" % event_type)
    print('Details = %s' % details)


def stream2dict(stream_list):
    """Convert stream list into stream dict

    Parameters
    ----------
    stream_list : list
        Stream in list form (list of dicts), as returned by Strava API v3

    Returns
    -------
    stream_dict : dict
        Stream in dict form, with key set to *stream name* and value set to the actual stream list.
        In this form, the stream is ready to be consumed by pandas
    """
    stream_dict = {}
    for s in stream_list:
        stream_dict.update({s['type']: s['data']})
    return stream_dict


@classmethod
def run_hooks(cls, hook_type, *args, **kwargs):
    """Run all hooks of specified type.

        :param cls: class that registers hooks
        :param hook_type: hook type, e.g., '__pre_parse_args__'
        :param args: args to be passed to every hook function
        :param kwargs: kwargs to be passed to every hook function
        """
    hook_funcs = cls._hooks_map.get(hook_type) or []
    for hook_func in hook_funcs:
        hook_func(*args, **kwargs)


@classmethod
def string_list_file(cls, filename):
    """
        Read a list of string values from a file.

        The file format is:

         - # anywhere in the line begins a comment
         - leading and trailing spaces are ignored
         - empty lines are ignored
         - strings cannot span over a single line

        @type  filename: str
        @param filename: Name of the file to read.

        @rtype:  list
        @return: List of integers and strings read from the file.
        """
    count = 0
    result = list()
    fd = open(filename, 'r')
    for line in fd:
        count = count + 1
        if '#' in line:
            line = line[:line.find('#')]
        line = line.strip()
        if line:
            result.append(line)
    return result


def tktIsResolved(tkt):
    """
    Returns True if the RITM is resolved, False otherwise.
    """
    return False


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

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


def alter_occupancy(fhandle, occupancy):
    """Sets the occupancy column in all ATOM/HETATM records to a given value.
    """
    records = 'ATOM', 'HETATM'
    occupancy = '{0:>6.2f}'.format(occupancy)
    for line in fhandle:
        if line.startswith(records):
            yield line[:54] + occupancy + line[60:]
        else:
            yield line


@classmethod
def get_name(cls):
    """ Returns the name of the hook.
		"""
    return 'plot'


def is_watchdog_supported():
    """ Return ``True`` if watchdog is available."""
    try:
        import watchdog
    except ImportError:
        return False
    return True


def _format_local(local_path, local_is_path):
    """Format a path for log output"""
    if local_is_path:
        return local_path
    else:
        return getattr(local_path, 'name', '<file obj>')


def invert_colors(clip):
    """ Returns the color-inversed clip.

    The values of all pixels are replaced with (255-v) or (1-v) for masks
    Black becomes white, green becomes purple, etc.
    """
    maxi = 1.0 if clip.ismask else 255
    return clip.fl_image(lambda f: maxi - f)


def get_next_tx_index(db):
    """Return index of next transaction."""
    cursor = db.cursor()
    txes = list(cursor.execute(
        'SELECT * FROM transactions WHERE tx_index = (SELECT MAX(tx_index) from transactions)'
        ))
    if txes:
        assert len(txes) == 1
        tx_index = txes[0]['tx_index'] + 1
    else:
        tx_index = 0
    cursor.close()
    return tx_index


@classmethod
def create(klass):
    """ Factory method to create a datastore with the
        full address space initialized to 0x00

        :returns: An initialized datastore
        """
    return klass([0] * 65536)


def _parse_address(address):
    """Parse a colon-separted address string into constituent parts.

    Given a string like ``foo:1234`` this will split it into a tuple
    containing ``foo`` and ``1234``, where ``1234`` is an integer.
    If the port is not given in the address string then it will default
    to 27015.

    .. note::
        This doesn't check that the host component of the address
        is either a valid dotted-decimal IPv4 address or DNS label.

    :raises ValueError: if the given port does not appear
        to be a valid port number.

    :returns: a tuple containing the host as a string and the port as
        an integer.
    """
    host_and_port = address.split(':', 1)
    if len(host_and_port) == 2:
        host, port_string = host_and_port
    else:
        host = host_and_port[0]
        port_string = '27015'
    try:
        port = int(port_string)
    except ValueError:
        raise ValueError('Could not parse address port {!r} as a number'.
            format(port_string))
    if port <= 0 or port > 65535:
        raise ValueError('Port number must be in the range 1 to 65535')
    return host, port


def start_of_chunk(prev_tag, tag, prev_type, type_):
    """Checks if a chunk started between the previous and current word.

    Args:
        prev_tag: previous chunk tag.
        tag: current chunk tag.
        prev_type: previous type.
        type_: current type.

    Returns:
        chunk_start: boolean.
    """
    chunk_start = False
    if tag == 'B':
        chunk_start = True
    if tag == 'S':
        chunk_start = True
    if prev_tag == 'E' and tag == 'E':
        chunk_start = True
    if prev_tag == 'E' and tag == 'I':
        chunk_start = True
    if prev_tag == 'S' and tag == 'E':
        chunk_start = True
    if prev_tag == 'S' and tag == 'I':
        chunk_start = True
    if prev_tag == 'O' and tag == 'E':
        chunk_start = True
    if prev_tag == 'O' and tag == 'I':
        chunk_start = True
    if tag != 'O' and tag != '.' and prev_type != type_:
        chunk_start = True
    return chunk_start


@staticmethod
def merge(reports):
    """Method used to merge multiple reports together. Here it simply
        concatenates the lists of values saved in the different reports.

        Parameters
        ----------
        reports : list of dict
            List of reports that need to be concatenated together

        Returns
        -------
        report : dict
            Final report with all concatenated values
        """
    report = reports[0]
    keys_report = list(reports[0].keys())
    for other_report in reports[1:]:
        for key in keys_report:
            report[key] += other_report[key]
    return report


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 repr_with_newlines(string):
    """
  return the string, passed through repr(), but with
  newlines intact.

  Thus the string "new
line" becomes not "new\\nline" but instead
  a string with a literal newline in it: '''new
line'''
  """
    if '\n' not in string:
        return repr(string)
    else:
        reprd = repr(string)
        quote_type = reprd[0]
        newlines_returned = reprd.replace('\\n', '\n')
        multiline_quotes = quote_type * 2 + newlines_returned + quote_type * 2
        return multiline_quotes


def simpson_d(num_tokens, freq_spectrum):
    """Calculate Simpson’s D.

    Parameters:
        num_tokens (int): Absolute number of tokens.
        freq_spectrum (pd.Series): Counted occurring frequencies.
    """
    a = freq_spectrum.values / num_tokens
    b = freq_spectrum.index.values - 1
    return (freq_spectrum.values * a * (b / (num_tokens - 1))).sum()


def _py2ri(obj):
    """ Dummy function for py2ri.

    This function will convert Python objects into rpy2.rinterface
    (ri) objects.
    """
    raise NotImplementedError(
        "Conversion 'py2ri' not defined for objects of type '%s'" % str(
        type(obj)))


def func(user_func, q, *args):
    """ Runs the user's function and puts return value in queue """
    value = user_func(*args)
    q.put(value)


def intersect_line_line_2d(lineA_p1: 'mathutils.Vector', lineA_p2:
    'mathutils.Vector', lineB_p1: 'mathutils.Vector', lineB_p2:
    'mathutils.Vector') ->'mathutils.Vector':
    """Takes 2 segments (defined by 4 vectors) and returns a vector for their point of intersection or None.

    :param lineA_p1: First point of the first line
    :type lineA_p1: 'mathutils.Vector'
    :param lineA_p2: Second point of the first line
    :type lineA_p2: 'mathutils.Vector'
    :param lineB_p1: First point of the second line
    :type lineB_p1: 'mathutils.Vector'
    :param lineB_p2: Second point of the second line
    :type lineB_p2: 'mathutils.Vector'
    :return:  The point of intersection or None when not found
    """
    pass


def prepare_lookup_value(key, value):
    """
    Returns a lookup value prepared to be used in queryset filtering.
    """
    if key.endswith('__in'):
        value = value.split(',')
    if key.endswith('__isnull'):
        if value.lower() in ('', 'false'):
            value = False
        else:
            value = True
    return value


def _raise(message: str) ->None:
    """Raise an exception in a template."""
    raise Exception(message)


def parse_step(checkdict):
    """Given a checkdict for a range widget return the step as string value."""
    return checkdict.get('step', '1')


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


@classmethod
def detect(cls, old_config, new_config):
    """Detect if commit hash in `new_config` differs from `old_config`"""
    old_hash_commit = old_config['metadata'].get('VCS', None)
    new_hash_commit = new_config['metadata'].get('VCS')
    if old_hash_commit is None or old_hash_commit != new_hash_commit:
        yield cls(old_config, new_config)


def _is_list(s):
    """Check a value is a CSV list."""
    if s[0] == '[' and s[-1] == ']':
        return True
    else:
        return False


@classmethod
def from_dict(cls, pattern_dict):
    """
        Loads an instance from a dictionary
        :param pattern_dict: a dictionary holding the pattern's parameters
        :return: a Pattern instance
        """
    return cls(**pattern_dict)


def _row_value(row):
    """ A function to extract the contents of the 'value' key in a Row
        object. This function exists because this is a very common situation.
    """
    if row is None:
        out = None
    else:
        out = row['value']
    return out


def handle_extensions(extensions):
    """
    Organizes multiple extensions that are separated with commas or passed by
    using --extension/-e multiple times.

    For example: running 'django-admin makemessages -e js,txt -e xhtml -a'
    would result in an extension list: ['.js', '.txt', '.xhtml']

    >>> handle_extensions(['.html', 'html,js,py,py,py,.py', 'py,.py'])
    {'.html', '.js', '.py'}
    >>> handle_extensions(['.html, txt,.tpl'])
    {'.html', '.tpl', '.txt'}
    """
    ext_list = []
    for ext in extensions:
        ext_list.extend(ext.replace(' ', '').split(','))
    for i, ext in enumerate(ext_list):
        if not ext.startswith('.'):
            ext_list[i] = '.%s' % ext_list[i]
    return set(ext_list)


@classmethod
def _from_dict(cls, _dict):
    """Initialize a ActivityTracking object from a json dictionary."""
    args = {}
    validKeys = ['read_data_events', 'write_data_events',
        'activity_tracker_crn']
    badKeys = set(_dict.keys()) - set(validKeys)
    if badKeys:
        raise ValueError(
            'Unrecognized keys detected in dictionary for class ActivityTracking: '
             + ', '.join(badKeys))
    if 'read_data_events' in _dict:
        args['read_data_events'] = _dict.get('read_data_events')
    if 'write_data_events' in _dict:
        args['write_data_events'] = _dict.get('write_data_events')
    if 'activity_tracker_crn' in _dict:
        args['activity_tracker_crn'] = _dict.get('activity_tracker_crn')
    return cls(**args)


def query(df, query):
    """
    Filter a dataset under a condition

    ---

    ### Parameters

    *mandatory :*
    - query (*str*): your query as a string (see [pandas doc](
    http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.query.html#pandas.DataFrame.query))

    ---

    ### Example

    **Input**

    | variable |   wave  |  year    | value |
    |:--------:|:-------:|:--------:|:-----:|
    |   toto   |  wave 1 |  2014    |  300  |
    |   toto   |  wave 1 |  2015    |  250  |
    |   toto   |  wave 1 |  2015    |  100  |
    |   toto   |  wave 1 |  2016    |  450  |

    ```cson
    query: 'value > 350'
    ```

    **Output**

    | variable |   wave  |  year    | value |
    |:--------:|:-------:|:--------:|:-----:|
    |   toto   |  wave 1 |  2016    |  450  |
    """
    df = df.query(query)
    return df


@classmethod
def check(cls, result: dict):
    """Return ``data`` or raise ``errors``."""
    for error in result.get('errors', ()):
        raise cls.Error(error)
    return result.get('data')


@classmethod
def from_array(cls, coords_array):
    """Create timeseries point coords from numpy array of coordinates.

        Parameters
        ----------
        coords_array : np.ndarray
            Numpy array of coordinates.
        """
    return cls(coords_array[(0), :], coords_array[(1), :])


def logical_not(attrs, inputs, proto_obj):
    """Logical not of two input arrays."""
    return 'logical_not', attrs, inputs


def smart_colormap(vmin, vmax, color_high='#b11902', hue_low=0.6):
    """
    Creates a "smart" colormap that is centered on zero, and accounts for
    asymmetrical vmin and vmax by matching saturation/value of high and low
    colors.

    It works by first creating a colormap from white to `color_high`.  Setting
    this color to the max(abs([vmin, vmax])), it then determines what the color
    of min(abs([vmin, vmax])) should be on that scale.  Then it shifts the
    color to the new hue `hue_low`, and finally creates a new colormap with the
    new hue-shifted as the low, `color_high` as the max, and centered on zero.

    Parameters
    ----------
    color_high : color
        Can be any format supported by matplotlib. Try "#b11902" for a nice
        red.
    hue_low : float in [0, 1]
        Try 0.6 for a nice blue
    vmin : float
        Lowest value in data you'll be plotting
    vmax : float
        Highest value in data you'll be plotting
    """
    import matplotlib
    import colorsys
    orig_cmap = matplotlib.colors.LinearSegmentedColormap.from_list('test',
        ['#FFFFFF', color_high], N=2048)
    vmin = float(vmin)
    vmax = float(vmax)
    mx = max([vmin, vmax])
    mn = min([vmin, vmax])
    frac = abs(mn / mx)
    rgb = orig_cmap(frac)[:-1]
    hsv = list(colorsys.rgb_to_hsv(*rgb))
    hsv[0] = hue_low
    new_rgb = colorsys.hsv_to_rgb(*hsv)
    new_hex = matplotlib.colors.rgb2hex(new_rgb)
    zeropoint = -vmin / (vmax - vmin)
    new_cmap = matplotlib.colors.LinearSegmentedColormap.from_list('test',
        [(0, new_rgb), (zeropoint, '#FFFFFF'), (1, color_high)], N=2048)
    return new_cmap


def nr_profiles(arr, genomes):
    """
    Get a condensed cgMLST pairwise distance matrix for specified Genomes_
    where condensed means redundant cgMLST profiles are only represented once in the distance matrix.

    Args:
        user_name (list): List of Genome_ names to retrieve condensed distance matrix for

    Returns:
        (numpy.array, list): tuple of condensed cgMLST distance matrix and list of grouped Genomes_
    """
    gs_collapse = []
    genome_idx_dict = {}
    indices = []
    patt_dict = {}
    for i, g in enumerate(genomes):
        p = arr[(i), :].tostring()
        if p in patt_dict:
            parent = patt_dict[p]
            idx = genome_idx_dict[parent]
            gs_collapse[idx].append(g)
        else:
            indices.append(i)
            patt_dict[p] = g
            genome_idx_dict[g] = len(gs_collapse)
            gs_collapse.append([g])
    return arr[(indices), :], gs_collapse


def get_expr_ids_visit(expr, ids):
    """Visitor to retrieve ExprId in @expr
    @expr: Expr"""
    if expr.is_id():
        ids.add(expr)
    return expr


def create_receipt_filter(Filter=None):
    """
    Creates a new IP address filter.
    For information about setting up IP address filters, see the Amazon SES Developer Guide .
    This action is throttled at one request per second.
    See also: AWS API Documentation

    Examples
    The following example creates a new IP address filter:
    Expected Output:

    :example: response = client.create_receipt_filter(
        Filter={
            'Name': 'string',
            'IpFilter': {
                'Policy': 'Block'|'Allow',
                'Cidr': 'string'
            }
        }
    )

    :type Filter: dict
    :param Filter: [REQUIRED]
            A data structure that describes the IP address filter to create, which consists of a name, an IP address range, and whether to allow or block mail from it.
            Name (string) -- [REQUIRED]The name of the IP address filter. The name must:
            Contain only ASCII letters (a-z, A-Z), numbers (0-9), periods (.), underscores (_), or dashes (-).
            Start and end with a letter or number.
            Contain less than 64 characters.
            IpFilter (dict) -- [REQUIRED]A structure that provides the IP addresses to block or allow, and whether to block or allow incoming mail from them.
            Policy (string) -- [REQUIRED]Indicates whether to block or allow incoming mail from the specified IP addresses.
            Cidr (string) -- [REQUIRED]A single IP address or a range of IP addresses that you want to block or allow, specified in Classless Inter-Domain Routing (CIDR) notation. An example of a single email address is 10.0.0.1. An example of a range of IP addresses is 10.0.0.1/24. For more information about CIDR notation, see RFC 2317 .

    :rtype: dict
    :return: {}

    """
    pass


def calculate_passengers_mass(n_passengers, passenger_mass):
    """
    Calculate passengers mass including driver [kg].

    :param n_passengers:
        Number of passengers including driver [-].
    :type n_passengers: int

    :param passenger_mass:
        Average passenger mass [kg].
    :type passenger_mass: float

    :return:
        Passengers mass including the driver [kg].
    :rtype: float
    """
    return passenger_mass * n_passengers


def timetuple():
    """Return a 9-element tuple of the form returned by time.localtime().

        The hours, minutes and seconds are 0, and the DST flag is -1.
        d.timetuple() is equivalent to
        (d.year, d.month, d.day, 0, 0, 0, d.weekday(), d.toordinal() -
        date(d.year, 1, 1).toordinal() + 1, -1)
        """


def _clamp(value, minx, maxx):
    """
    Constrain a value between a minimum and a maximum.

    If the value is larger than the maximum or lower than the minimum, the
    maximum or minimum will be returned instead.

    :param int value: The value to clamp.
    :param int minx: The minimum the value can take.
    :param int maxx: The maximum the value can take.
    """
    return max(minx, min(maxx, value))


def set_load_balancer_policies_of_listener(LoadBalancerName=None,
    LoadBalancerPort=None, PolicyNames=None):
    """
    Replaces the current set of policies for the specified load balancer port with the specified set of policies.
    To enable back-end server authentication, use  SetLoadBalancerPoliciesForBackendServer .
    For more information about setting policies, see Update the SSL Negotiation Configuration , Duration-Based Session Stickiness , and Application-Controlled Session Stickiness in the Classic Load Balancer Guide .
    See also: AWS API Documentation

    Examples
    This example replaces the policies that are currently associated with the specified listener.
    Expected Output:

    :example: response = client.set_load_balancer_policies_of_listener(
        LoadBalancerName='string',
        LoadBalancerPort=123,
        PolicyNames=[
            'string',
        ]
    )

    :type LoadBalancerName: string
    :param LoadBalancerName: [REQUIRED]
            The name of the load balancer.

    :type LoadBalancerPort: integer
    :param LoadBalancerPort: [REQUIRED]
            The external port of the load balancer.

    :type PolicyNames: list
    :param PolicyNames: [REQUIRED]
            The names of the policies. This list must include all policies to be enabled. If you omit a policy that is currently enabled, it is disabled. If the list is empty, all current policies are disabled.
            (string) --

    :rtype: dict
    :return: {}

    """
    pass


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

    The ".dev0" means dirty.

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


def _add_mmcif_res_full(table):
    """
    Utility that adds a new column to the table.
    Adds a new column with the 'full res' (i.e. seq_id + ins_code).

    :param table: pandas DataFrame object
    :return: returns a modified pandas DataFrame
    """
    if 'label_seq_id' in table:
        table['label_seq_id_full'] = table['label_seq_id'] + table[
            'pdbx_PDB_ins_code'].str.replace('?', '')
    if 'auth_seq_id' in table:
        table['auth_seq_id_full'] = table['auth_seq_id'] + table[
            'pdbx_PDB_ins_code'].str.replace('?', '')
    return table


@classmethod
def get_exec_name(cls):
    """
        Get the name of this executable
        """
    return 'plainbox'


@staticmethod
def disconnect_extension_point_traits(obj):
    """ Disconnect all of the 'ExtensionPoint' traits on an object. """
    for trait_name, trait in obj.traits(__extension_point__=True).items():
        trait.trait_type.disconnect(obj, trait_name)
    return


def default_resolver(riak_object):
    """
    The default conflict-resolution function, which does nothing. To
    implement a resolver, define a function that sets the
    :attr:`siblings <aioriak.riak_object.RiakObject.siblings>` property
    on the passed :class:`RiakObject <aioriak.riak_object.RiakObject>`
    instance to a list containing a single :class:`RiakContent
    <aioriak.content.RiakContent>` object.

    :param riak_object: an object-in-conflict that will be resolved
    :type riak_object: :class:`RiakObject <aioriak.riak_object.RiakObject>`
    """
    pass


def get_description():
    """ Returns a description that identifies the object """


def identity(arg):
    """Identity function. Produces what it consumes.

  :param arg:
      Argument
  :returns:
      Argument.
  """
    return arg


@classmethod
def new(cls, *args, **kwargs):
    """
        Create a new instance of this Trace.

        :param args: Passed directly through to the Trace.__init__ method.
        :param kwargs: Passed directly through to the Trace.__init__ method.
        :return: A new instance of an Trace class.
        :rtype: Trace
        """
    trace = cls(*args, **kwargs)
    trace.logger.debug('Created {trace}'.format(trace=trace))
    return trace


def cesnet_dict_typedef(flavour, list_flavour, errors_list, abuses_list,
    addon=None):
    """
    Typedef generator helper for easy usage of custom definitions at
    multiple places.
    """
    cesnet_def = {'InspectionErrors': {'description':
        'List of event pecularities found during inspection', 'type':
        errors_list}, 'StorageTime': {'description':
        'Unix timestamp of the moment the message was stored into database',
        'type': flavour['Timestamp']}, 'EventTemplate': {'description':
        'Template used to generate the event (deprecated)', 'type': flavour
        ['String']}, 'EventClass': {'description':
        'Event class determined by inspection', 'type': flavour['String']},
        'EventSeverity': {'description':
        'Event severity determined by inspection', 'type': flavour['String'
        ]}, 'Impact': {'description':
        'More user friendly description of event impact, used for reporting (IDMEF legacy)'
        , 'type': flavour['String']}, 'ResolvedAbuses': {'description':
        'Abuse contacts related to any alert source', 'type': abuses_list},
        'SourceResolvedASN': {'description':
        'AS numbers related to any alert source', 'type': list_flavour[
        'Integer']}, 'SourceResolvedCountry': {'description':
        'Coutry ISO codes related to any alert source', 'type':
        list_flavour['String']}}
    if addon is not None:
        cesnet_def.update(addon)
    return cesnet_def


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


def parse_range(checkdict):
    """Given a checkdict for a range widget return the min and max string values."""
    Range = checkdict.get('range', '1-5')
    try:
        rmin, rmax = Range.split('-', 1)
    except ValueError:
        rmin, rmax = '1', '5'
    return rmin, rmax


def ensure_ext(filepath, ext, case_sensitive=False):
    """
    Return the path with the extension added if it is not already set.

    :arg ext: The extension to check for, can be a compound extension. Should
              start with a dot, such as '.blend' or '.tar.gz'.
    :type ext: string
    :arg case_sensitive: Check for matching case when comparing extensions.
    :type case_sensitive: bool
    """
    if case_sensitive:
        if filepath.endswith(ext):
            return filepath
    elif filepath[-len(ext):].lower().endswith(ext.lower()):
        return filepath
    return filepath + ext


def _is_dunder(name):
    """Returns True if a __dunder__ name, False otherwise."""
    return name[:2] == name[-2:] == '__' and name[2:3] != '_' and name[-3:-2
        ] != '_' and len(name) > 4


@classmethod
def validate_remove(cls, filters: dict) ->dict:
    """
        Validate a document(s) removal request.

        :param filters: Provided filters.
        Each entry if composed of a field name associated to a value.
        :return: Validation errors that might have occurred. Empty if no error occurred.
        Entry would be composed of a field name associated to a list of error messages.
        """
    return cls.validate_query(filters)


def castable(value, typename):
    """Can value be cast as type typename without throwing an exception?"""
    try:
        typename(value)
        return True
    except Exception:
        return False


def collapseDuplicateSubtrees(ast):
    """Common subexpression elimination.
    """
    seen = {}
    aliases = []
    for a in ast.allOf('op'):
        if a in seen:
            target = seen[a]
            a.astType = 'alias'
            a.value = target
            a.children = ()
            aliases.append(a)
        else:
            seen[a] = a
    for a in aliases:
        while a.value.astType == 'alias':
            a.value = a.value.value
    return aliases


def bulles(l):
    """ Trie la liste avec la méthode du tri à bulles

    :param l: Un tableau de nombre
    :return: une copie de la liste triée

    >>> bulles([1, 2, 6, 5])
    [1, 2, 5, 6]

    """
    tab = l[:]
    n = len(tab)
    for i in range(n):
        for j in range(n - i - 1):
            if tab[j] > tab[j + 1]:
                tab[j], tab[j + 1] = tab[j + 1], tab[j]
    return tab


def filter_meta(pattern, metatags):
    """ Filter METADATA_FIELDS from unused tags."""
    used_tags = set()
    for metatag in metatags:
        if '{' + metatag + '}' in pattern:
            used_tags.add(metatag)
    return used_tags


@staticmethod
def dotDrawEdge(st1, st2, sep='\n'):
    """ Draw a transition in Dot Format

        :arg str st1: starting state
        :arg str st2: ending state
        :arg str sep: separator
        :rtype: str"""
    return '"{0:s}" -> "{1:s}" {3:s} '.format(st1, st2, sep)


def pytest_itemcollected(item):
    """ we just collected a test item. """


def _load_pretrained_tok2vec(nlp, loc):
    """Load pre-trained weights for the 'token-to-vector' part of the component
    models, which is typically a CNN. See 'spacy pretrain'. Experimental.
    """
    with loc.open('rb') as file_:
        weights_data = file_.read()
    loaded = []
    for name, component in nlp.pipeline:
        if hasattr(component, 'model') and hasattr(component.model, 'tok2vec'):
            component.tok2vec.from_bytes(weights_data)
            loaded.append(name)
    return loaded


@classmethod
def from_string(cls, string):
    """Read the struct from string."""
    _self = cls()
    _self.xforms = [cls._inner_type.from_string(string)]
    return _self


def define_command(subparsers, command, callback):
    """Define a command in the subparsers collection.

    :param subparsers: subparsers collection where the command will go
    :param command: command name
    :param callback: function that will be used to process the command
    """
    desc = callback.__doc__ or ''
    help = desc.strip().split('\n')[0]
    arguments = getattr(callback, 'arguments', [])
    subparser = subparsers.add_parser(command, help=help, description=desc)
    for args, kwargs in arguments:
        subparser.add_argument(*args, **kwargs)
    subparser.set_defaults(func=callback)


def _load_yml(yaml_path) ->None:
    """
    Load global yaml file if one exist.
    :param yaml_path:
    :return: None
    """
    global _YAML_DATA
    with open(yaml_path, 'r') as yaml_file:
        data = yaml_file.read()
        _YAML_DATA += data
    if 'paths' not in _YAML_DATA:
        _YAML_DATA += 'paths:\n'


def theta_Na_Sr_MWRB78(T, P):
    """c-c': sodium strontium [MWRB78]."""
    theta = -0.0076
    valid = T == 298.15
    return theta, valid


@classmethod
def as_server(cls, host, port):
    """Return an address to use as a server address."""
    return cls(host, port, isserver=True)


def search_dict_list(l, key, value):
    """ Search a list of dict
        * return dict with specific value & key """
    for i in l:
        if i.get(key) == value:
            return i


def upperfirst(value):
    """upper first word of string, and does not change the rest case,
    such as:
        foobAr => FoobAr
    """
    if len(value) > 1:
        return value[0].upper() + value[1:]
    else:
        return value[0].upper()


def select_segment_id(fhandle, segment_set):
    """Filters the PDB file for specific segment identifiers.
    """
    records = 'ATOM', 'HETATM', 'ANISOU'
    for line in fhandle:
        if line.startswith(records):
            if line[72:76].strip() not in segment_set:
                continue
        yield line


def _startswith(value):
    """
    Maps to `string.startswith`.
    """
    return lambda v: v.startswith(value)


def paste():
    """Paste text from clipboard

    """
    pass


def _parse_token(k, v):
    """
    Convert parameters to their Python code representation

    Notes
    -----
    This is a very simple way of doing it, for a more complete implementation,
    check out papermill's source code:
    https://github.com/nteract/papermill/blob/master/papermill/translators.py
    """
    return '{} = {}'.format(k, repr(v))


def iterator(d):
    """
    Helper to get and a proper dict iterator with Py2k and Py3k
    """
    try:
        return d.iteritems()
    except AttributeError:
        return d.items()


def _extend(M, sym):
    """Extend window by 1 sample if needed for DFT-even symmetry"""
    if not sym:
        return M + 1, True
    else:
        return M, False


@property
def declarative_props(cls):
    """
        Gathers all the declared props, including the ones declared in superclasses.
        This is a meta-property common to all classes with this metatype
        """
    return cls.__walk_mro_inherit_declarations('_own_declarative_props')


def _clean_dict(row):
    """
    Transform empty strings values of dict `row` to None.
    """
    row_cleaned = {}
    for key, val in row.items():
        if val is None or val == '':
            row_cleaned[key] = None
        else:
            row_cleaned[key] = val.strip()
    return row_cleaned


def route_path(route_name, request, *elements, **kw):
    """
    This is a backwards compatibility function.  Its result is the same as
    calling::

        request.route_path(route_name, *elements, **kw)

    See :meth:`pyramid.request.Request.route_path` for more information.
    """
    return request.route_path(route_name, *elements, **kw)


def circuit_command(api, command, name=None, **selection):
    """Run mobilities circuit commands.

    :param command: in ['list', 'get']
    :param name: circuit name
    :param **selections: selections by circuit site and type

    """
    assert command in ('list', 'get')
    if 'type' in selection:
        assert selection['type'] in ('predefined', 'userdefined')
    if command == 'list':
        result = api.get_circuits(**selection)
    elif command == 'get':
        result = api.get_circuit(name)
    else:
        raise ValueError('Unknown command %r' % command)
    return result


def make_invcovmatrix(sigma_x, sigma_y, rho=0):
    """ create inverse covariance matrix from given standard deviations and normalised correlation rho, vectorized """
    F = 1.0 / (sigma_x ** 2 * sigma_y ** 2 * (1 - rho ** 2))
    return (F * sigma_y ** 2, F * -rho * sigma_x * sigma_y), (F * -rho *
        sigma_x * sigma_y, F * sigma_x ** 2)


def get_source(template_id):
    """Get the source of a given template.

        Returns None if the source cannot be loaded.
        """


def get_theme():
    """Returns the current theme object, cached."""


def separate_globs(globs):
    """Separate include and exclude globs."""
    exclude = []
    include = []
    for path in globs:
        if path.startswith('!'):
            exclude.append(path[1:])
        else:
            include.append(path)
    return exclude, include


def expand(recursive=0):
    """
        Expand this node.

        'recursive' can be set to true to expand all children nodes as
        well
        """


def mp_init(l, c):
    """ Initialization function for multi-threaded operations.

    :param l: lock
    :param c: value for common counter
    """
    global lock
    global counter
    lock = l
    counter = c


def log2(data=None, name=None, attr=None, out=None, **kwargs):
    """Returns element-wise Base-2 logarithmic value of the input.

    ``2**log2(x) = x``

    The storage type of ``log2`` output is always dense

    Defined in src/operator/tensor/elemwise_unary_op_logexp.cc:L105

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

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

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


def get_rect_ymin(data):
    """Find minimum y value from four (x,y) vertices."""
    return min(data[0][1], data[1][1], data[2][1], data[3][1])


def toListOfPairs(s):
    """
    Convert a spaces-separated string to a list of pairs.
    Raise ValueError if the list length is not even.

    >>> toListOfPairs('a b c d e f')
    [('a', 'b'), ('c', 'd'), ('e', 'f')]
    """
    items = s.split()
    if len(items) % 2:
        raise ValueError('input must contain even number of entries')
    return list(zip(items[::2], items[1::2]))


def addBarcodesToIdentifier(read, UMI, cell):
    """extract the identifier from a read and append the UMI and
    cell barcode before the first space"""
    read_id = read.identifier.split(' ')
    if cell == '':
        read_id[0] = read_id[0] + '_' + UMI
    else:
        read_id[0] = read_id[0] + '_' + cell + '_' + UMI
    identifier = ' '.join(read_id)
    return identifier


def join():
    """Join selected objects into active object

    """
    pass


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 dim_unit_scaling(in_unit, out_unit):
    """
    Calculate the scaling factor to convert from the input unit (in_unit) to
    the output unit (out_unit). in_unit and out_unit must be a string and one
    of ['nm', 'um', 'mm', 'cm', 'm', 'km'].

    inputs
    ======
    in_unit : str
        Input unit
    out_unit :str
        Output unit

    returns
    =======
    scaling_factor : float
    """
    unit_vals = {'nm': 1e-09, 'um': 1e-06, 'mm': 0.001, 'cm': 0.01, 'm':
        1.0, 'km': 1000.0}
    if in_unit not in unit_vals:
        raise ValueError('Invalid input unit {}. Must be one of {}'.format(
            in_unit, list(unit_vals.keys())))
    if out_unit not in unit_vals:
        raise ValueError('Invalid input unit {}. Must be one of {}'.format(
            in_unit, list(unit_vals.keys())))
    return unit_vals[in_unit] / unit_vals[out_unit]


def reload():
    """Reload active text data block from its file

    """
    pass


def dict_convert(_dict, keyfn=None, valuefn=None):
    """Return a new dict with each key converted by keyfn (if not None),
       and each value converted by valuefn (if not None).
    """
    if keyfn is None and valuefn is not None:
        for k in _dict:
            _dict[k] = valuefn(_dict[k])
        return _dict
    elif keyfn is not None:
        out_dict = {}
        for k in _dict:
            out_dict[keyfn(k)] = valuefn(_dict[k]) if valuefn else _dict[k]
        return out_dict
    else:
        return _dict


def __deserialize_datatime(B, string):
    """Deserializes string to datetime.

        The string should be in iso8601 datetime format.

        :param string: str.
        :return: datetime.
        """
    A = string
    try:
        from dateutil.parser import parse
        return parse(A)
    except ImportError:
        return A


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

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


def reset_globals():
    """
    Reset mas.glob related global variables.

    Must be called whenever (and before) pynusmv.init.init.deinit_nusmv
    is called.
    """
    global __mas
    __mas = None


def read_centrimo_stats(centrimo_stats):
    """Read centrimo' stats.txt for single motif[should be independent though]

    Attributes
    ----------
    centrimo_stats: str
        Path to stats.txt file

    Returns
    -------
    hits: dict
         A dict containing hits from centrimo.txt

    """
    motif_wise_site_stats = {'MEME': {}, 'DREME': {}}
    with open(centrimo_stats) as f:
        for line in f:
            line = line.strip()
            if line.startswith('DB'):
                line_split = line.replace(' ', '\t').split('\t')
                assert len(line_split) == 5
                meme_dreme = line_split[-1]
                assert meme_dreme in ['MEME', 'DREME']
                key = '_'.join(line_split[2:4])
                assert key not in list(motif_wise_site_stats[meme_dreme].keys()
                    )
                motif_wise_site_stats[meme_dreme][key] = {'pos': [],
                    'count': []}
            else:
                line = line.replace(' ', '')
                pos, count = line.split('\t')
                motif_wise_site_stats[meme_dreme][key]['pos'].append(float(pos)
                    )
                motif_wise_site_stats[meme_dreme][key]['count'].append(float
                    (count))
    return motif_wise_site_stats


def to_digital(d, num):
    """
    进制转换，从10进制转到指定机制
    :param d:
    :param num:
    :return:
    """
    if not isinstance(num, int) or not 1 < num < 10:
        raise ValueError('digital num must between 1 and 10')
    d = int(d)
    result = []
    x = d % num
    d = d - x
    result.append(str(x))
    while d > 0:
        d = d // num
        x = d % num
        d = d - x
        result.append(str(x))
    return ''.join(result[::-1])


def exclude_soft_clip(row, read_cigar):
    """
    Separated from extend_realign_region, used to exclude the soft clip at the start or end of the query_sequence.
    Because sometimes realign region might include the softclip region and the softclip region usually is really
    long which can lead to a wrong realignment result.
    """
    cigar_slice = read_cigar.cslice(start_ci=row['realign_start_ci'],
        end_ci=row['realign_end_ci'])
    if cigar_slice[0][1] == 'S':
        row['realign_start_rdp'] += cigar_slice[0][0]
        row['realign_start_ci'] = row['realign_start_ci'][0] + 1, 0
    if cigar_slice[-1][1] == 'S':
        row['realign_end_rdp'] -= cigar_slice[0][0]
        row['realign_end_ci'] = row['realign_end_ci'][0], 0
    return row


def __call__(*args, **kwargs):
    """
        Called with dependencies (specified in :py:attr:`dependencies`
        attribute) as arguments (and possibly other, additional arguments)
        returns a provided object. Provider is not responsible for caching
        objects in scopes and should never return a cached object.
        """


def sql_flush(style, connection, only_django=False, reset_sequences=True,
    allow_cascade=False):
    """
    Returns a list of the SQL statements used to flush the database.

    If only_django is True, then only table names that have associated Django
    models and are in INSTALLED_APPS will be included.
    """
    if only_django:
        tables = connection.introspection.django_table_names(only_existing=True
            )
    else:
        tables = connection.introspection.table_names()
    seqs = connection.introspection.sequence_list() if reset_sequences else ()
    statements = connection.ops.sql_flush(style, tables, seqs, allow_cascade)
    return statements


def calculate_centre_of_mass(points_list):
    """
    Calculates the centre of mass for the non-intersecting polygon defined by points_list.

    .. note:: the centre of mass will be incorrect for intersecting polygons.

    .. note::

            it is assumed that points_list defines, in order, the vertices of the polygon. The last
            point is assumed to connect to the first point.

    :param points_list: a list of x, y points defining the non-intersecting polygon
    :return: the x,y centre of mass
    """
    centre_x = 0
    centre_y = 0
    area = 0
    size = len(points_list)
    points_list.append(points_list[0])
    for i, each in enumerate(points_list):
        if i == size:
            break
        added_area = each[0] * points_list[i + 1][1] - points_list[i + 1][0
            ] * each[1]
        area += added_area
        centre_x += (each[0] + points_list[i + 1][0]) * added_area
        centre_y += (each[1] + points_list[i + 1][1]) * added_area
    area *= 0.5
    try:
        centre_x /= 6 * area
        centre_y /= 6 * area
    except ZeroDivisionError:
        raise ValueError('Points not ordered in polygon')
    return centre_x, centre_y


@classmethod
def array_fields(cls):
    """ All array fields """
    return cls.shared_fields + cls.unshared_fields + cls.array_only_fields


def stats_per_chunk(chunk, block_data_totals):
    """Given a chunk, increment the block types with the number of blocks found"""
    for block_id, data_id in chunk.blocks.get_all_blocks_and_data():
        block_data_totals[block_id][data_id] += 1


def polynomialFit5(x, b0, b1, b2, b3, b4, b5):
    """
    Taylor polynomial for fit
    b1 = GD
    b2 = GDD / 2
    b3 = TOD / 6
    b4 = FOD / 24
    b5 = QOD / 120
    """
    return b0 + b1 * x + b2 * x ** 2 + b3 * x ** 3 + b4 * x ** 4 + b5 * x ** 5


def apply_mapping(sample, mappings, start, end):
    """Helper applying maps in defined threshold."""
    for mapping in mappings[start:end]:
        sample = mapping(sample)
    return sample


def economic_sectors_regional_MISTRAL():
    """
    Reginal sector ID with description from
    economic_sectors_regiona.csv of MISTRAl
    population/economic simuations

    match_int: Integer of GVA input
    """
    lookup_dict = {'mining': {'match_int': 2, 'description':
        'Mining & quarrying'}, 'food_production': {'match_int': 3,
        'description': 'Food, drink & tobacco'}, 'tobacco': {'match_int': 3,
        'description': 'Food, drink & tobacco'}, 'textiles': {'match_int':
        4, 'description': 'Textiles etc'}, 'wood': {'match_int': 5,
        'description': 'Wood & paper'}, 'paper': {'match_int': 5,
        'description': 'Wood & paper'}, 'printing': {'match_int': 6,
        'description': 'Printing & recording'}, 'chemicals': {'match_int':
        8, 'description': 'Chemicals, etc'}, 'pharmaceuticals': {
        'match_int': 9, 'description': 'Pharmaceuticals'}, 'beverages': {
        'match_int': 29, 'description': 'Food & beverage services'},
        'fabricated_metal_products': {'match_int': 11, 'description':
        'Metals & metal prods'}, 'electrical_equipment': {'match_int': 12,
        'description': 'Electronics'}, 'non_metallic_mineral_products': {
        'match_int': 10, 'description': 'Non-metallic min. prods.'},
        'motor_vehicles': {'match_int': 15, 'description':
        'Motor vehicles, etc'}, 'machinery': {'match_int': 14,
        'description': 'Machinery, etc'}, 'waste_collection': {'match_int':
        19, 'description': 'Water, sewerage & waste'},
        'water_collection_treatment': {'match_int': 19, 'description':
        'Water, sewerage & waste'}, 'other_manufacturing': {'match_int': 17,
        'description': 'Other manuf. & repair'}, 'education': {'match_int':
        40, 'description': 'Education'}, 'health': {'match_int': 41,
        'description': 'Health'}, 'hospitality': {'match_int': 28,
        'description': 'Accomodation'}, 'offices': {'match_int': 35,
        'description': 'Head offices & manag. cons.'}, 'retail': {
        'match_int': 23, 'description': 'Retail trade'}, 'storage': {
        'match_int': 27, 'description': 'Warehousing & postal'}}
    return lookup_dict


def create_lrzip(archive, compression, cmd, verbosity, interactive, filenames):
    """Create a LRZIP archive."""
    cmdlist = [cmd, '-o', archive]
    if verbosity > 1:
        cmdlist.append('-v')
    cmdlist.extend(filenames)
    return cmdlist


def parent(docker_path):
    """
    >>> path = getfixture('tmpdir').mkdir('parent').join('Dockerfile')
    >>> path.write('FrOm    ubuntu')

    >>> parent(str(path))
    'ubuntu'

    """
    for l in open(docker_path):
        if l.strip().lower().startswith('from'):
            return l.split()[1]


def home_link():
    """ Returns a link to the API entry point/home page.

    .. versionchanged:: 0.5
       Link is relative to API root.

    .. versionchanged:: 0.0.3
       Now returning a JSON link.
    """
    return {'title': 'home', 'href': '/'}


@staticmethod
def _get_session_args(decode=False, eval_loop_ix=None):
    """ Returns a dict of kwargs to feed to session.run
            Expected format: {fetches, feed_dict=None}
        """
    del decode, eval_loop_ix
    return {}


def DotProduct_DML(feat, M, query=None, is_sparse=False, is_trans=False):
    """ DotProduct distance with DML.
    """
    if query is None:
        query = feat
    return -query.dot(M).dot(feat.T)


def get(isamAppliance, check_mode=False, force=False):
    """
    Get all snmp objects
    """
    return isamAppliance.invoke_get('Get all alert objects',
        '/core/system_alerts')


def event_id(event):
    """
    Gets a unique identifier for an event retrieved from Pilatus files (or HiDRA).

    Returns a label that unambiguosly identifies, within an experiment, the event
    currently being processed. For the Pilatus detector, an event corresponds to a
    single CBF file, and the full path to the file is used as identifier.

    Arguments:

        event (:class:`~onda.utils.data_event.DataEvent`): an object storing the event
            data.

    Returns:

        str: a unique event identifier.
    """
    return event.framework_info['full_path']


def get_urls(session, name, data, find_changelogs_fn, **kwargs):
    """
    Gets URLs to changelogs.
    :param session: requests Session instance
    :param name: str, package name
    :param data: dict, meta data
    :param find_changelogs_fn: function, find_changelogs
    :return: tuple, (set(changelog URLs), set(repo URLs))
    """
    return {'https://api.launchpad.net/1.0/{}/releases'.format(name)}, set()


@classmethod
def beliefs(cls):
    """
        Not applicable for gliders
        """
    return {}


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

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

    """
    pass


def cmp(a, b):
    """
    >>> cmp("a", "b")
    -1
    >>> cmp(2, 1)
    1
    """
    if a < b:
        return -1
    elif a > b:
        return 1
    else:
        return 0


def _iter_ns_str_reversed(namespace):
    """
        Take a namespace string, and yield successively smaller portions
        of it (ex foo::bar::baz::, foo::bar::, foo::). The last item yielded
        will always be an empty string
    """
    if namespace:
        parts = namespace.split('::')
        for i in range(len(parts) - 1, 0, -1):
            yield '::'.join(parts[:i]) + '::'
    yield ''


def unix_to_timestamp(unix):
    """Convert a Unix timestamp (floating point seconds since epoch)
    into a NILM timestamp (integer microseconds since epoch)"""
    return int(round(unix * 1000000.0))


def diag_item_get_length(item):
    """Returns the item length according to the item_type

    :param item: item to look at
    :type item: :class:`SAPDiagItem`

    :return: the item length
    :rtype: ``int``
    """
    diag_item_sizes = {(1): 16, (2): 20, (3): 3, (7): 76, (8): 0, (9): 22,
        (10): 3, (11): 2, (12): 0, (16): item.item_length, (17): item.
        item_length4, (18): item.item_length4, (19): 2, (21): 36}
    return diag_item_sizes[item.item_type]


def _exist_ip_rule(rules, ip, iif, table, priority, to):
    """Check if any rule matches the conditions"""
    for rule in rules:
        if iif and rule.get('iif') != iif:
            continue
        if not iif and rule['from'] != ip:
            continue
        if table and rule.get('table') != str(table):
            continue
        if priority and rule['priority'] != str(priority):
            continue
        if to and rule.get('to') != to:
            continue
        break
    else:
        return False
    return True


@staticmethod
def _get_primary_keys(formatted_columns):
    """Get columns that are primary key"""
    primary_keys = list()
    for column in formatted_columns:
        column_is_primary_key = column[3]
        if column_is_primary_key:
            column_name = column[0]
            primary_keys.append(column_name)
    return primary_keys


def render_to_file(doc, outf):
    """
    Renders the document as an svg to a file-like object.
    """
    for l in doc.render():
        outf.write(l + '\n')


def istype(object, cls):
    """instance(object, type) and issubclass(object, cls)

Examples
--------

    >>> assert istype(int, int)
    >>> assert not istype(10, int)

"""
    if isinstance(object, type):
        return issubclass(object, cls)
    return False


def selectSuR(i):
    """
    not all functions are still in this file, the older functions can be found
    (with the same numbering) in h:\\My Documents\\memo's\\python scripts\\wflow    """
    if i == 1:
        name = 'unsatZone_LP_beta'
    elif i == 2:
        name = 'unsatZone_LP'
    elif i == 3:
        name = 'unsatZone_SF'
    elif i == 4:
        name = 'unsatZone_EisEp'
    elif i == 5:
        name = 'unsatZone_drain'
    elif i == 6:
        name = 'unsatZone_drain_split'
    elif i == 7:
        name = 'unsatZone_drain_Sumin'
    elif i == 8:
        name = 'unsatZone_drain_DZ'
    elif i == 9:
        name = 'unsatZone_drain_split_DZ'
    elif i == 10:
        name = 'unsatZone_withAgri'
    elif i == 11:
        name = 'unsatZone_withAgri_oldBeta'
    elif i == 12:
        name = 'unsatZone_LP_beta_Jarvis'
    elif i == 13:
        name = 'unsatZone_LP_beta_Ep'
    elif i == 14:
        name = 'unsatZone_withAgri_Ep'
    elif i == 15:
        name = 'unsatZone_withAgri_Jarvis'
    elif i == 16:
        name = 'unsatZone_forAgri_Jarvis'
    elif i == 17:
        name = 'unsatZone_forAgri_Ep'
    elif i == 18:
        name = 'unsatZone_forAgri_Jarvis_cropG'
    elif i == 19:
        name = 'unsatZone_forAgri_Ep_cropG'
    elif i == 20:
        name = 'unsatZone_LP_beta_Ep_cropG'
    return name


def _script_command_options(opts):
    """Extract `command` and `options` from argparse 'opts'."""
    if opts.run_script_site is not None:
        command = 'run'
        options = opts.run_script_site
    elif opts.kill_sites is not None:
        command = 'kill'
        options = opts.kill_sites
    elif opts.status_sites is not None:
        command = 'status'
        options = opts.status_sites
    else:
        raise ValueError('Unknown request')
    return command, options


@staticmethod
def get_banner():
    """
        Returns the Shell banner
        """
    return '** Pelix Shell prompt **\n'


@classmethod
def enable(cls):
    """Enables compositing tree inspection.
        """
    return cls.build_send_payload('enable', {}), None


def ensure_str(s):
    """ Ensure that s is a str and not a bytes (.decode() if necessary)

    >>> ensure_str(b"I'm 2. When I grow up I want to be a str!")
    "I'm 2. When I grow up I want to be a str!"
    >>> ensure_str(42)
    '42'
    """
    try:
        return s.decode()
    except AttributeError:
        if isinstance(s, str):
            return s
    return repr(s)


@staticmethod
def _check_imports():
    """
        Static method to check that healpy is installed on the machine running bibly
        """
    try:
        import healpy
    except Exception:
        raise ImportError(
            'Must have healpy installed on this machine to use HealPixMapPrior'
            )
    return healpy


def get_diz_from_colly(filepath):
    """ Get FILE_ID.DIZ from within an ASCII collection. """
    colly = open(filepath, 'r').read()
    colly_diz_begin = '@BEGIN_FILE_ID.DIZ'
    colly_diz_end = '@END_FILE_ID.DIZ'
    pos = colly.find(colly_diz_begin)
    if pos > 0:
        colly = colly[pos + len(colly_diz_begin):]
        pos = colly.find(colly_diz_end)
        if pos > 0:
            return colly[:pos].splitlines()
    return None


def stop_logging(Name=None):
    """
    Suspends the recording of AWS API calls and log file delivery for the specified trail. Under most circumstances, there is no need to use this action. You can update a trail without stopping it first. This action is the only way to stop recording. For a trail enabled in all regions, this operation must be called from the region in which the trail was created, or an InvalidHomeRegionException will occur. This operation cannot be called on the shadow trails (replicated trails in other regions) of a trail enabled in all regions.
    See also: AWS API Documentation

    :example: response = client.stop_logging(
        Name='string'
    )

    :type Name: string
    :param Name: [REQUIRED]
            Specifies the name or the CloudTrail ARN of the trail for which CloudTrail will stop logging AWS API calls. The format of a trail ARN is:
            arn:aws:cloudtrail:us-east-1:123456789012:trail/MyTrail

    :rtype: dict
    :return: {}

    """
    pass


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


def scroll_page(up: bool=False):
    """Scroll page up or down

    :param up: Up, Scroll up one page
    :type up: bool
    """
    pass


@staticmethod
def _filter_significant(match: 'HMMER') ->bool:
    """ Select significant alignments based on evalues and coverage.

        dbCAN uses a threshold of 1e-5 for alignments over 80 AA
        and 1e-3 for others. A coverage threshold of 0.3 is used.
        """
    if match.coverage < 0.3:
        return False
    is_long = match.ali_to - match.ali_from > 80
    if is_long:
        return match.evalue < 1e-05
    else:
        return match.evalue < 0.001


def simple_gcd(a, b):
    """Compute GCD of its two inputs."""
    while b != 0:
        a, b = b, a % b
    return a


def read_directional_view_map_pixel(orientation: int, level: int, x: int, y:
    int) ->float:
    """Reads a pixel in one of the oriented view map images.

    :param orientation: The number telling which orientation we want to check.
    :type orientation: int
    :param level: The level of the pyramid in which we wish to read the pixel.
    :type level: int
    :param x: The x coordinate of the pixel we wish to read. The origin is in the lower-left corner.
    :type x: int
    :param y: The y coordinate of the pixel we wish to read. The origin is in the lower-left corner.
    :type y: int
    :return:  The floating-point value stored for that pixel.
    """
    pass


@staticmethod
def scan_done(cb):
    """call function which is not inherited from QObject"""
    cb()


def __maiseli_step(queue, I, Ix, Iy, Iz, c, dIdt, nx, ny, nz, prg, ht, beta,
    lamb):
    """Performs a single time step of the Maiseli filter for a single working
    package.

    Parameters
    ----------
    I : ndarray
        Image to become smoothed
    Ix : ndarray
        Partial derivative in x direction
    Iy : ndarray
        Partial derivative in y direction
    Iz : ndarray
        Partial derivative in z direction
    c : ndarray
        Conductivity factor (depending on gradient, to preserve edges)
    dIdt : ndarray
        Time derivative of the image
    nx : int
        Size of the package in x direction
    ny : int
        Size of the package in y direction
    nz : int
        Size of the package in z direction
    prg : cl-Program
        OpenCL program to become executed
    ht : float
        Time step
    beta : float
        Beta factor
    lamb : float
        Lambda regularization factor
    """
    prg.grad(queue, (nx + 2, ny + 2, nz + 2), None, I, Ix, Iy, Iz, nx, ny, nz)
    prg.c(queue, (nx + 2, ny + 2, nz + 2), None, Ix, Iy, Iz, c, nx, ny, nz,
        beta)
    shape = int(nx), int(ny), int(nz)
    prg.dIdt_stage1(queue, shape, None, Ix, Iy, Iz, c, dIdt, nx, ny, nz)
    prg.dIdt_stage2(queue, shape, None, Ix, Iy, Iz, c, dIdt, nx, ny, nz)
    prg.time_step(queue, shape, None, dIdt, I, nx, ny, nz, ht)


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

        :param WriteError val:
        :rtype: RestoreError
        """
    return cls('path_write', val)


def slice_to_inclusive_slice(key: slice) ->slice:
    """Make a stop exclusive key inclusive by adding one to the stop value.
    """
    stop = None if key.stop is None else key.stop + 1
    return slice(key.start, stop, key.step)


def generate_time_pairs(start_times, end_times):
    """Forms time pairs out of start times and end times
        Parameters
        ----------
        start_times : list
            contains all times where a condition applies
        end_times : list
            contains all times where the condition does not apply
        Return
        ------
        time_pair : list
            list of touples with start and end time
        """
    time_pair: float = []
    if not start_times:
        time_pair.append((0, 0))
    elif not end_times:
        time_pair.append((start_times[0], 0))
    else:
        time_hook = 0
        last_start_time = 0
        for start in list(sorted(set(start_times))):
            if start > time_hook:
                for end in list(sorted(set(end_times))):
                    if end > start:
                        time_pair.append((start, end))
                        time_hook = end
                        break
        if list(sorted(set(start_times)))[-1] > list(sorted(set(end_times)))[-1
            ]:
            time_pair.append((list(sorted(set(end_times)))[-1], 0))
    return time_pair


def primary_recoil_ranges_rowdata(mobj):
    """Generate list of 'Primary Recoil Ranges' section data, which is output in csv format

    mobj is parsed object given by Parser.parse()
    """
    rowdata = [mobj['Index']['Cascade'], mobj['Index']['Group'], mobj[
        'Index']['Number']]
    d = mobj['Primary Recoil Ranges']
    rowdata += [d['Elem'], d['Radial Range'], d['Penetration'], d['Spread'],
        d['Total Path'], d['Slowing Down Time']]
    return rowdata


def is_anonymous(request):
    """
    Returns True if request.user is not authenticated else returns False
    """
    return not request.user.is_authenticated


def _has_newline(line):
    """Used by has_bad_header to check for \\r or \\n"""
    if line and ('\r' in line or '\n' in line):
        return True
    return False


@staticmethod
def _endpoint_address(ep_num, direction):
    """
        Returns the endpoint number that corresponds to a given directio
        and address.
        """
    if direction:
        return ep_num | 128
    else:
        return ep_num


@classmethod
def stop_all_threads(cls):
    """ set the stop_running attribute to True for all threads
            and their workers (if they have one)
        """
    for thread in cls.thread_set:
        worker = thread.worker
        if worker is not None:
            worker.stop_running = True
        thread.stop_running = True


def apply(settings):
    """Modify settings."""
    if 'DATABASE_ROUTERS' not in settings:
        settings['DATABASE_ROUTERS'] = []
    settings['DATABASE_ROUTERS'] += ['kalabash_amavis.dbrouter.AmavisRouter']
    if 'SILENCED_SYSTEM_CHECKS' not in settings:
        settings['SILENCED_SYSTEM_CHECKS'] = []
    settings['SILENCED_SYSTEM_CHECKS'] += ['fields.W342']
    settings['AMAVIS_DEFAULT_DATABASE_ENCODING'] = 'LATIN1'


@classmethod
def from_weight(cls, weight):
    """Instantiate class by evaluating the mass
        of an object with given weight.

        :param float weight:
        :rtype: Mass
        """
    return cls(weight / cls.g)


def sub_tempita(s, context, file=None, name=None):
    """Run tempita on string s with given context."""
    if not s:
        return None
    if file:
        context['__name'] = '%s:%s' % (file, name)
    elif name:
        context['__name'] = name
    from ..Tempita import sub
    return sub(s, **context)


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


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


def get_ssl():
    """Get TLS/HTTPS info"""
    raise NotImplementedError


def load_datetime(finder, module):
    """the datetime module implicitly imports time; make sure this happens."""
    finder.IncludeModule('time')


def heading(text: str, underline: str) ->str:
    """
    Create a heading using the specified underline character.

    :param text: The text to use as the heading
    :param underline: The character to underline with
    :return: The heading in rst format
    """
    return text + '\n' + underline * len(text)


@classmethod
def get_default_session_class(cls):
    """Get the default session class for :py:class:`JsonApiService`.

        Returns
        -------
        JsonApiService
            The default session class, which is :py:class:`JsonApiService` itself or
            a derived class from :py:class:`JsonApiService`.
        """
    return cls._session_class


def track_copy_color():
    """Copy color to all selected tracks

    """
    pass


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


@staticmethod
def __is_key_value_v1(read_response, secret_key):
    """
        Checks if the response is from the key value v1 secret engine.
        See https://www.vaultproject.io/api/secret/kv/kv-v1.html#sample-response-1
        Args:
            - read_response: response from HVAC read function
            - secret_key: secret key being retrieved
        Returns:
            Bool
        """
    return isinstance(read_response.get('data', {}).get(secret_key, {}), str)


@staticmethod
def clean_parameter(param=''):
    """ I get parameters already with '"' quotes from curl? """
    if param is None:
        return param
    return param.strip('"')


def _check_dataset_shapes(datasets):
    """ If the  datasets are not the same shape throw a ValueError Exception

    :param datasets: OCW Datasets to check for a consistent shape
    :type datasets: List of OCW Dataset Objects

    :raises: ValueError
    """
    dataset_shape = None
    for dataset in datasets:
        if dataset_shape is None:
            dataset_shape = dataset.values.shape
        elif dataset.values.shape != dataset_shape:
            msg = '%s != %s' % (dataset.values.shape, dataset_shape)
            raise ValueError(
                'Input datasets must be the same shape for an ensemble :: ',
                msg)
        else:
            pass


def serialize_dtype(o):
    """
    Serializes a :obj:`numpy.dtype`.

    Args:
        o (:obj:`numpy.dtype`): :obj:`dtype` to be serialized.

    Returns:
        A dictionary that can be passed to :obj:`json.dumps`.
    """
    if len(o) == 0:
        return dict(_type='np.dtype', descr=str(o))
    return dict(_type='np.dtype', descr=o.descr)


def read_config_file(filename):
    """
    Read a simple ``'='``-delimited config file.
    Raises :const:`IOError` if unable to open file, or :const:`ValueError`
    if an parse error occurs.
    """
    f = open(filename)
    try:
        cfg = {}
        for line in f:
            line = line.strip()
            if line and not line.startswith('#'):
                try:
                    key, value = line.split('=', 1)
                    cfg[key] = value
                except ValueError:
                    pass
    finally:
        f.close()
    return cfg


def _testThresholdPen():
    """
    >>> from fontPens.printPointPen import PrintPointPen
    >>> from random import seed
    >>> seed(100)
    >>> glyph = _makeTestGlyph()
    >>> pen = ThresholdPointPen(PrintPointPen())
    >>> glyph.drawPoints(pen)
    pen.beginPath()
    pen.addPoint((100, 100), segmentType='line')
    pen.addPoint((900, 100), segmentType='line')
    pen.addPoint((900, 800), segmentType='line')
    pen.addPoint((100, 800), segmentType='line')
    pen.endPath()
    pen.addComponent('a', (1.0, 0.0, 0.0, 1.0, 0.0, 0.0))
    """


def _indicate_bind_completed(kek_meta_dto, kek_datum):
    """Updates the supplied kek_datum instance

    Updates the kek_datum per the contents of the supplied
    kek_meta_dto instance. This function is typically used once plugins
    have had a chance to bind kek_meta_dto to their crypto systems.

    :param kek_meta_dto:
    :param kek_datum:
    :return: None

    """
    kek_datum.bind_completed = True
    kek_datum.algorithm = kek_meta_dto.algorithm
    kek_datum.bit_length = kek_meta_dto.bit_length
    kek_datum.mode = kek_meta_dto.mode
    kek_datum.plugin_meta = kek_meta_dto.plugin_meta


def get_preferred_sparse_format():
    """Get the preferred sparse matrix format supported by the backend.

    Different backends have their preferred backend. This info is useful when
    constructing a sparse matrix.
    """
    return 'csr'


def atom_is_aromatic(atom):
    """Get whether the atom is aromatic.

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

    Returns
    -------
    list
        List containing one bool only.
    """
    return [atom.GetIsAromatic()]


def flip_names(do_strip_numbers: bool=False):
    """Flips (and corrects) the axis suffixes of the names of selected bones

    :param do_strip_numbers: Strip Numbers, Try to remove right-most dot-number from flipped names (WARNING: may result in incoherent naming in some cases)
    :type do_strip_numbers: bool
    """
    pass


def get_formatted_time(seconds: float) ->str:
    """
    Convert seconds to the time format ``H:M:S.UU``.

    :param seconds: time in seconds
    :return: formatted human-readable time
    """
    seconds = round(seconds)
    m, s = divmod(seconds, 60)
    h, m = divmod(m, 60)
    return '{:d}:{:02d}:{:02d}'.format(h, m, s)


def update_provisioned_product(AcceptLanguage=None, ProvisionedProductName=
    None, ProvisionedProductId=None, ProductId=None, ProvisioningArtifactId
    =None, PathId=None, ProvisioningParameters=None, UpdateToken=None):
    """
    Requests updates to the configuration of an existing ProvisionedProduct object. If there are tags associated with the object, they cannot be updated or added with this operation. Depending on the specific updates requested, this operation may update with no interruption, with some interruption, or replace the ProvisionedProduct object entirely.
    You can check the status of this request using the  DescribeRecord operation.
    See also: AWS API Documentation

    :example: response = client.update_provisioned_product(
        AcceptLanguage='string',
        ProvisionedProductName='string',
        ProvisionedProductId='string',
        ProductId='string',
        ProvisioningArtifactId='string',
        PathId='string',
        ProvisioningParameters=[
            {
                'Key': 'string',
                'Value': 'string',
                'UsePreviousValue': True|False
            },
        ],
        UpdateToken='string'
    )

    :type AcceptLanguage: string
    :param AcceptLanguage: The language code to use for this operation. Supported language codes are as follows:
            'en' (English)
            'jp' (Japanese)
            'zh' (Chinese)
            If no code is specified, 'en' is used as the default.

    :type ProvisionedProductName: string
    :param ProvisionedProductName: The updated name of the ProvisionedProduct object . You must specify either ProvisionedProductName or ProvisionedProductId , but not both.

    :type ProvisionedProductId: string
    :param ProvisionedProductId: The identifier of the ProvisionedProduct object to update. You must specify either ProvisionedProductName or ProvisionedProductId , but not both.

    :type ProductId: string
    :param ProductId: The identifier of the ProvisionedProduct object.

    :type ProvisioningArtifactId: string
    :param ProvisioningArtifactId: The provisioning artifact identifier for this product.

    :type PathId: string
    :param PathId: The identifier of the path to use in the updated ProvisionedProduct object. This value is optional if the product has a default path, and is required if there is more than one path for the specified product.

    :type ProvisioningParameters: list
    :param ProvisioningParameters: A list of ProvisioningParameter objects used to update the ProvisionedProduct object.
            (dict) --The parameter key/value pair used to update a ProvisionedProduct object. If UsePreviousValue is set to true, Value is ignored and the value for Key is kept as previously set (current value).
            Key (string) --The ProvisioningArtifactParameter.ParameterKey parameter from DescribeProvisioningParameters .
            Value (string) --The value to use for updating the product provisioning. Any constraints on this value can be found in the ProvisioningArtifactParameter parameter for Key .
            UsePreviousValue (boolean) --If true, uses the currently set value for Key , ignoring UpdateProvisioningParameter.Value .

    :type UpdateToken: string
    :param UpdateToken: [REQUIRED]
            The idempotency token that uniquely identifies the provisioning update request.
            This field is autopopulated if not provided.

    :rtype: dict
    :return: {
        'RecordDetail': {
            'RecordId': 'string',
            'ProvisionedProductName': 'string',
            'Status': 'IN_PROGRESS'|'SUCCEEDED'|'ERROR',
            'CreatedTime': datetime(2015, 1, 1),
            'UpdatedTime': datetime(2015, 1, 1),
            'ProvisionedProductType': 'string',
            'RecordType': 'string',
            'ProvisionedProductId': 'string',
            'ProductId': 'string',
            'ProvisioningArtifactId': 'string',
            'PathId': 'string',
            'RecordErrors': [
                {
                    'Code': 'string',
                    'Description': 'string'
                },
            ],
            'RecordTags': [
                {
                    'Key': 'string',
                    'Value': 'string'
                },
            ]
        }
    }

    """
    pass


def peptide_mutation_interval(peptide_start_in_protein, peptide_length,
    mutation_start_in_protein, mutation_end_in_protein):
    """
    Half-open interval of mutated residues in the peptide, determined
    from the mutation interval in the original protein sequence.

    Parameters
    ----------
    peptide_start_in_protein : int
        Position of the first peptide residue within the protein
        (starting from 0)

    peptide_length : int

    mutation_start_in_protein : int
        Position of the first mutated residue starting from 0. In the case of a
        deletion, the position where the first residue had been.

    mutation_end_in_protein : int
        Position of the last mutated residue in the mutant protein. In the case
        of a deletion, this is equal to the mutation_start_in_protein.
    )
    """
    if peptide_start_in_protein > mutation_end_in_protein:
        raise ValueError('Peptide starts after mutation')
    elif peptide_start_in_protein + peptide_length < mutation_start_in_protein:
        raise ValueError('Peptide ends before mutation')
    peptide_mutation_start_offset = min(peptide_length, max(0,
        mutation_start_in_protein - peptide_start_in_protein))
    peptide_mutation_end_offset = min(peptide_length, max(0,
        mutation_end_in_protein - peptide_start_in_protein))
    return peptide_mutation_start_offset, peptide_mutation_end_offset


def calculate_air_density(air_temperature, atmospheric_pressure):
    """
    Calculates the air density [kg/m3].

    :param air_temperature:
        Air temperature [°C].
    :type air_temperature: float

    :param atmospheric_pressure:
        Atmospheric pressure [kPa].
    :type atmospheric_pressure: float

    :return:
        Air density [kg/m3].
    :rtype: float
    """
    return 3.48 * atmospheric_pressure / (273.16 + air_temperature)


@staticmethod
def byte_to_handle(in_byte: int) ->str:
    """Convert a byte array to a handle string."""
    return '0x' + '{:02x}'.format(in_byte).upper()


def do_something(x):
    """
    Routine that does something

    Parameters
    ----------
    x : object
        Some input parameter

    Returns
    -------
    y : array
        Some relevant integers

    Notes
    -----
    This routine actually doesn't do much.

    """
    print('something: %r' % x)
    return x


@classmethod
def scopes(cls):
    """
        Return a list of valid/understood class scopes.
        """
    return [cls.USAGE, cls.DEFINITION, cls.TYPE, cls.ALL]


def integer_bit_size(n):
    """Returns the number of bits necessary to store the integer n."""
    if n == 0:
        return 1
    s = 0
    while n:
        s += 1
        n >>= 1
    return s


def cached_objects_with_updates(iter):
    """Return objects from a session/iterator that are tagged for caching and
    that need an update."""
    for obj in iter:
        if getattr(obj, '__needs_update__', False):
            yield obj


def _convert_constant_of_shape(builder, node, graph, err):
    """
    convert to CoreML Fill Static Layer:
    https://github.com/apple/coremltools/blob/655b3be5cc0d42c3c4fa49f0f0e4a93a26b3e492/mlmodel/format/NeuralNetwork.proto#L3641
    """
    value = node.attrs.get('value', [0.0])
    if node.inputs[0] in node.input_tensors:
        output_shape = node.input_tensors[node.inputs[0]]
        if len(output_shape.shape) == 1:
            output_shape = output_shape.reshape(output_shape.shape[0], 1)
        builder.add_fill_static(name=node.name, output_name=node.outputs[0],
            output_shape=output_shape, value=value[0])
    else:
        builder.add_fill_dynamic(name=node.name, input_name=node.inputs[0],
            output_name=node.outputs[0], value=value[0])


@classmethod
def close_registry_entry(cls, value):
    """Close a registry entry."""
    return False


def is_larger(im, dimensions):
    """
    Check if this image is currently larger in either axis than the desired
    dimensions. If either desired dimension is None, the image will be larger
    in that dimension.
    """
    w, h = im.size
    desired_w, desired_h = dimensions
    return w > (desired_w or 0) or h > (desired_h or 0)


def get_help_website():
    """Get the URL for the help website."""
    return 'https://help.cloudsmith.io/docs/cli/'


@classmethod
def getUrl(cls, state):
    """
        Return the URL to start the OAuth2 authentication flow with an external
        provider.

        This abstract function must be reimplemented by each provider.

        :param state: A unique string, used to prevent CSRF and store other
        state information. This string should not be URL-encoded (that must be
        done in this method).
        :return: An external absolute URL to the start point for this provider's
        OAuth2 flow.
        """
    raise NotImplementedError()


@staticmethod
def guard(*args, **kwargs):
    """ Look in storage.

        :returns: False

        """
    return False


def cyclic(graph):
    """
    Return True if the directed graph has a cycle.
    The graph must be represented as a dictionary mapping vertices to
    iterables of neighbouring vertices. For example:

    >>> cyclic({1: (2,), 2: (3,), 3: (1,)})
    True
    >>> cyclic({1: (2,), 2: (3,), 3: (4,)})
    False

    """
    visited = set()
    path = [object()]
    path_set = set(path)
    stack = [iter(graph)]
    i = 0
    while stack:
        for v in stack[-1]:
            if v in path_set:
                return True
            elif v not in visited:
                visited.add(v)
                path.append(v)
                path_set.add(v)
                stack.append(iter(graph.get(v, ())))
                break
        else:
            path_set.remove(path.pop())
            stack.pop()
    return False


def normalize_profile(profile, critx):
    """Normalize a [(x:int, y:int), ...] profile.

    The normalized profile will ensure that:

     - the profile is a monotonically increasing function
       (i.e. for every i, i > 1, x[i] - x[i-1] > 0 and y[i] - y[i-1] >= 0)
     - the profile is sorted
     - a (critx, 100) failsafe is enforced

    >>> normalize_profile([(30, 40), (25, 25), (35, 30), (40, 35), (40, 80)], 60)
    [(25, 25), (30, 40), (35, 40), (40, 80), (60, 100)]
    """
    profile = sorted(list(profile) + [(critx, 100)], key=lambda p: (p[0], -
        p[1]))
    mono = profile[0:1]
    for (x, y), (xb, yb) in zip(profile[1:], profile[:-1]):
        if x == xb:
            continue
        if y < yb:
            y = yb
        mono.append((x, y))
    return mono


def ReserveUernPremEnd(t):
    """Unearned Premium: End of period"""
    return 0


@classmethod
def join(cls, *names):
    """Join components of chunk name with supported separator."""
    return cls.NAME_SEP.join(names)


def run(vhd_list, output_file):
    """Runs this backend."""
    for vhd in vhd_list.order:
        output_file.write('%s %s %04d %s\n' % ('top' if vhd in vhd_list.top
             else 'dep', vhd.lib, vhd.version, vhd.fname))


def annualize(returns, durations, one_year=365.0):
    """
    年化收益率，(1 + returns) ** (1 / (durations / one_year)) - 1
    """
    return (1.0 + returns) ** (1.0 / (durations / one_year)) - 1.0


def identityfunc(arg):
    """Single argument identity function.

    >>> identityfunc('arg')
    'arg'

    """
    return arg


def _compare_dicts(d1, d2):
    """Given two dictionaries, return what keys were added, removed, changed or might be changed
    """
    added, removed, changed, maybe_changed = [], [], [], []
    all_keys = set(d1).union(set(d2))
    for k in all_keys:
        if k not in d1:
            added.append(k)
        elif k not in d2:
            removed.append(k)
        elif d1[k] is d2[k]:
            continue
        else:
            try:
                if d1[k] != d2[k]:
                    changed.append(k)
            except:
                maybe_changed.append(k)
    return added, changed, removed, maybe_changed


def _toggle_help(history):
    """ Display/hide help. """
    help_buffer_control = history.history_layout.help_buffer_control
    if history.app.layout.current_control == help_buffer_control:
        history.app.layout.focus_previous()
    else:
        history.app.layout.current_control = help_buffer_control


@classmethod
def GET(cls, *n, **kw):
    """
        Perform a GET request using `RESTClient.request()`.
        """
    return cls.IMPL.GET(*n, **kw)


def get_thin_dict(diff):
    """Returns a dict containing minimal data on the diff.

    This includes:
      - before/after file name
      - change type (add, delete, move, change)
      - diffstats
    """
    return {'a': diff.a, 'b': diff.b, 'type': diff.type}


def safe_unpack(seq, ln, fill=None):
    """Safely unpack a sequence to length `ln`, without raising ValueError. Based on Lua's method of unpacking. Empty values will be filled in with `fill`, while any extra values will be cut off.

       :param seq: The sequence to unpack.

       :param ln: The expected length of the sequence.

       :param fill: The value to substitute if the sequence is too small. Defaults to ``None``.

       Example::

           s = 'a:b'
           a, b = safe_unpack(s.split(':'), 2)
           # a = 'a'
           # b = 'b'
           s = 'a'
           a, b = safe_unpack(s.split(':'), 2)
           # a = 'a'
           # b = None"""
    if len(seq) > ln:
        return seq[:ln]
    elif len(seq) < ln:
        return seq + type(seq)([fill] * (ln - len(seq)))
    else:
        return seq


@staticmethod
def _get_translated_field_names(model_instance):
    """
        Get the instance translatable fields

        :return:
        """
    hvad_internal_fields = ['id', 'language_code', 'master', 'master_id',
        'master_id']
    translated_field_names = set(model_instance._translated_field_names) - set(
        hvad_internal_fields)
    return translated_field_names


def above():
    """Returns a function that takes two 2D bounding boxes and computes whether
    the first one is strictly above the second one.

    The output function takes in two 2D bounding boxes (dicts with keys 'x1',
    'x2', 'y1', 'y2') and returns ``True`` if the first bounding box's 'y2' value
    is less than the second bounding box's 'y1' value.

    Returns:
        A function that takes two 2D bounding boxes and returns ``True`` if the
        first bounding box is strictly above the second one.
    """
    return lambda bbox1, bbox2: bbox1['y2'] < bbox2['y1']


def get_client_ip(request):
    """
    extracts external IP from HTTP requests
    """
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[-1].strip()
    else:
        ip = request.META.get('REMOTE_ADDR')
    return ip


def load_material(material, mat_name, data_class):
    """Material loader with name as identification.

    Loads Material specified in the JSON. Sources are
    :cite:`DeutschesInstitutfurNormung.Juli2000`,
    DeutschesInstitutfurNormung.Februar2013, :cite:`Schramek.2009` and
    :cite:`VereinDeutscherIngenieure.2015c`.

    Parameters
    ----------
    material : Material()
        instance of TEASERS Material class

    mat_name : str
        Code list for Material

    data_class : DataClass()
        DataClass containing the bindings for TypeBuildingElement and
        Material (typically this is the data class stored in prj.data,
        but the user can individually change that.

    """
    binding = data_class.material_bind
    for id, mat in binding.items():
        if id != 'version':
            if mat['name'] == mat_name:
                material.material_id = id
                material.name = mat['name']
                material.density = mat['density']
                material.thermal_conduc = mat['thermal_conduc']
                material.heat_capac = mat['heat_capac']
                material.solar_absorp = mat['solar_absorp']
                material.thickness_default = mat['thickness_default']
                material.thickness_list = mat['thickness_list']


def get_paginator(operation_name=None):
    """
    Create a paginator for an operation.

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

    :rtype: L{botocore.paginate.Paginator}
    """
    pass


@classmethod
def from_storage(cls, storage):
    """Load from storage.

        Parameters
        ----------
        storage : `markovchain.storage.Storage`

        Returns
        -------
        `markovchain.Markov`
        """
    args = dict(storage.settings.get('markov', {}))
    args['storage'] = storage
    return cls(**args)


def keys():
    """Obtain a list of paths in the manifest."""


@classmethod
def from_private_key(klass, private_key):
    """This class method will create a new Public Key
        based on a private key.

        :param private_key: The private key
        :returns: a new public key
        """
    public_key = private_key.get_verifying_key()
    hexkey = (klass.key_prefix + public_key.to_string()).encode('hex')
    return klass(hexkey)


def format_input_source(input_source_name, input_source_number):
    """Format input source for display in UI."""
    return f'{input_source_name} {input_source_number}'


def crunch_window_path(path):
    """
	Returns the input window name void of all periods and exclamation points.
	"""
    return path.replace('!', '').replace('.', '')


def parse_patterns(patterns_spec, ignore_patterns_spec, separator=';'):
    """
    Parses pattern argument specs and returns a two-tuple of
    (patterns, ignore_patterns).
    """
    patterns = patterns_spec.split(separator)
    ignore_patterns = ignore_patterns_spec.split(separator)
    if ignore_patterns == ['']:
        ignore_patterns = []
    return patterns, ignore_patterns


@classmethod
def from_invalid_default_value(cls, default):
    """
        Compile time error. Default value for restriction is invalid.
        """
    return cls('Invalid default "%s".' % default)


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

    Example::

       abs([-2, 0, 3]) = [2, 0, 3]

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

       - abs(default) = default
       - abs(row_sparse) = row_sparse
       - abs(csr) = csr

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

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

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

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


def sample_to_orbit(sample: list) ->list:
    """Provides the orbit corresponding to a given sample.

    **Example usage:**

    >>> sample = [1, 2, 0, 0, 1, 1, 0, 3]
    >>> sample_to_orbit(sample)
    [3, 2, 1, 1, 1]

    Args:
        sample (list[int]): a sample from GBS

    Returns:
        list[int]: the orbit of the sample
    """
    return sorted(filter(None, sample), reverse=True)


@staticmethod
def nameserversets(nameserversets):
    """
        list namerserversets:  The list of nameserversets to be pretty printed.
        """
    if 'resData' in nameserversets:
        nameserversets = nameserversets['resData']
    count, total = 0, len(nameserversets['nsset'])
    output = '\n%i nameserversets:\n' % total
    for nameserverset in nameserversets['nsset']:
        count += 1
        output += '%i of %i - ID: %i consisting of [%s]\n' % (count, total,
            nameserverset['id'], ', '.join(nameserverset['ns']))
    return output


def all_continuous_indexes_slices(ol, value):
    """
        from elist.elist import *
        ol = [1,"a","a",2,3,"a",4,"a","a","a",5]
        all_continuous_indexes_slices(ol,"a")
    """
    rslt = []
    length = ol.__len__()
    cursor = 0
    begin = None
    slice = []
    while cursor < length:
        cond1 = ol[cursor] == value
        cond2 = begin == None
        if cond1 & cond2:
            begin = cursor
            slice.append(cursor)
        elif cond1 & (not cond2):
            slice.append(cursor)
        elif (not cond1) & (not cond2):
            rslt.append(slice)
            begin = None
            slice = []
        else:
            pass
        cursor = cursor + 1
    if slice:
        rslt.append(slice)
    else:
        pass
    return rslt