def cHadamard():
    """
    Return the Hardamard operations related kernel sources.
    """
    R = """
        KERNEL void cSelect2(
        const unsigned int Reps,
        GLOBAL_MEM const  unsigned int *order1,
        GLOBAL_MEM const  unsigned int *order2,
        GLOBAL_MEM const float2 *indata,
        GLOBAL_MEM       float2 *outdata)
        {
        const unsigned int gid=get_global_id(0);
        const unsigned int t = ((float)gid / (float)Reps); // indptr
        const unsigned int r = gid - t*Reps; // residue

        const unsigned int index2 = order2[t]*Reps + r;
        const unsigned int index1 = order1[t]*Reps + r;

        outdata[index2]=indata[index1];
        };

        KERNEL void cDistribute(
        const    unsigned int    Reps,
        const    unsigned int    prodNd,
        GLOBAL_MEM const float2 *arr_large, // sensitivity and scaling array, prodNd*Reps
        GLOBAL_MEM const float2 *arr_image, // image array, prodNd
        GLOBAL_MEM float2 *arr_out // output array, prodNd * Reps
        )
        {
        const unsigned int t = get_global_id(0);
        //const unsigned int nd = t/Reps;
        const unsigned int nd = ((float)t / (float)Reps);
        if (nd < prodNd){
        const float2 u = arr_large[t];
        const float2 v = arr_image[nd];
        float2 w;
        w.x = u.x * v.x - u.y * v.y;
        w.y = u.x * v.y + u.y * v.x;
        arr_out[t] = w;
        }
        };  // End of cDistribute

        KERNEL void cMerge(
        const    unsigned int    Reps,
        const    unsigned int    prodNd,
        GLOBAL_MEM const float2 *arr_large, // sensitivity and scaling array, prodNd*Reps
        GLOBAL_MEM const float2 *arr_image, // image array, prodNd*Reps
        GLOBAL_MEM float2 *arr_out // reduced output array, prodNd
        )
        {
        const unsigned int t = get_local_id(0);
        //const float float_reps = (float)Reps;
        const unsigned int vecWidth=${LL};
        // Thread ID within wavefront
        const unsigned int id = t & (vecWidth-1);
        // One row per wavefront
        unsigned int vecsPerBlock=get_local_size(0)/vecWidth;
        unsigned int myRow=(get_group_id(0)*vecsPerBlock) + (t/ vecWidth);
        LOCAL_MEM float2 partialSums[${LL}];
        float2 zero;
        zero.x = 0.0;
        zero.y = 0.0;

        partialSums[t] = zero;
        // float2  y= zero;
        if (myRow < prodNd)
        {
        const unsigned int vecStart = myRow * Reps;
        const unsigned int vecEnd = vecStart + Reps;
        for (unsigned int j = vecStart+id;  j<vecEnd; j += vecWidth)
        {

              const float2 u = arr_large[j]; // sensitivities and scaling, complex
              const float2 v = arr_image[j];
              float2 w;
              w.x = u.x * v.x + u.y * v.y; // conjugate of u
              w.y = u.x * v.y - u.y * v.x;
              w.x = w.x/(float)Reps;
              w.y = w.y/(float)Reps;
            partialSums[t] = w;        //partialSums[t] + y;
        }

        LOCAL_BARRIER;
        //__syncthreads();
        //barrier(CLK_LOCAL_MEM_FENCE);
        // Reduce partial sums
        unsigned int bar = vecWidth / 2;
        while(bar > 0)
        {
             if (id < bar)
            partialSums[t] = partialSums[t] + partialSums[t+bar];

             //barrier(CLK_LOCAL_MEM_FENCE);
             //__syncthreads();
             LOCAL_BARRIER;
             bar = bar / 2;
        }
        // Write result
        if (id == 0)
        {
         arr_out[myRow]=partialSums[t];
        }
        }
        };    // End of cMerge

        KERNEL void cAggregate(
        const    unsigned int    Reps,
        const    unsigned int    prodNd,
        GLOBAL_MEM const float2 *arr_image, // image array, prodNd*Reps
        GLOBAL_MEM float2 *arr_out // reduced output array, prodNd
        )
        {
        const unsigned int t = get_local_id(0);
        //const float float_reps = (float)Reps;
        const unsigned int vecWidth=${LL};
        // Thread ID within wavefront
        const unsigned int id = t & (vecWidth-1);
        // One row per wavefront
        unsigned int vecsPerBlock=get_local_size(0)/vecWidth;
        unsigned int myRow=(get_group_id(0)*vecsPerBlock) + (t/ vecWidth);
        LOCAL_MEM float2 partialSums[${LL}];
        float2 zero;
        zero.x = 0.0;
        zero.y = 0.0;

        partialSums[t] = zero;
        // float2  y= zero;
        if (myRow < prodNd)
        {
        const unsigned int vecStart = myRow * Reps;
        const unsigned int vecEnd = vecStart + Reps;
        for (unsigned int j = vecStart+id;  j<vecEnd; j += vecWidth)
        {
          float2 v = arr_image[j];
          v.x = v.x/(float)Reps;
          v.y = v.y/(float)Reps;
          partialSums[t] =partialSums[t] + v;        //partialSums[t] + y;
        }

        LOCAL_BARRIER;
        //__syncthreads();
        //barrier(CLK_LOCAL_MEM_FENCE);
        // Reduce partial sums
        unsigned int bar = vecWidth / 2;
        while(bar > 0)
        {
             if (id < bar)
            partialSums[t] = partialSums[t] + partialSums[t+bar];

             //barrier(CLK_LOCAL_MEM_FENCE);
             //__syncthreads();
             LOCAL_BARRIER;
             bar = bar / 2;
        }
        // Write result
        if (id == 0)
        {
         arr_out[myRow]=partialSums[t];
        }
        }
        LOCAL_BARRIER;
        };    // End of cAggregate

        KERNEL void cPopulate(
        const    unsigned int    Reps,
        const    unsigned int   prodNd,
        GLOBAL_MEM const float2 *arr_image, // image array, prodNd
        GLOBAL_MEM float2 *arr_out // output array, prodNd * Reps
        )
        {
        const unsigned int t = get_global_id(0);
        //const unsigned int nd = t/Reps;
        const unsigned int nd = ((float)t / (float)Reps);
        if (nd < prodNd){
        const float2 v = arr_image[nd];
        arr_out[t] = v;
        }
        LOCAL_BARRIER;
        };  // End of cPopulate

        """
    return R


def save_id_map(filename, revision_ids):
    """Save the mapping of commit ids to revision ids to a file.

    Throws the usual exceptions if the file cannot be opened,
    written to or closed.

    :param filename: name of the file to save the data to
    :param revision_ids: a dictionary of commit ids to revision ids.
    """
    with open(filename, 'wb') as f:
        for commit_id in revision_ids:
            f.write(b'%s %s\n' % (commit_id, revision_ids[commit_id]))


@classmethod
def from_pixel(cls, value):
    """Create RGB value from pillow getpixel() return value."""
    if isinstance(value, tuple):
        red, green, blue = value[:3]
    else:
        red, green, blue = [value] * 3
    return cls(red, green, blue)


def _name_matches(element_def, element):
    """ Checks for match in the element name, performing a strict match based on the name regex in the def. """
    if element_def.name_matcher.match(element.name):
        return True
    return False


def parsing_rb_all(response, tips=False):
    """
    功能：解析回读所有舵机角度命令执行后机器人的回应信息。
    输入：空
    返回：
    angles：回读所有舵机角度的命令。
    """
    if response == b'':
        print('回应内容为空，请重新获取回应！')
        return
    cmd_len = response[2]
    cmd_type = response[3]
    if cmd_type != 37:
        print('解析类型错误，请检查回应内容，当前命令类型为%d' % cmd_type)
        return 0
    angles = []
    for i in range(16):
        angles.append(response[4 + i])
    if tips:
        print('回读到所有舵机的角度值为：{}'.format(angles))
    return angles


def sigma_cr_plate(thickness, width, psi=None):
    """
    Critical stress of a plate.

    Calculates the critical stress for a simply supported plate.

    Parameters
    ----------
    thickness : float
        [mm] Plate thickness
    width : float
        [mm] Plate width
    psi : float, optional
        [_] Ratio of the min over max stress for a linear distribution,
        (sigma_min / sigma_max)
        Default = 1, which implies a uniform distribution

    Returns
    -------
    float
        [MPa] Plate critical stress

    Notes
    -----
    To be extended to include cantilever plate (outstand members)

    References
    ----------
    .. [1] Eurocode 3: Design of steel structures - Part 1-5: Plated structural elements. Brussels: CEN, 2005.

    """
    thickness, width = float(thickness), float(width)
    if psi is None:
        psi = 1.0
    else:
        psi = float(psi)
    k_sigma = 8.2 / (1.05 + psi)
    sigma_e = 190000 * (thickness / width) ** 2
    sigma_cr = sigma_e * k_sigma
    return sigma_cr


@staticmethod
def is_cvte_spec_sw(sw_name):
    """
        检查是否符合CVTE软件命名规范
        :return:
        """
    return 'CP' in sw_name or 'CS' in sw_name


def glue(f, r):
    """Return (metadata, stream) pair where `r` is the initial portion of
    the metadata that has already been read from the stream `f`.
    """
    r = r + f.read(60 - len(r))
    return r, f


def unindex(relationship):
    """obtains the token for the relationship and unindexes (calls
        IInjection.unindex_doc)"""


def unique_element(ll):
    """ returns unique elements from a list preserving the original order """
    seen = {}
    result = []
    for item in ll:
        if item in seen:
            continue
        seen[item] = 1
        result.append(item)
    return result


@classmethod
def ctx(cls, tag_number):
    """Create context-specific tag from tag number.

        :param tag_number: tag number
        :type  tag_number: int
        :returns:          context-specific tag
        :rtype:            :class:`VASN1Tag`

        """
    return cls(cls.CONTEXT, tag_number)


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

        :param TfaResetType val:
        :rtype: EventType
        """
    return cls('tfa_reset', val)


def save_image(x, y, values, years, **kwargs):
    """
    Enregistre les cartes dessinees dans le repertoire courant
    :param          x               vecteur de longitudes
    :param          y               vecteur de latitudes
    :param          values           vecteur des valeurs representees
    :param          years            vecteur des annees sur lesquelles les cartes sont faites
    :param          kwargs          parametres additionnels
    """
    import cartopy.crs as ccrs
    import cartopy.feature as cfeature
    from matplotlib import pyplot as plt
    from cartopy.feature import NaturalEarthFeature, COLORS
    import numpy as np
    import pandas as pd
    assert isinstance(x, np.ndarray
        ), 'Erreur, x n est pas de type np.ndarray(vecteur)'
    assert isinstance(y, np.ndarray
        ), 'Erreur, y n est pas de type np.ndarray(vecteur)'
    assert isinstance(years, np.ndarray
        ), 'Erreur, years n est pas de type np.ndarray(vecteur)'
    assert isinstance(values, pd.DataFrame
        ), 'Erreur, values n est pas de type pd.DataFrame'
    assert len(x) == len(y), 'Erreur, x et y doit etre de meme taille'
    resolution = '50m'
    BORDERS = NaturalEarthFeature('cultural', 'admin_0_boundary_lines_land',
        resolution, edgecolor='black', facecolor='none')
    STATES = NaturalEarthFeature('cultural',
        'admin_1_states_provinces_lakes', resolution, edgecolor='black',
        facecolor='none')
    COASTLINE = NaturalEarthFeature('physical', 'coastline', resolution,
        edgecolor='black', facecolor='none')
    LAKES = NaturalEarthFeature('physical', 'lakes', resolution, edgecolor=
        'face', facecolor=COLORS['water'])
    LAND = NaturalEarthFeature('physical', 'land', resolution, edgecolor=
        'face', facecolor=COLORS['land'], zorder=-1)
    OCEAN = NaturalEarthFeature('physical', 'ocean', resolution, edgecolor=
        'face', facecolor=COLORS['water'], zorder=-1)
    RIVERS = NaturalEarthFeature('physical', 'rivers_lake_centerlines',
        resolution, edgecolor=COLORS['water'], facecolor='none')
    for i in range(len(years)):
        fig = plt.figure(figsize=(10, 7))
        ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree())
        ax.set_extent([-5, 10, 41, 52])
        ax.add_feature(BORDERS)
        ax.add_feature(LAKES)
        ax.add_feature(LAND)
        ax.add_feature(OCEAN)
        ax.add_feature(RIVERS)
        ax.add_feature(COASTLINE)
        plt.scatter(x, y, s=values.iloc[:, (i)] * 100, c=values.iloc[:, (i)
            ], alpha=0.5)
        plt.colorbar()
        ax.set_title('Annee' + ':' + str(years[i]))
        fig.savefig('carte' + str(years[i]) + '.png')
        plt.close(fig)
    return


def getANSIfgarray_for_ANSIcolor(ANSIcolor):
    """Return array of color codes to be used in composing an SGR escape
    sequence. Using array form lets us compose multiple color updates without
    putting out additional escapes"""
    return ['38', '5', str(ANSIcolor)]


def get_parm_val(parm=None, key=None):
    """
    Return the value of a key

    >>> get_parm_val(parm={'test':'val'},key='test')
    'val'
    >>> get_parm_val(parm={'test':'val'},key='foo')
    >>>
    """
    if parm and key in parm.keys():
        return parm[key]


def hello():
    """ Returns a Hello, World! """
    return 'Hello, Python'


def getRuleset():
    """Returns the IRuleset that owns this rule."""


def remove_comments(text: str) ->str:
    """
    Удаление комментариев из кода.

    :param text: Код для очистки
    :return: Очищенный код
    """
    if '/*' not in text:
        return text
    result = []
    state = ''
    index = 0
    length = len(text)
    while index < length:
        char = text[index]
        if state in ("'", '"', '|'):
            if char == state:
                state = ''
            result.append(char)
        elif char == '/':
            if index + 1 < length and text[index + 1] == '*':
                while index < length:
                    char = text[index]
                    if char in ('\r', '\n'):
                        result.append(char)
                        break
                    index = index + 1
            else:
                result.append(char)
        elif char in ("'", '"', '|'):
            state = char
            result.append(char)
        else:
            result.append(char)
        index = index + 1
    return ''.join(result)


def _get_metric_value(nested_dict, metric_name):
    """Gets the value of the named metric from a slice's metrics."""
    for key in nested_dict:
        if metric_name in nested_dict[key]['']:
            typed_value = nested_dict[key][''][metric_name]
            if 'doubleValue' in typed_value:
                return typed_value['doubleValue']
            if 'boundedValue' in typed_value:
                return typed_value['boundedValue']['value']
            raise ValueError('Unsupported value type: %s' % typed_value)
        else:
            raise ValueError('Key %s not found in %s' % (metric_name, list(
                nested_dict[key][''].keys())))


@classmethod
def check_state(cls, state, new_build):
    """checks if a state is allowed."""
    if not state in cls.states:
        raise ValueError('unknown state: %s' % repr(state))
    if new_build:
        if state == 'disabled':
            raise ValueError("state 'disabled' not allowed for a new build")


def listMembers():
    """ Return a sequence of all IMember instances.

        o This may eventually be replaced with a set of methods for querying
          pieces of the list rather than the entire list at once.

        o Permission:  Manage users
        """


def validipport(port):
    """
    Returns True if `port` is a valid IPv4 port.

        >>> validipport('9000')
        True
        >>> validipport('foo')
        False
        >>> validipport('1000000')
        False
    """
    try:
        if not 0 <= int(port) <= 65535:
            return False
    except ValueError:
        return False
    return True


@staticmethod
def secrets_retrieve(client, secret_ref):
    """Retrieve the payload from a secret in Barbican.

        :param client: the Barbican client
        :type client: barbicanclient.client

        :param secret_ref: Full HATEOAS reference to a Secret
        :type secret_ref: string
        """
    return client.secrets.get(secret_ref).payload


def _get_cast_kind(kind0, kind1):
    """determine the kind to cast into
    """
    if kind0 == kind1:
        return kind0, True
    elif 'O' in (kind0, kind1):
        return 'O', False
    elif 'f' in (kind0, kind1):
        return 'f', True
    elif 'i' in (kind0, kind1):
        return 'i', True
    else:
        return 'O', False


def remove_namespace_from_string(name):
    """
    Removes the namespace from the given string
    :param name: str, string we want to remove namespace from
    :return: str
    """
    sub_name = name.split(':')
    new_name = ''
    if sub_name:
        new_name = sub_name[-1]
    return new_name


def extrude_vertices_move(MESH_OT_extrude_verts_indiv=None,
    TRANSFORM_OT_translate=None):
    """Extrude vertices and move result

    :param MESH_OT_extrude_verts_indiv: Extrude Only Vertices, Extrude individual vertices only
    :param TRANSFORM_OT_translate: Translate, Translate (move) selected items
    """
    pass


@conf
def gcc_modifier_darwin(conf):
    """Configuration flags for executing gcc on MacOS"""
    v = conf.env
    v.CFLAGS_cshlib = ['-fPIC']
    v.LINKFLAGS_cshlib = ['-dynamiclib']
    v.cshlib_PATTERN = 'lib%s.dylib'
    v.FRAMEWORKPATH_ST = '-F%s'
    v.FRAMEWORK_ST = ['-framework']
    v.ARCH_ST = ['-arch']
    v.LINKFLAGS_cstlib = []
    v.SHLIB_MARKER = []
    v.STLIB_MARKER = []
    v.SONAME_ST = []


def p_load_or_verify(p):
    """ load_or_verify : LOAD
                       | VERIFY
    """
    p[0] = p[1]


def merge_two_dicts(d1, d2):
    """Valid for Python 2 & Python 3"""
    merged = d1.copy()
    merged.update(d2)
    return merged


def __get_vm_port_variable_value(var_config_values, vm_dict):
    """
    Returns the associated OS credentials value
    :param var_config_values: the configuration dictionary
    :param vm_dict: the dictionary containing all VMs where the key is the VM's
                    name
    :return: the value
    """
    port_name = var_config_values.get('port_name')
    vm_name = var_config_values.get('vm_name')
    if port_name and vm_name:
        vm = vm_dict.get(vm_name)
        if vm:
            port_value_id = var_config_values.get('port_value')
            if port_value_id:
                if port_value_id == 'mac_address':
                    return vm.get_port_mac(port_name)
                if port_value_id == 'ip_address':
                    return vm.get_port_ip(port_name)


def translate(value, offset=180):
    """ Transform values to shift origin

    Intended for longitudes in range (-180, 180)
    to shift the 0 meridian to the 180 degree point.
    """
    if value <= 0.0:
        return value + offset
    if value > 0.0:
        return value - offset


def allow_duplicate_nodes(enable=True):
    """
    Nodes with the same full name (including module and class names)
    are not allowed because it means they can't be differentiated
    correctly when unpickling.

    However when reloading modules duplicate nodes occur because
    existing nodes are redeclared. This is something that only
    happens during development, and so this function is here to
    allow that, but the default is not to allow it.
    """
    global _allow_duplicate_nodes
    _allow_duplicate_nodes = enable


def is_col(node, num_rows):
    """Checks if a node in the graph representation of the instance is a column.

    Args:
        node (int): The node ID in the graph representation.
        num_rows (int): The number of rows in the instance.

    Returns:
        bool: True if and only if node is a column.
    """
    return node >= num_rows


@classmethod
def supports_replay_gain(cls):
    """returns True if this class supports ReplayGain"""
    return True


def all_paths(paths, steps, keep_last=False):
    """Get all possible anonymous walks of length up to steps.

	Parameters
	----------

	Returns
	-------
	"""
    new_paths = []
    last_step_paths = [[0, 1]]
    for i in range(2, steps + 1):
        current_step_paths = []
        for j in range(i + 1):
            for walks in last_step_paths:
                if walks[-1] != j and j <= max(walks) + 1:
                    new_paths.append(walks + [j])
                    current_step_paths.append(walks + [j])
        last_step_paths = current_step_paths
    if keep_last:
        new_paths = list(filter(lambda path: len(path) == steps + 1, new_paths)
            )
    paths[steps] = new_paths
    return new_paths


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


def delete_dataset(IdentityPoolId=None, IdentityId=None, DatasetName=None):
    """
    Deletes the specific dataset. The dataset will be deleted permanently, and the action can't be undone. Datasets that this dataset was merged with will no longer report the merge. Any subsequent operation on this dataset will result in a ResourceNotFoundException.
    This API can be called with temporary user credentials provided by Cognito Identity or with developer credentials.
    See also: AWS API Documentation

    :example: response = client.delete_dataset(
        IdentityPoolId='string',
        IdentityId='string',
        DatasetName='string'
    )

    :type IdentityPoolId: string
    :param IdentityPoolId: [REQUIRED] A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region.

    :type IdentityId: string
    :param IdentityId: [REQUIRED] A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region.

    :type DatasetName: string
    :param DatasetName: [REQUIRED] A string of up to 128 characters. Allowed characters are a-z, A-Z, 0-9, '_' (underscore), '-' (dash), and '.' (dot).

    :rtype: dict
    :return: {
        'Dataset': {
            'IdentityId': 'string',
            'DatasetName': 'string',
            'CreationDate': datetime(2015, 1, 1),
            'LastModifiedDate': datetime(2015, 1, 1),
            'LastModifiedBy': 'string',
            'DataStorage': 123,
            'NumRecords': 123
        }
    }

    :returns:
    (dict) -- Response to a successful DeleteDataset request.
    Dataset (dict) -- A collection of data for an identity pool. An identity pool can have multiple datasets. A dataset is per identity and can be general or associated with a particular entity in an application (like a saved game). Datasets are automatically created if they don't exist. Data is synced by dataset, and a dataset can hold up to 1MB of key-value pairs.
    IdentityId (string) -- A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region.
    DatasetName (string) -- A string of up to 128 characters. Allowed characters are a-z, A-Z, 0-9, '_' (underscore), '-' (dash), and '.' (dot).
    CreationDate (datetime) -- Date on which the dataset was created.
    LastModifiedDate (datetime) -- Date when the dataset was last modified.
    LastModifiedBy (string) -- The device that made the last change to this dataset.
    DataStorage (integer) -- Total size in bytes of the records in this dataset.
    NumRecords (integer) -- Number of records in this dataset.

    """
    pass


def capacity():
    """Return the maximum number of (item, score) pairs.

        This is N (the value passed to the constructor).
        """


def softmax(input, dim=-1):
    """Apply the softmax function on given dimension.

    Parameters
    ----------
    input : Tensor
        The input tensor.
    dim : int
        The dimension along which to compute softmax.

    Returns
    -------
    Tensor
        The output tensor.
    """
    pass


def define_position(environment, definition, key_position):
    """
    Get the position

    Arguments
    ---------
        environment:
            The environment

        definition:
            The definition

        key_position:
            The position key
    """
    if key_position in definition:
        environment['position'] = str(definition[key_position])


def get_positive_index(index, size):
    """Used for negative indexing"""
    if index < 0:
        index = size + index
        if index < 0:
            raise ValueError('index is out of range')
    if index >= size:
        raise ValueError('index is out of range')
    return index


@classmethod
def FlushNaviCache(cls):
    """Clear the navigation cache"""
    cls._poscache.Clear()


def delete_network_acl_entry(DryRun=None, NetworkAclId=None, RuleNumber=
    None, Egress=None):
    """
    Deletes the specified ingress or egress entry (rule) from the specified network ACL.
    See also: AWS API Documentation

    Examples
    This example deletes ingress rule number 100 from the specified network ACL.
    Expected Output:

    :example: response = client.delete_network_acl_entry(
        DryRun=True|False,
        NetworkAclId='string',
        RuleNumber=123,
        Egress=True|False
    )

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

    :type NetworkAclId: string
    :param NetworkAclId: [REQUIRED]
            The ID of the network ACL.

    :type RuleNumber: integer
    :param RuleNumber: [REQUIRED]
            The rule number of the entry to delete.

    :type Egress: boolean
    :param Egress: [REQUIRED]
            Indicates whether the rule is an egress rule.

    :return: response = client.delete_network_acl_entry(
        Egress=True,
        NetworkAclId='acl-5fb85d36',
        RuleNumber=100,
    )

    print(response)

    """
    pass


def getANSIfgarray_for_ANSIcolor(ANSIcolor):
    """Return array of color codes to be used in composing an SGR escape
    sequence. Using array form lets us compose multiple color updates without
    putting out additional escapes"""
    return ['38', '5', str(ANSIcolor)]


def primitive_circle_add(size: float=100.0, location: float=(0.0, 0.0)):
    """Add new circle-shaped spline

    :param size: Size, Size of new circle
    :type size: float
    :param location: Location, Location of new circle
    :type location: float
    """
    pass


def _GenerateCRCTable():
    """Generate a CRC-32 table.

        ZIP encryption uses the CRC32 one-byte primitive for scrambling some
        internal keys. We noticed that a direct implementation is faster than
        relying on binascii.crc32().
        """
    poly = 3988292384
    table = [0] * 256
    for i in range(256):
        crc = i
        for j in range(8):
            if crc & 1:
                crc = crc >> 1 & 2147483647 ^ poly
            else:
                crc = crc >> 1 & 2147483647
        table[i] = crc
    return table


def findMeshReferenceImage(overlayList, overlay):
    """Searches the :class:`.OverlayList` and tries to identify a reference
    image for the given :class:`.Mesh` overlay. Returns the identified
    overlay, or ``None`` if one can't be found.
    """
    import fsl.data.vtk as fslvtk
    if not isinstance(overlay, fslvtk.VTKMesh):
        return None
    try:
        prefix = fslvtk.getFIRSTPrefix(overlay.dataSource)
        for ovl in overlayList:
            if prefix.startswith(ovl.name):
                return ovl
    except Exception:
        pass
    return None


@classmethod
def _form_extension_params_segment(cls, extension_params):
    """
        Convert iterable of extension parameters to str segment for header.

        `extension_params` is an iterable where each item is either a parameter
        string or a (name, value) tuple.
        """
    extension_params_segment = ''
    for item in extension_params:
        try:
            extension_params_segment += ';' + item
        except TypeError:
            param_name, param_value = item
            param_value = cls._escape_and_quote_parameter_value(param_value
                =param_value)
            extension_params_segment += ';' + param_name + '=' + param_value
    return extension_params_segment


def describe_db_engine_versions(Engine=None, EngineVersion=None,
    DBParameterGroupFamily=None, Filters=None, MaxRecords=None, Marker=None,
    DefaultOnly=None, ListSupportedCharacterSets=None,
    ListSupportedTimezones=None):
    """
    Returns a list of the available DB engines.
    See also: AWS API Documentation

    Examples
    This example lists settings for the specified DB engine version.
    Expected Output:

    :example: response = client.describe_db_engine_versions(
        Engine='string',
        EngineVersion='string',
        DBParameterGroupFamily='string',
        Filters=[
            {
                'Name': 'string',
                'Values': [
                    'string',
                ]
            },
        ],
        MaxRecords=123,
        Marker='string',
        DefaultOnly=True|False,
        ListSupportedCharacterSets=True|False,
        ListSupportedTimezones=True|False
    )

    :type Engine: string
    :param Engine: The database engine to return.

    :type EngineVersion: string
    :param EngineVersion: The database engine version to return.
            Example: 5.1.49

    :type DBParameterGroupFamily: string
    :param DBParameterGroupFamily: The name of a specific DB parameter group family to return details for.
            Constraints:
            Must be 1 to 255 alphanumeric characters
            First character must be a letter
            Cannot end with a hyphen or contain two consecutive hyphens

    :type Filters: list
    :param Filters: Not currently supported.
            (dict) --This type is not currently supported.
            Name (string) -- [REQUIRED]This parameter is not currently supported.
            Values (list) -- [REQUIRED]This parameter is not currently supported.
            (string) --

    :type MaxRecords: integer
    :param MaxRecords: The maximum number of records to include in the response. If more than the MaxRecords value is available, a pagination token called a marker is included in the response so that the following results can be retrieved.
            Default: 100
            Constraints: Minimum 20, maximum 100.

    :type Marker: string
    :param Marker: An optional pagination token provided by a previous request. If this parameter is specified, the response includes only records beyond the marker, up to the value specified by MaxRecords .

    :type DefaultOnly: boolean
    :param DefaultOnly: Indicates that only the default version of the specified engine or engine and major version combination is returned.

    :type ListSupportedCharacterSets: boolean
    :param ListSupportedCharacterSets: If this parameter is specified and the requested engine supports the CharacterSetName parameter for CreateDBInstance , the response includes a list of supported character sets for each engine version.

    :type ListSupportedTimezones: boolean
    :param ListSupportedTimezones: If this parameter is specified and the requested engine supports the TimeZone parameter for CreateDBInstance , the response includes a list of supported time zones for each engine version.

    :rtype: dict
    :return: {
        'Marker': 'string',
        'DBEngineVersions': [
            {
                'Engine': 'string',
                'EngineVersion': 'string',
                'DBParameterGroupFamily': 'string',
                'DBEngineDescription': 'string',
                'DBEngineVersionDescription': 'string',
                'DefaultCharacterSet': {
                    'CharacterSetName': 'string',
                    'CharacterSetDescription': 'string'
                },
                'SupportedCharacterSets': [
                    {
                        'CharacterSetName': 'string',
                        'CharacterSetDescription': 'string'
                    },
                ],
                'ValidUpgradeTarget': [
                    {
                        'Engine': 'string',
                        'EngineVersion': 'string',
                        'Description': 'string',
                        'AutoUpgrade': True|False,
                        'IsMajorVersionUpgrade': True|False
                    },
                ],
                'SupportedTimezones': [
                    {
                        'TimezoneName': 'string'
                    },
                ]
            },
        ]
    }

    """
    pass


def set_jugdir(jugdir):
    """
    store = set_jugdir(jugdir)

    Sets the jugdir. This is the programmatic equivalent of passing
    ``--jugdir=...`` on the command line.

    Parameters
    ----------
    jugdir : str

    Returns
    -------
    store : a jug backend
    """
    from .task import Task
    from . import backends
    if jugdir is None:
        jugdir = 'jugdata'
    store = backends.select(jugdir)
    Task.store = store
    return store


@staticmethod
def _add_func(functype, obj, funcname, func):
    """
        Adds `func` to `obj` as `funcname` using `setattr()`, but adds
        `funcname` to set given by `obj._extrattrs[functype]` for tracking
        purposes.
        """
    if funcname not in obj._extra_attrs[functype]:
        obj._extra_attrs[functype].append(funcname)
    setattr(obj, funcname, func)


def all_values(json_rec, field_name, subfield_name=None):
    """
    This is a helper function that, given a field name, returns an iterator over all values in the field regardless of
    if the field contains an array or a single value.
    :param json_rec: JSON record
    :param field_name: field to contain either array or a single value
    :return: iterator over the values
    """
    if field_name not in json_rec:
        return
    field = json_rec[field_name][subfield_name] if subfield_name else json_rec[
        field_name]
    if isinstance(field, list):
        for k in field:
            yield k
    else:
        yield field


def __validate_params(h, params, no_questions):
    """Validate header parameters"""
    if no_questions:
        return True
    print('**** PARAMETERS ****')
    print('         Description: {}'.format(h.description))
    print('         Sample Rate: {:d} ({:.1f} real)'.format(h.sampleRate, h
        .realSampleRate))
    print('  Number of Channels: {}'.format(h.numberOfChannels))
    print('           Wake Time: {}'.format(params['wake_time'].isoformat()))
    print('            End Time: {}'.format(params['end_time'].isoformat()))
    print('     Output Filename: {}'.format(params['filename_prefix'] +
        '.header.raw.lch'))
    resp = input('Is this acceptable? [y/N]: ')
    if not resp:
        return False
    if resp[0].lower() == 'y':
        return True
    return False


def get_member(userid, location=None):
    """Get member object for ``userid``, or None if no such member
        object within the site at the given ``location`` if provided.

        :return: an :py:class:`~silva.core.interfaces.auth.IMember`
                 object or None.
        """


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


def ctime():
    """Return a string representing the date.

        For example date(2002, 12, 4).ctime() == 'Wed Dec 4 00:00:00 2002'.
        d.ctime() is equivalent to time.ctime(time.mktime(d.timetuple()))
        on platforms where the native C ctime() function
        (which time.ctime() invokes, but which date.ctime() does not invoke)
        conforms to the C standard.
        """


def default_handle_failed_alternative_encryption(exception):
    """
    Handle failures when trying to encrypt alternative content for messages
    """
    raise exception


def spmax(a):
    """
    Maximum value in a matrix or vector to deal with sparse and dense objects

    Parameters
    ----------
    a           : array or sparse matrix
                  Object with one or more columns.

    Returns
    -------
    max a       : int or float
                  maximum value in a
    """
    return a.max()


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 set_tensor_linop_backend(backend):
    """Set the default backend used for tensor network linear operators, via
    'opt_einsum'. This is different from the default contraction backend as
    the contractions are likely repeatedly called many times.

    See Also
    --------
    get_tensor_linop_backend, set_contract_backend, get_contract_backend,
    TNLinearOperator
    """
    global _TENSOR_LINOP_BACKEND
    _TENSOR_LINOP_BACKEND = backend


def dict_scrub(data):
    """This method will clean a dictionary and bring any of its data types
        to the standard built-in types or types that are known to marshall.
        """


@staticmethod
def is_same_road(lane_index_1, lane_index_2, same_lane=False):
    """
            Is lane 1 in the same road as lane 2?
        """
    return lane_index_1[:2] == lane_index_2[:2] and (not same_lane or
        lane_index_1[2] == lane_index_2[2])


def add(name, **spider_args):
    """Add a spider to the queue given its name a some spider arguments.

        This method can return a deferred. """


@classmethod
def stop_recording_skipped(cls):
    """
        Stop collecting OptionErrors recorded with the
        record_skipped_option method and return them
        """
    if cls._errors_recorded is None:
        raise Exception('Cannot stop recording before it is started')
    recorded = cls._errors_recorded[:]
    cls._errors_recorded = None
    return recorded


def strip_trailing_newline(text):
    """
    Strips a newline from the end of text.
    """
    if text.endswith('\n'):
        text = text[:-1]
    return text


def environmentfilter(f):
    """Decorator for marking environment dependent filters.  The current
    :class:`Environment` is passed to the filter as first argument.
    """
    f.environmentfilter = True
    return f


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


def array_bounds(height, width, transform):
    """Return the bounds of an array given height, width, and a transform.

    Return the `west, south, east, north` bounds of an array given
    its height, width, and an affine transform.
    """
    w, n = transform.xoff, transform.yoff
    e, s = transform * (width, height)
    return w, s, e, n


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

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

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


@classmethod
def get_tablename(cls, table_id):
    """Get a table name."""
    return table_id if table_id in cls.get_tablenames() else None


def register_handler(handler):
    """
    Install application-specific HDF5 image handler.

    :param handler: Handler object.
    """
    global _handler
    _handler = handler


def get_label_identifier(label, current_file):
    """Return unique label identifier

    Parameters
    ----------
    label : str
        Database-internal label
    current_file
        Yielded by pyannote.database protocols

    Returns
    -------
    unique_label : str
        Global label
    """
    database = current_file['database']
    return database + '|' + label


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


def get_displacement(offset):
    """Calculate the displacement."""
    result = 0
    while offset >= 16:
        offset >>= 1
        result += 1
    return result


def FitPowerLaw(x, y):
    """
	Fits the input data in the form
		y = a*x^b
	returns a,b
	"""
    import scipy.optimize as optimize
    fFit = lambda p, x: p[0] * x ** p[1]
    fErr = lambda p, x, y: y - fFit(p, x)
    p0 = [max(y), -1.0]
    out = optimize.leastsq(fErr, p0, args=(x, y), full_output=1)
    pOut = out[0]
    b = pOut[1]
    a = pOut[0]
    return a, b


def vowels_between_consonants(name1):
    """Vowels between consonants find the vowels mapping between consonant
       example: pradeeip-----> {a,eei}
    """
    list_consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm',
        'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z']
    index_list = []
    ans_list = []
    for index, item in enumerate(name1):
        if item in list_consonants:
            index_list.append(index)
    if index_list[0] not in list_consonants:
        ans_list.append(name1[:index_list[0]])
    for i in range(len(index_list) - 1):
        ans_list.append(name1[index_list[i] + 1:index_list[i + 1]])
    if index_list[-1] < len(name1) - 1:
        ans_list.append(name1[index_list[-1] + 1:])
    ans_list = list(filter(None, ans_list))
    return ans_list


@staticmethod
def color_difference(testColor, otherColor):
    """test diff between two rgbs"""
    difference = 0
    difference += abs(testColor[0] - otherColor[0])
    difference += abs(testColor[1] - otherColor[1])
    difference += abs(testColor[2] - otherColor[2])
    return difference


def build_manifest():
    """I generate a table of everything reachable from this directory.
        I also compute deep-stats as described below.

        I return a Monitor. The Monitor's results will be a dictionary with
        four elements:

         res['manifest']: a list of (path, cap) tuples for all nodes
                          (directories and files) reachable from this one.
                          'path' will be a tuple of unicode strings. The
                          origin dirnode will be represented by an empty path
                          tuple.
         res['verifycaps']: a list of (printable) verifycap strings, one for
                            each reachable non-LIT node. This is a set:
                            it will contain no duplicates.
         res['storage-index']: a list of (base32) storage index strings,
                               one for each reachable non-LIT node. This is
                               a set: it will contain no duplicates.
         res['stats']: a dictionary, the same that is generated by
                       start_deep_stats() below.

        The Monitor will also have an .origin_si attribute with the (binary)
        storage index of the starting point.
        """


def is_autosome(chrom):
    """
    Returns true if the given chromosome label likely refers to an autosome.

    :param str chrom: Chromosome label
    """
    if chrom[-7:] == '_random':
        return False
    try:
        int(chrom[3:])
    except ValueError:
        return False
    return True


def uncomment():
    """Convert selected comment to text

    """
    pass


def run(*argv, **kwargs):
    """
    Runs a command and returns the stdout, stderr and returncode
    using `run
    <https://docs.python.org/3.5/library/subprocess.html?highlight=popen#subprocess.run>`_.
    >>> run('ls')["returncode"] == 0
    True
    >>> 'SHELL' not in run('echo $SHELL', shell=True)['stdout']
    True
    >>> run(['ls', 'foo'])['returncode'] > 0
    True
    """
    import sys
    if sys.version_info[0] < 3:
        import subprocess32 as subprocess
    else:
        import subprocess
    defaults = {'stdout': subprocess.PIPE, 'stderr': subprocess.PIPE}
    defaults.update(kwargs)
    proc = subprocess.run(*argv, **defaults).__dict__
    if 'text' not in kwargs or kwargs['text']:
        proc['stdout'] = proc['stdout'].decode()
        proc['stderr'] = proc['stderr'].decode()
    return proc


def announce(*a) ->None:
    """Make this message stand out from all the noise in the console."""
    print('******** ', *a)


def fix_saving_name(name):
    """Neutralizes backslashes in Arch-Vile frame names"""
    return name.rstrip('\x00').replace('\\', '`')


def num2percent(num):
    """
    Return `num` (float or int) as human-readable percentage

    >>> num2percent(7.3188)
    '  7%'
    """
    return '{:3.0f}%'.format(float(num))


def _search_on_path(filenames):
    """Find file on system path."""
    from os.path import exists, abspath, join
    from os import pathsep, environ
    search_path = environ['PATH']
    paths = search_path.split(pathsep)
    for path in paths:
        for filename in filenames:
            if exists(join(path, filename)):
                return abspath(join(path, filename))


def writeSequence(data):
    """
        Write an iterable of byte strings to the physical connection.

        If possible, make sure that all of the data is written to
        the socket at once, without first copying it all into a
        single byte string.

        @type data: an iterable of L{bytes}
        @param data: The data to write.
        """


@classmethod
def load(cls, data):
    """
        Convert "UserComment" value in exif format to str.

        :param bytes data: "UserComment" value from exif
        :return: u"foobar"
        :rtype: str(Unicode)
        :raises: ValueError if the data does not conform to the EXIF specification,
        or the encoding is unsupported.
        """
    if len(data) < cls._PREFIX_SIZE:
        raise ValueError('not enough data to decode UserComment')
    prefix = data[:cls._PREFIX_SIZE]
    body = data[cls._PREFIX_SIZE:]
    if prefix == cls._UNDEFINED_PREFIX:
        raise ValueError('prefix is UNDEFINED, unable to decode UserComment')
    try:
        encoding = {cls._ASCII_PREFIX: cls.ASCII, cls._JIS_PREFIX: cls._JIS,
            cls._UNICODE_PREFIX: cls._UNICODE}[prefix]
    except KeyError:
        raise ValueError('unable to determine appropriate encoding')
    return body.decode(encoding, errors='replace')


@classmethod
def disable(cls):
    """Disables the CSS agent for the given page.
        """
    return cls.build_send_payload('disable', {}), None


def execute():
    """Executes the request and returns a ValidationResult object"""


@staticmethod
def _verify_source_and_target(source, target):
    """
        Checks that the dimensions and number of points match up of the source
        and the target.

        Parameters
        ----------
        source : :map:`PointCloud`
            A PointCloud that the alignment will be based from
        target : :map:`PointCloud`
            A PointCloud that the alignment is targeted towards

        Raises
        ------
        ValueError
            Source and target must have the same dimensionality
        ValueError
            Source and target must have the same number of points
        """
    if source.n_dims != target.n_dims:
        raise ValueError('Source and target must have the same dimensionality')
    elif source.n_points != target.n_points:
        raise ValueError(
            'Source and target must have the same number of points')


def fortran_to_value(fortran_value):
    """Return a Python compatible version of a FORTRAN argument.

    Parameters
    ----------
    fortran_value : str
        A FORTRAN argument.

    Returns
    -------
    value : bool | int | float | str
        A Python friendly representation of the input value.
    """
    if fortran_value == '.true.':
        return True
    elif fortran_value == '.false.':
        return False
    try:
        value = int(fortran_value)
    except ValueError:
        try:
            value = float(fortran_value)
        except ValueError:
            value = fortran_value.strip("'")
    return value


def pers(n):
    """ 返回指定数量的%s，中间用逗号隔开
    --
        @example
            pers(5)
        return: %s, %s, %s, %s, %s

    """
    return ', '.join(['%s' for i in range(n)])


@classmethod
def get_valid_format_order(cls, format_target, format_order=None):
    """ Checks to see if the target format string follows the proper style
        """
    format_order = format_order or cls.parse_format_order(format_target)
    cls.validate_no_token_duplicates(format_order)
    format_target = cls.remove_tokens(format_target, format_order)
    format_target = cls.remove_static_text(format_target)
    cls.validate_separator_characters(format_target)
    cls.validate_matched_parenthesis(format_target)
    return format_order


def local_pose_to_global_pose(pose1, pose2):
    """
    Applies the transform from pose1 to pose2
    :param pose1: instance of :py:class:`util.Pose`
    :param pose2: instance of :py:class:`util.Pose`
    """
    return pose1.transform().apply_to_pose(pose2)


@classmethod
def unpack(cls, data):
    """ Performs raw unpacking with the smartyparser in self.PARSER.
        """
    unpacked = cls.PARSER.unpack(data)
    self = cls(_control=unpacked)
    self._packed = memoryview(data)
    return self


def load_Xlib_display(finder, module):
    """the Xlib.display module implicitly loads a number of extension modules;
       make sure this happens."""
    finder.IncludeModule('Xlib.ext.xtest')
    finder.IncludeModule('Xlib.ext.shape')
    finder.IncludeModule('Xlib.ext.xinerama')
    finder.IncludeModule('Xlib.ext.record')
    finder.IncludeModule('Xlib.ext.composite')
    finder.IncludeModule('Xlib.ext.randr')


def new():
    """Add New Pose Library to active Object

    """
    pass


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


@classmethod
def from_dict(cls, settings, tool_dict):
    """ Create an ExcellonTool from a dict.

        Parameters
        ----------
        settings : FileSettings (dict-like)
            Excellon File-wide settings

        tool_dict : dict
            Excellon tool parameters as a dict

        Returns
        -------
        tool : ExcellonTool
            An ExcellonTool initialized with the parameters in tool_dict.
        """
    return cls(settings, **tool_dict)


def get_listOfReactants(reaction):
    """Get list of reactants of a reaction

    Args:
        reaction (xml.etree.ElementTree.Element): reaction

    Returns:
        xml.etree.ElementTree.Element: list of reactants
    """
    listOfReactants = None
    for e in reaction:
        if e.tag[0] == '{':
            uri, tag = e.tag[1:].split('}')
        else:
            tag = e.tag
        if tag == 'listOfReactants':
            listOfReactants = e
            break
    return listOfReactants


def run(_):
    """Function to execute when the post-merge hook is called. """
    pass


def inverse_pose(pose):
    """
    Same as pose.inverse()
    :param pose: instance of C{Pose}
    """
    return pose.transform().inverse().pose()


def is_requirements_file(filename):
    """Return True if filename is Python file."""
    if filename.endswith('.txt') and 'requirements' in filename:
        return True
    return False


def unsetf(flags, flag):
    """
     unsets flag, adding to flags
    :param flags: current flag value
    :param flag: flag to unset
    :return: new flag value
    """
    return flags & ~flag


def enable_lazy():
    """Convenience function for configuring _() to use lazy gettext

    Call this at the start of execution to enable the gettextutils._
    function to use lazy gettext functionality. This is useful if
    your project is importing _ directly instead of using the
    gettextutils.install() way of importing the _ function.
    """
    global USE_LAZY
    USE_LAZY = True


def iter_stack(stack):
    """Iterate through the items on the stack.

	:param stack stack: A stack.
	:rtype: iterator
	"""
    while stack:
        item, stack = stack
        yield item


def discard_value(collection, key, value):
    """ Discard an element from a value set.

    For a `collection` that maps `key` to {`value1`, `value2`, ...}, discard
    a specific `value` from the value set and drop the entire entry if the
    set becomes empty.
    """
    try:
        values = collection[key]
    except KeyError:
        pass
    else:
        values.discard(value)
        if not values:
            del collection[key]


def get_cigar(var):
    """
    Return the cigar string describing how to align an
    alternate allele to the reference allele
    """
    return var.INFO.get('CIGAR')


@staticmethod
def save(file_path, model):
    """
        Save the model onto the file identified by file_path.

        Parameters
        ----------
        file_path : str
            The path to the filename where the model has to be saved
        model : RTEnsemble
            The model RTEnsemble model to save on file

        Returns
        -------
        status : bool
            Returns true if the save is successful, false otherwise
        """
    raise NotImplementedError('Feature not implemented!')


def sync_frame_initializer(new_frame, reference_frame):
    """Set the initializers of the new_frame to be the same as the reference_frame,
    for both the default initializer and per-column initializers.

    Parameters
    ----------
    new_frame : Frame
        The frame to set initializers
    reference_frame : Frame
        The frame to copy initializers
    """
    new_frame._default_initializer = reference_frame._default_initializer
    new_frame._initializers = reference_frame._initializers


def get_pairs(vals):
    """
    takes 1D list `vals` and returns 1D list of pairs.
    if input does not have an even number of elements,
    a 0 is padded at the end
    """
    if len(vals) % 2 == 1:
        vals = vals + [0.0]
    return zip(vals[::2], vals[1::2])


def copy():
    """Copy selected keyframes to the copy/paste buffer

    """
    pass


def _check_not_tuple_of_2_elements(obj, obj_name='obj'):
    """Check object is not tuple or does not have 2 elements."""
    if not isinstance(obj, tuple) or len(obj) != 2:
        raise TypeError('%s must be a tuple of 2 elements.' % obj_name)


@classmethod
def command_line_name(cls):
    """Convert class name to lowercase with underscores.

        i.e. turn HttpMethods to http_methods.
        """
    final_string = cls.__name__[0].lower()
    for character in cls.__name__[1:]:
        if character.isupper():
            final_string += f'_{character.lower()}'
        else:
            final_string += character
    return final_string


def dictifyatts(varptr, tag):
    """
    read netcdf attributes and return them as a dict

    :param varptr: pointer to a netcdf variable object
    :param tag: string to add to the beginning of the keys in the dict
    :return: the attributes as a dict where the keys are the attribute names and the values are the attribute data
    """
    theDict = {}
    for key in varptr.ncattrs():
        if key.startswith('Instrument_'):
            n = key.find('_')
            newkey = tag + key[n + 1:]
        else:
            newkey = tag + key
        theDict[newkey] = varptr.getncattr(key)
    return theDict


def disconnect_hair(all: bool=False):
    """Disconnect hair from the emitter mesh

    :param all: All hair, Disconnect all hair systems from the emitter mesh
    :type all: bool
    """
    pass


def reconnect(connection):
    """
    Reconnect to server

    @Args:
    * [connection] connection to reconnect
    """
    connection.connect()


def get_overlap_score(candidate, target):
    """Takes a candidate word and a target word and returns the overlap
    score between the two.

    Parameters
    ----------
    candidate : str
        Candidate word whose overlap has to be detected.
    target : str
        Target word against which the overlap will be detected

    Returns
    -------
    float
        Overlap score betwen candidate and the target.

    """
    if len(candidate) < len(target):
        temp = candidate
        candidate = target
        target = temp
    overlap = 0.0
    while len(target) >= 2:
        if target in candidate:
            overlap = len(target)
            return overlap * 1.0 / len(candidate)
        else:
            target = target[:-1]
    return 0.0


@classmethod
def readable_size(C, bytes, suffix='B', decimals=1, sep='\xa0'):
    """given a number of bytes, return the file size in readable units"""
    if bytes is None:
        return
    size = float(bytes)
    for unit in C.SIZE_UNITS:
        if abs(size) < 1024 or unit == C.SIZE_UNITS[-1]:
            return '{size:.{decimals}f}{sep}{unit}{suffix}'.format(size=
                size, unit=unit, suffix=suffix, sep=sep, decimals=C.
                SIZE_UNITS.index(unit) > 0 and decimals or 0)
        size /= 1024


def generate_completions(event):
    """
    Tab-completion: where the first tab completes the common suffix and the
    second tab lists all the completions.
    """
    b = event.current_buffer
    if b.complete_state:
        b.complete_next()
    else:
        b.start_completion(insert_common_part=True)


def make_footer() ->str:
    """Makes a footer to be appended to the bottom of other, actionable
    responses.
    """
    return """To make your next move, respond to Chess Bot with

```do <your move>```

*Remember to @-mention Chess Bot at the beginning of your response.*"""


@classmethod
def detail(cls, cluster, replication_data=False, flat=False):
    """Detailed view of a cluster."""
    result = cls.summary(cluster, flat=True)
    result.update(num_hosts=cluster.num_hosts, num_down_hosts=cluster.
        num_down_hosts, last_heartbeat=cls._normalize(cluster.
        last_heartbeat), created_at=cls._normalize(cluster.created_at),
        updated_at=cls._normalize(cluster.updated_at), disabled_reason=
        cluster.disabled_reason, replication_status=cluster.
        replication_status, frozen=cluster.frozen, active_backend_id=
        cluster.active_backend_id)
    if not replication_data:
        for field in ('replication_status', 'frozen', 'active_backend_id'):
            del result[field]
    if flat:
        return result
    return {'cluster': result}


def logging_options(parser):
    """Add cli options for logging to parser"""
    LOG_LEVELS = 'critical', 'error', 'warning', 'notice', 'info', 'debug'
    parser.add_argument('--log-file')
    parser.add_argument('--log-file-level', choices=LOG_LEVELS, default='debug'
        )
    stderr_parser = parser.add_mutually_exclusive_group()
    stderr_parser.add_argument('--stderr-level', choices=LOG_LEVELS,
        default='notice')
    stderr_parser.add_argument('--quiet', '-q', default=False, action=
        'store_true')
    stderr_parser.add_argument('--verbose', '-v', default=False, action=
        'store_true')


@staticmethod
def _get_address_family(table):
    """
        Function to derive address family from a junos table name.

        :params table: The name of the routing table
        :returns: address family
        """
    address_family_mapping = {'inet': 'ipv4', 'inet6': 'ipv6', 'inetflow':
        'flow'}
    family = table.split('.')[-2]
    try:
        address_family = address_family_mapping[family]
    except KeyError:
        address_family = family
    return address_family


def round_up(rounded, divider):
    """Round up an integer to a multiple of divider."""
    return int(rounded + divider - 1) // divider * divider


@classmethod
def is_valid(cls, conversion_time):
    """Validates conversion time

        :param conversion_time: conversion time to validate
        :type conversion_time: int
        :return: True if conversion time is valid, False otherwise
        :rtype: boolean
        """
    return conversion_time >= cls.TIME_MIN and conversion_time <= cls.TIME_MAX


def number_of_common_3grams(string1, string2):
    """ Return the number of common tri-grams in two strings
    """
    tri_grams = set(zip(string1, string1[1:], string1[2:]))
    tri_grams = tri_grams.intersection(zip(string2, string2[1:], string2[2:]))
    return len(tri_grams)


def ensure_sphinx_astropy_installed():
    """
    Make sure that sphinx-astropy is available.

    This returns the available version of sphinx-astropy as well as any
    paths that should be added to sys.path for sphinx-astropy to be available.
    """
    sys_path_inserts = []
    sphinx_astropy_version = None
    try:
        from sphinx_astropy import __version__ as sphinx_astropy_version
    except ImportError:
        raise ImportError(
            'sphinx-astropy needs to be installed to buildthe documentation.')
    return sphinx_astropy_version, sys_path_inserts


def set_args(a):
    """Set cmd-line args for use in rest of file
	"""
    global args
    args = a


def provideFeature(name):
    """Record that a named feature is available in this context."""


def displayName(name):
    """
    Converts a GSSAPI Name into a String

    This function is essentially the opposite of :func:`importName`:
    it takes a GSSAPI name and converts it back into a string and
    name type.

    :param name: a GSSAPI name capsule
    :returns: a tuple containing the string-version of the name
              and its name type
    :rtype: (bytes, :class:`gssapi.base.types.NameType`)
    :except GSSError:
    """


def calculate_absolute_position_non_replaced_height(node, context):
    """Implements S10.6.7"""
    raise NotImplementedError('Section 10.6.7')


def provider_parser(subparser):
    """Configure provider parser for Zonomi"""
    subparser.add_argument('--auth-token', help=
        'specify token for authentication')
    subparser.add_argument('--auth-entrypoint', help=
        'use Zonomi or Rimuhosting API', choices=['zonomi', 'rimuhosting'])


def suppress_context(exc):
    """
    This is used to mask an exception with another one.

    For instance, below, the divide by zero error is masked by the CustomException.
        try:
            1/0
        except ZeroDivisionError:
            raise suppress_context(CustomException())

    Note: In python 3, the last line would simply be raise CustomException() from None
    :param exc: new Exception that will be raised
    :return: Exception to be raised
    """
    exc.__cause__ = None
    return exc


def simplify_successful_results(results):
    """
    Removes all information besides whether the run was successful from given results
    """
    for from_host in results:
        for to_host in results[from_host]:
            for port in results[from_host][to_host]:
                if results[from_host][to_host][port]['success']:
                    results[from_host][to_host][port] = {'success': True}
                else:
                    results[from_host][to_host][port] = {'success': False}


@classmethod
def has_resuming(cls):
    """Returns whether it supports to resume the fetch process.

        :returns: this backend supports items resuming
        """
    return False


def all_dependents(object=True):
    """ Returns a list of all the dependents (including dependents
            of dependents) of a ticket
        """


def algorithm_key_lengths(algorithm):
    """Return the possible key lengths for the configured algorithm."""
    from pskc.exceptions import DecryptionError
    if algorithm is None:
        raise DecryptionError('No algorithm specified')
    elif algorithm.endswith('#aes128-cbc') or algorithm.endswith('#aes192-cbc'
        ) or algorithm.endswith('#aes256-cbc'):
        return [int(algorithm[-7:-4]) // 8]
    elif algorithm.endswith('#tripledes-cbc') or algorithm.endswith(
        '#kw-tripledes'):
        return [16, 24]
    elif algorithm.endswith('#kw-aes128') or algorithm.endswith('#kw-aes192'
        ) or algorithm.endswith('#kw-aes256'):
        return [int(algorithm[-3:]) // 8]
    elif algorithm.endswith('#camellia128-cbc') or algorithm.endswith(
        '#camellia192-cbc') or algorithm.endswith('#camellia256-cbc'):
        return [int(algorithm[-7:-4]) // 8]
    elif algorithm.endswith('#kw-camellia128') or algorithm.endswith(
        '#kw-camellia192') or algorithm.endswith('#kw-camellia256'):
        return [int(algorithm[-3:]) // 8]
    else:
        raise DecryptionError('Unsupported algorithm: %r' % algorithm)


def should_ignore_line(line, strings_to_ignore):
    """Return true if line contains a rule name in `rule_names`."""
    for string in strings_to_ignore:
        if string in line:
            return True
    return False


def _regex_to_postfix(regex):
    """
    Convert infix regular expression into postfix w/ implicit concatenation.

    Parameters
    ----------
    regex : str
        Regular expression -- accepts only ( | ) * + ?

    Returns
    -------
    str

    Notes
    -----
    Translated from Russ Cox's C implementation of
    Ken Thompson's Regular Expression Search Algorithm:
    https://swtch.com/~rsc/regexp/dfa0.c.txt (MIT License)

    See also http://swtch.com/~rsc/regexp/ and
    Thompson, Ken.  Regular Expression Search Algorithm,
    Communications of the ACM 11(6) (June 1968), pp. 419-422.

    """
    nalt = 0
    natom = 0
    dst = []
    paren = []
    if not len(regex) > 0:
        raise ValueError('Regular expression is empty.')
    for _ in regex:
        if _ == '(':
            if natom > 1:
                natom = natom - 1
                dst.append('.')
            paren.append((nalt, natom))
            nalt = 0
            natom = 0
        elif _ == '|':
            if natom == 0:
                raise ValueError('Regex is missing an expression before |.')
            natom -= 1
            while natom > 0:
                dst.append('.')
                natom -= 1
            nalt += 1
        elif _ == ')':
            if not paren:
                raise ValueError('Regex parentheses do not match.')
            if natom == 0:
                raise ValueError('Regex parentheses are missing an expression.'
                    )
            natom -= 1
            while natom > 0:
                dst.append('.')
                natom -= 1
            while nalt > 0:
                dst.append('|')
                nalt -= 1
            nalt, natom = paren.pop()
            natom += 1
        elif _ in ('*', '+', '?'):
            if natom == 0:
                raise ValueError(
                    'Regex operator %s requires an expression.' % _)
            dst.append(_)
        else:
            if natom > 1:
                natom -= 1
                dst.append('.')
            dst.append(_)
            natom += 1
    natom -= 1
    while natom > 0:
        dst.append('.')
        natom -= 1
    while nalt > 0:
        dst.append('|' * nalt)
        nalt -= 1
    return ''.join(dst)


def conj(x):
    """Apply complex conjugation to torch ComplexTensor

    Parameters
    ----------
    x : :obj:`pytorch_complex_tensor.ComplexTensor`
        Torch ComplexTensor

    Returns
    -------
    x : :obj:`pytorch_complex_tensor.ComplexTensor`
        Complex conjugated Torch ComplexTensor

    """
    xc = x.__graph_copy__(x.real, -x.imag)
    return xc


def __insert_color(txt, s, c):
    """insert HTML span style into txt. The span will change the color of the
    text located between s[0] and s[1]:
    txt: txt to be modified
    s: span of where to insert tag
    c: color to set the span to"""
    return txt[:s[0]] + ''.format(c) + txt[s[0]:s[1]
        ] + '' + txt[s[1]:]


def read_data(filename, options=''):
    """same as readdata in cpptraj

    Returns
    -------
    out : CpptrajDatasetList
    """
    from pytraj.datasets import CpptrajDatasetList
    cdslist = CpptrajDatasetList()
    cdslist.read_data(filename, options)
    return cdslist


@classmethod
def crop_sizes(cls, original_width, original_height, target_width,
    target_height):
    """
        Calculate crop parameters for outbound mode
        :param original_width: int
        :param original_height: int
        :param target_width: int
        :param target_height: int
        :return: tuple(int, int, int, int)
        """
    if target_width < original_width:
        left = abs(original_width - target_width) / 2
        right = left + target_width
    else:
        left = 0
        right = original_width
    if target_height < original_height:
        upper = abs(original_height - target_height) / 2
        lower = upper + target_height
    else:
        upper = 0
        lower = original_height
    return left, upper, right, lower


@staticmethod
def _check_valid_region_arg(region):
    """
		Check that the string passed is a valid brain region name.

		:param region: string, acronym of a brain region according to the Allen Brain Atlas.

		"""
    if not isinstance(region, int) and not isinstance(region, str):
        raise ValueError('region must be a list, integer or string, not: {}'
            .format(type(region)))
    else:
        return True


def paramstopot(thresh, shape, scale):
    """transform shape scale for peak over threshold

    y = x-u|x>u ~ GPD(k, sigma-k*u) if x ~ GPD(k, sigma)
    notation of de Zea Bermudez, Kotz
    k, sigma is shape, scale
    """
    return shape, scale - shape * thresh


@staticmethod
def __normalize(a):
    """
        Normalizes an array.
        Parameters
        -----------
        a : list
           The array to normalize
        """
    return (a - min(a)) / (max(a) - min(a))


@staticmethod
def is_not_sw(sw_name):
    """
        检查是否是正常的软件而非烧录bin或者OTA包
        :param sw_name:
        :return:
        """
    return sw_name.startswith('EMMCBIN') or sw_name.startswith('NANDBIN'
        ) or sw_name.startswith('OTA')


def extract_validatable_type(type_name, models):
    """Returns a jsonschema-compatible typename from the Swagger type.

    This is necessary because for our Swagger specs to be compatible with
    swagger-ui, they must not use a $ref to internal models.

    :returns: A key-value that jsonschema can validate. Key will be either
        'type' or '$ref' as is approriate.
    :rtype: dict
    """
    if type_name in models:
        return {'$ref': type_name}
    else:
        return {'type': type_name}


def getHistory(obj, oldestFirst=False, preserve=(), countPurged=True):
    """Returns the history of a content.

        Return the oldest version first  when ``oldestFirst`` set to
        ``True``. Default is ``False`` (youngest version first).

        Returns a sequence (``IHistory``) of ``IVersionData`` objects.

        Also counts purged versions if ``True`` is passed to ``countPurged``
        (see interface documentation for details).
        """


def hex_string_to_int(hexstring, pos=0, length=4, shift=8):
    """
    Converts a hex string to an integer
    """
    total = 0
    shift_multiplier = length
    for i in range(pos, pos + length):
        shift_multiplier -= 1
        total += ord(hexstring[i]) << shift * shift_multiplier
    return total


def isinteger(astring):
    """Is the given string an integer?"""
    try:
        int(astring)
    except ValueError:
        return False
    else:
        return True


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


@classmethod
def add_column_data(cls, name, dtype, transform):
    """
        Function-based approach to modifying the class-specific
        :attr:`.__column_data_map` attribute. Must use :func:`getattr`
        to prevent class-private name mangling

        Parameters
        ----------
        name: str
            Name of the new column_data field
        dtype: str
            The SQL data type to encode the column as
        transform: function
            The function to extract the value of the column_data from a record
        """
    try:
        getattr(cls, '_{}__column_data_map'.format(cls.__name__))[name
            ] = dtype, transform
    except:
        setattr(cls, '_{}__column_data_map'.format(cls.__name__), {name: (
            dtype, transform)})


def get_value(hw_lst, level1, level2, level3):
    """Get an specific value from the hardware inventory."""
    for entry in hw_lst:
        if level1 == entry[0] and level2 == entry[1] and level3 == entry[2]:
            return entry[3]
    return None


def _check_weights(weights):
    """Check to make sure weights are valid"""
    if weights in (None, 'uniform', 'distance'):
        return weights
    elif callable(weights):
        return weights
    else:
        raise ValueError(
            "weights not recognized: should be 'uniform', 'distance', or a callable function"
            )


def apply_move(grid, move):
    """Try to move: return a new grid, or None if illegal."""
    p, q = grid
    bit = 1 << move
    return (q, p | bit) if 0 == bit & (p | q) else None


def location_to_string(locationID):
    """
    helper to calculate port and bus number from locationID
    """
    loc = ['{}-'.format(locationID >> 24)]
    while locationID & 15728640:
        if len(loc) > 1:
            loc.append('.')
        loc.append('{}'.format(locationID >> 20 & 15))
        locationID <<= 4
    return ''.join(loc)


def _split_EP_days(hourly_series):
    """
    Splits the hourly series of EP simulations that simulate multiple days in different seasons into specific energyhub time series.
    """
    result1 = hourly_series.head(24)
    result1 = result1.reset_index()
    result2 = hourly_series.tail(24)
    result2 = result2.reset_index()
    return result1, result2


def event_log_formatter(events):
    """Return the events in log format."""
    event_log = []
    log_format = (
        '%(event_time)s [%(rsrc_name)s]: %(rsrc_status)s  %(rsrc_status_reason)s'
        )
    for event in events:
        event_time = getattr(event, 'event_time', '')
        log = log_format % {'event_time': event_time.replace('T', ' '),
            'rsrc_name': getattr(event, 'resource_name', ''), 'rsrc_status':
            getattr(event, 'resource_status', ''), 'rsrc_status_reason':
            getattr(event, 'resource_status_reason', '')}
        event_log.append(log)
    return '\n'.join(event_log)


def optimize_graph(edges, aggr_type, fr='from_int', to='to_int', weight_col
    ='weight'):
    """
    Optimize the graph in terms of keeping only e.g. 'min' or 'max' (fastest / slowest) edges between nodes.
    This process can dramatically decrease the size of the graph.

    Parameters
    ----------

    edges : pd.DataFrame
        Pandas DataFrame containing the edge information.
    aggr_type : str
        Aggregation type. Possible values are: 'min', 'max', 'mean', 'median'

    """
    optimized = edges.groupby([fr, to])[weight_col].agg(aggr_type).reset_index(
        ).merge(edges, on=[fr, to]).rename(columns={(weight_col + '_x'):
        weight_col}).drop_duplicates([fr, to]).drop(weight_col + '_y', axis=1)
    return optimized


@classmethod
def get_by_uuid(cls, context, uuid):
    """Find a volume connector based on its UUID.

        :param cls: the :class:`VolumeConnector`
        :param context: security context
        :param uuid: the UUID of a volume connector
        :returns: a :class:`VolumeConnector` object
        :raises: VolumeConnectorNotFound if no volume connector exists with
                 the specified UUID
        """
    db_connector = cls.dbapi.get_volume_connector_by_uuid(uuid)
    connector = cls._from_db_object(context, cls(), db_connector)
    return connector


def write_histograms(fname, hists):
    """Writes all histograms in list `hists` to file named `fname`

    If the filename is the empty string, then output is to stdout.
    Assumes that all files should have the same bins.
    """
    pass


@classmethod
def search(cls, q=None, sort=None, page=1, size=1000, sandbox=False,
    all_versions=False, max_pages=10):
    """Search public records

        It is possible to filter the results use the optional parameters.  Note that the web interface
        can sometimes be used to find search parameters by looking in the `search-hidden-params`
        parameter of the `invenio-search` tag.

        Example queries
        ===============
        'title:"SXS:BBH:0003"'  # Finds titles with given string; use quotes for robustness
        'communities:sxs'  # Records in the 'sxs' Zenodo community
        'provisional_communities:sxs'  # Records awaiting approval by the community curator
        'owners: 38418'  # Find records by id number of owner

        Optional parameters
        ===================
        q: string
            Search query, using Elasticsearch query string syntax.  See
            https://help.zenodo.org/guides/search/ for details.
        sort: string
            Sort order ('bestmatch' or 'mostrecent').  Prefix with minus to change from ascending to
            descending (e.g., '-mostrecent').
        page: int
            Page number for pagination
        size: int
            Number of results to return per page.  Note that Zenodo (as of this writing) seems to
            place a hard limit of 9999 responses.  Anything more will result in an error.  Use
            multiple pages to get more results.
        sandbox: bool [defaults to False]
            If True use sandbox.zenodo.org instead of the standard site.
        all_versions: bool [defaults to False]
            If True return all records, including older versions of published records.
        max_pages: int [defaults to 10]
            If the query returns a number of records equal to `size`, it is evidently incomplete.
            This function will attempt to retrieve successive pages until the number of records is
            less than `size`.  If the query is still incomplete after this many pages, just return
            what we've got.

        """
    import requests
    from . import url_sandbox, url_standard
    if sandbox:
        base_url = url_sandbox
    else:
        base_url = url_standard
    url = base_url + 'api/records/'
    params = {}
    if q is not None:
        params['q'] = q
    if sort is not None:
        params['sort'] = sort
    params['page'] = page
    params['size'] = size
    if all_versions:
        params['all_versions'] = ''
    r = requests.get(url, params=params, headers={'Accept': 'application/json'}
        )
    if r.status_code != 200:
        print('An unknown error occurred when trying to access {0}.'.format
            (url))
        print('The search parameters were "{0}"'.format(params))
        try:
            print(r.json())
        except:
            pass
        r.raise_for_status()
        raise RuntimeError()
    json = r.json()
    if len(json) == size:
        page += 1
        if page > max_pages:
            print(
                'Search is not yet complete after {0} pages; returning with what we have.'
                .format(max_pages))
            return r.json()
        return json + cls.search(q=q, sort=sort, page=page, size=size,
            sandbox=sandbox, all_versions=all_versions, max_pages=max_pages)
    return json


def cols_to_strip_commas(df, columns):
    """Strip commas from selected dataframe columns.

    Args:
        df: Pandas dataframe.
        columns: List of columns to convert.

    Returns:
        Original dataframe with converted column data.
    """
    for col in columns:
        df[col] = df[col].str.replace(',', '')
    return df


def __call__():
    """Generate a new UUID.
        """


def p_comp_op_lt(p):
    """comp_op : expr LT expr"""
    p[0] = 'lt', p[1], p[3]


@staticmethod
def get_tokens_data(code: str, redirect_uri: str) ->dict:
    """
            Data with code from OAuth2.0 authentication
            that should be sent to get tokens.
        """
    return {'code': code, 'redirect_uri': redirect_uri, 'grant_type':
        'authorization_code'}


def tag(tag):
    """Select a single tag."""
    return {'tag': tag}


def useOrRaise(thing, errmsg=''):
    """Raise 'thing' if it's a subclass of Exception.  Otherwise return it.

    Called by: Cheetah.Servlet.cgiImport()
    """
    if isinstance(thing, type) and issubclass(thing, Exception):
        raise thing(errmsg)
    return thing


def join_version(version_tuple):
    """Return a string representation of version from given VERSION tuple"""
    version = '%s.%s.%s' % version_tuple[:3]
    if version_tuple[3] != 'final':
        version += '-%s' % version_tuple[3]
    return version


def override_remove_button(all: bool=True):
    """Remove an override operation

    :param all: All, Reset to default values all elements of the array
    :type all: bool
    """
    pass


def is_contiguous(array, dtype=None):
    """Check for contiguity and type."""
    if dtype is None:
        return array.flags.contiguous
    else:
        return array.flags.contiguous and array.dtype == dtype


def _save(tables, writer, sheet_name='Sheet1', n_row=1):
    """Save a list of tables as an excel file.

    Parameters
    ----------
    tables : iterable[DataFrame]
    writer : ExcelWritter

    """
    for t in tables:
        label = t.columns.name
        t.to_excel(writer, sheet_name, startrow=n_row, index_label=label)
        n_row += len(t.index) + 2
    return n_row


def impulse(sys, T=None, X0=0.0, input=0, output=None, return_x=False):
    """
    Impulse response of a linear system

    If the system has multiple inputs or outputs (MIMO), one input has
    to be selected for the simulation.  Optionally, one output may be
    selected. If no selection is made for the output, all outputs are
    given. The parameters `input` and `output` do this. All other
    inputs are set to 0, all other outputs are ignored.

    Parameters
    ----------
    sys: StateSpace, TransferFunction
        LTI system to simulate

    T: array-like object, optional
        Time vector (argument is autocomputed if not given)

    X0: array-like or number, optional
        Initial condition (default = 0)

        Numbers are converted to constant arrays with the correct shape.

    input: int
        Index of the input that will be used in this simulation.

    output: int
        Index of the output that will be used in this simulation.

    Returns
    -------
    yout: array
        Response of the system

    T: array
        Time values of the output

    xout: array (if selected)
        Individual response of each x variable

    See Also
    --------
    lsim, step, initial

    Examples
    --------
    >>> yout, T = impulse(sys, T)
    """
    from ..timeresp import impulse_response
    T, yout, xout = impulse_response(sys, T, X0, input, output, transpose=
        True, return_x=True)
    if return_x:
        return yout, T, xout
    return yout, T


@staticmethod
def supported_operations():
    """Return the supportedOperations object."""
    return []


@staticmethod
def do_selection_reduction_to_one_parent(selection):
    """ Find and reduce selection to one parent state.

        :param selection:
        :return: state model which is parent of selection or None if root state
        """
    all_models_selected = selection.get_all()
    parent_m_count_dict = {}
    for model in all_models_selected:
        parent_m_count_dict[model.parent] = parent_m_count_dict[model.parent
            ] + 1 if model.parent in parent_m_count_dict else 1
    parent_m = None
    current_count_parent = 0
    for possible_parent_m, count in parent_m_count_dict.items():
        parent_m = (possible_parent_m if current_count_parent < count else
            parent_m)
    if len(selection.states) == 1 and selection.get_selected_state(
        ).state.is_root_state:
        parent_m = None
        if len(all_models_selected) > 1:
            selection.set(selection.get_selected_state())
    if parent_m is not None:
        for model in all_models_selected:
            if model.parent is not parent_m:
                selection.remove(model)
    return parent_m


def extract_map_fragment(map_file, coords, op_file):
    """
    Takes the map and extracts a segment of the map at coords
    into a separate file, used for the settlement wiki so we
    can see where each town and city lives.

    NOTE coords is (x,y) and is a PERCENTAGE of the image size

    """
    from PIL import Image
    img = Image.open(map_file)
    width, height = img.size
    centre_x_pixels = int(round(width * (coords[0] / 100), 0))
    centre_y_pixels = int(round(height * (coords[1] / 100), 0))
    offset_x = int(round(width * (22 / 100), 0))
    offset_y = int(round(height * (11 / 100), 0))
    print(centre_x_pixels, centre_y_pixels)
    left = centre_x_pixels - offset_x
    top = centre_y_pixels - offset_y
    right = left + offset_x
    bottom = top + offset_y
    if left < 1:
        left = 0
        right = offset_x * 2
    if top < 1:
        top = 0
        bottom = offset_y * 2
    if right > width:
        right = width
        left = offset_x * 2
    if bottom > height:
        bottom = height
        top = offset_y * 2
    box = left, top, right, bottom
    area = img.crop(box)
    area.save(op_file, 'jpeg')


def GraphDef_Opt(meta_graph):
    """Inject the optimization options into GraphDef.

    Parameters
    ----------
    meta_graph : dragon_pb2.GraphDef
        The definition of meta graph.

    Returns
    -------
    None

    References
    ----------
    `config.SetDebugMode(*args, **kwargs)`_ - How the enable debug mode.

    `memonger.share_grads(*args, **kwargs)`_ - How the enable gradients sharing.

    """
    from dragon.config import option
    meta_graph.debug_mode = option['debug_mode']
    meta_graph.share_grads = option['share_grads']


@staticmethod
def beta_r(r, beta):
    """
        anisotropy as a function of radius

        :param r: 3d radius
        :param beta: anisotropy
        :return: beta
        """
    return beta


def HT_SINE(df, price='Close'):
    """
    Hilbert Transform - SineWave
    """


def align(val: int, lowerBitCntToAlign: int):
    """
    Cut off lower bits to aligin a int value.
    """
    val = val >> lowerBitCntToAlign
    return val << lowerBitCntToAlign


def calculate_final_drive_speeds_in(final_drive_speeds_out,
    final_drive_ratio_vector):
    """
    Calculates final drive speed [RPM].

    :param final_drive_speeds_out:
        Rotating speed of the wheel [RPM].
    :type final_drive_speeds_out: numpy.array | float

    :param final_drive_ratio_vector:
        Final drive ratio vector [-].
    :type final_drive_ratio_vector: numpy.array | float

    :return:
        Final drive speed in [RPM].
    :rtype: numpy.array | float
    """
    return final_drive_speeds_out * final_drive_ratio_vector


@staticmethod
def __split_key(key):
    """ Break the requested key into a list of items

        :param key: The config key to be validated
        :return:    List of items to traverse for the requested config value.
        """
    return key.split(u'.')


def dpad_topright_unheading(controller):
    """
    Callback function that is triggered, when the direction top right was released

    :param controller:              the controller that triggered the action
    :type controller:               steuer.Controller
    """
    print('DIRECTION:' + str(controller.number) + ':' + controller.name +
        ':DPAD Top Right unheading')


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


def yesno(value, true_value, false_value):
    """Return ``true_value`` if ``value`` evaluates to true and ``false_value`` otherwise."""
    return true_value if value else false_value


def is_ascii(char: str) ->bool:
    """
    Returns whether or not a single character is an ASCII character.
    :param char: A single character
    :return: If that character is an ASCII character.
    """
    if len(char) == 0:
        raise ValueError('Cannot determine if an empty string is ascii or not.'
            )
    if len(char) > 1:
        raise ValueError('The value {} is not a single character!'.format(char)
            )
    return ord(char) >= 0 and ord(char) <= 127


@classmethod
def get_friendly_name(cls):
    """Returns a human-readable name of the curve that can be
        used in messages."""
    return 'ROC curve'


def get_role_description(role_arn, iam_client):
    """Get a role description for the given role arn

    Throws botocore.exceptions.ClientError if the description for
    a role cannot be found from the given arn
    """
    return iam_client.get_role(RoleName=role_arn.split('/')[-1])


def p_label_line_label_line_co(p):
    """ label_line : label_line_co
    """
    p[0] = p[1]


def rhosat(phi, sw, rhomin, rhow, rhohc):
    """
    Density of partially saturated rock.
    """
    a = rhomin * (1 - phi)
    b = rhow * sw * phi
    c = rhohc * (1 - sw) * phi
    return a + b + c


@classmethod
def vol_type(cls):
    """The type of volume supported by this driver."""
    raise NotImplementedError()


def extents_overlap(a_extent, b_extent):
    """Test if two extents overlap"""
    if (a_extent.xmin > b_extent.xmax or a_extent.xmax < b_extent.xmin or
        a_extent.ymin > b_extent.ymax or a_extent.ymax < b_extent.ymin):
        return False
    else:
        return True


@classmethod
def from_dict(cls, amount_dict):
    """Retrieve data from dict and place it as object properties."""
    return cls(electronic=amount_dict.get('Electronic'), advance_payment=
        amount_dict.get('AdvancePayment'), credit=amount_dict.get('Credit'),
        provision=amount_dict.get('Provision'))


def shape_key_rekey(location: bool=True, feather: bool=True):
    """Recalculate animation data on selected points for frames selected in the dopesheet

    :param location: Location
    :type location: bool
    :param feather: Feather
    :type feather: bool
    """
    pass


def get_node_portmap(task):
    """Extract the switch port information for the node.

    The information is returned in the form of::

        {
            port.uuid: {
                'switch_id': 'abc',
                'port_id': 'Po0/1',
                'other_llc_key': 'val'
            }
        }

    :param task: a task containing the Node object.
    :returns: port information as a dict
    """
    portmap = {}
    for port in task.ports:
        portmap[port.uuid] = port.local_link_connection
    return portmap


def _format_level(level):
    """Convert a level to a string and keep zeros if not a top level."""
    text = str(level)
    if text.endswith('.0') and len(text) > 3:
        text = text[:-2]
    return text


@staticmethod
def model_specific():
    """
        Returns model class (that inherits from `BaseCondition`) if action is meant to be model specific, `True` if it
        requires any model and `False` if the condition is generic (default).
        """
    return False


def convert_to_timezone_naive(time_to_freeze):
    """
    Converts a potentially timezone-aware datetime to be a naive UTC datetime
    """
    if time_to_freeze.tzinfo:
        time_to_freeze -= time_to_freeze.utcoffset()
        time_to_freeze = time_to_freeze.replace(tzinfo=None)
    return time_to_freeze


def character_from_str(src):
    """Returns the first character of src or None, if src is empty."""
    if len(src) > 0:
        return src[0]
    else:
        return None


def get_strands(names, strand_dict):
    """Get list of sequences from list of names."""
    strands = []
    for name in names:
        assert name in strand_dict, 'Strand %s referenced before definition' % name
        strands.append(strand_dict[name])
    return strands


def generate_move_args(start_day, remaining, last_move_dest, where):
    """
    ar: apparent-dest apprent-dir actual-dest road dest-hidden distance orig orig-hidden

    Right now we aren't setting all of these, just the easy ones.
    """
    ar = ['0', '0', '0', '0', '0', '0', '0', '0']
    ar[2] = last_move_dest
    if remaining == '-1':
        raise ValueError(
            'If I am moving, days remaining canot be unknown: ' + remaining)
    ar[5] = str(31 - int(start_day) + int(remaining))
    ar[6] = where
    return ar


@staticmethod
def mimetype():
    """Return most common media type for format."""
    return 'application/xml-dtd'


def case_1(node):
    """ Case when node have two children, one
    of which is operator, other not.
    In that case choice operator node as top node.

    Example:
    T->[a, *->[a]] to *->[a, a]"""
    op_node = node.find_op_child()
    unop_node = node.find_unop_child()
    op_node.add_child(unop_node)
    parent = node.parent
    if parent is not None:
        parent.replace_child(node, op_node)
        return parent
    else:
        op_node.parent = parent
        return op_node


def normalize_scheme(scheme):
    """Normalize the scheme component."""
    return scheme.lower()


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


@classmethod
def add_options(cls, parser):
    """Add options to flake8.

        :param parser: optparse.OptionParser from pep8.
        """
    parser.add_option('--show-pep257', action='store_true', help=
        'show explanation of each PEP 257 error')
    parser.config_options.append('show-pep257')


def __call__(input):
    """Render the template given input.

        input - opaque template-language native data structure.

        Raise a RenderError if the template cannot be rendered.
        """


def listify(string_or_list):
    """Takes a string or a list and converts strings to one item lists"""
    if hasattr(string_or_list, 'startswith'):
        return [string_or_list]
    else:
        return string_or_list


def str2int(s):
    """Convert a byte string to an integer.

    @param s: byte string representing a positive integer to convert
    @return: converted integer
    """
    s = bytearray(s)
    r = 0
    for c in s:
        r = r << 8 | c
    return r


def parse_two_part_term(term, delim=','):
    """Parse a term assuming [ [part1],[part2] ]"""
    valid = False
    part1 = ''
    part2 = ''
    if term.find(delim) != -1:
        valid = True
        field1 = term.split(delim, 1)[0]
        if bool(field1):
            part1 = field1
        field2 = term.rsplit(delim, 1)[-1]
        if bool(field2):
            part2 = field2
    return valid, part1, part2


@staticmethod
def del_key_with_comments(dic, key, logger=None):
    """Delete section with comments."""
    if key not in dic:
        return
    if logger:
        logger.debug('Removing key: %s', key)
    del dic[key]
    dic.ca.items.pop(key, None)


def escapejson(jsonstr):
    """
    Escape quotes in JSON strings

    Parameters
    ----------
    jsonstr : JSON string

    Returns
    -------
    string
       String with quotes and newlines escaped

    """
    jsonstr = jsonstr.replace('\\', '\\\\')
    jsonstr = jsonstr.replace('\\"', '\\\\"')
    jsonstr = jsonstr.replace('\x08', '\\u0008')
    jsonstr = jsonstr.replace('\x0c', '\\u000C')
    jsonstr = jsonstr.replace('\n', '\\u000A')
    jsonstr = jsonstr.replace('\r', '\\u000D')
    jsonstr = jsonstr.replace('\t', '\\u0009')
    return jsonstr


def identity_transform(data):
    """Example data transformation function for a capture handler."""
    return data


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

        :param TfaRemoveBackupPhoneType val:
        :rtype: EventType
        """
    return cls('tfa_remove_backup_phone', val)


def padl(text, n, c):
    """
    left pad of text with character c
    """
    text = str(text)
    return str(c) * (n - len(text)) + text


@classmethod
def mask(cls, dt, **options):
    """
        Return a datetime with the same value as ``dt``, to a
        resolution of years.
        """
    return dt.replace(month=1, day=1, hour=0, minute=0, second=0, microsecond=0
        )