def continue_update_rollback(StackName=None, RoleARN=None, ResourcesToSkip=
    None, ClientRequestToken=None):
    """
    For a specified stack that is in the UPDATE_ROLLBACK_FAILED state, continues rolling it back to the UPDATE_ROLLBACK_COMPLETE state. Depending on the cause of the failure, you can manually fix the error and continue the rollback. By continuing the rollback, you can return your stack to a working state (the UPDATE_ROLLBACK_COMPLETE state), and then try to update the stack again.
    A stack goes into the UPDATE_ROLLBACK_FAILED state when AWS CloudFormation cannot roll back all changes after a failed stack update. For example, you might have a stack that is rolling back to an old database instance that was deleted outside of AWS CloudFormation. Because AWS CloudFormation doesn't know the database was deleted, it assumes that the database instance still exists and attempts to roll back to it, causing the update rollback to fail.
    See also: AWS API Documentation

    :example: response = client.continue_update_rollback(
        StackName='string',
        RoleARN='string',
        ResourcesToSkip=[
            'string',
        ],
        ClientRequestToken='string'
    )

    :type StackName: string
    :param StackName: [REQUIRED]
            The name or the unique ID of the stack that you want to continue rolling back.
            Note
            Don't specify the name of a nested stack (a stack that was created by using the AWS::CloudFormation::Stack resource). Instead, use this operation on the parent stack (the stack that contains the AWS::CloudFormation::Stack resource).

    :type RoleARN: string
    :param RoleARN: The Amazon Resource Name (ARN) of an AWS Identity and Access Management (IAM) role that AWS CloudFormation assumes to roll back the stack. AWS CloudFormation uses the role's credentials to make calls on your behalf. AWS CloudFormation always uses this role for all future operations on the stack. As long as users have permission to operate on the stack, AWS CloudFormation uses this role even if the users don't have permission to pass it. Ensure that the role grants least privilege.
            If you don't specify a value, AWS CloudFormation uses the role that was previously associated with the stack. If no role is available, AWS CloudFormation uses a temporary session that is generated from your user credentials.

    :type ResourcesToSkip: list
    :param ResourcesToSkip: A list of the logical IDs of the resources that AWS CloudFormation skips during the continue update rollback operation. You can specify only resources that are in the UPDATE_FAILED state because a rollback failed. You can't specify resources that are in the UPDATE_FAILED state for other reasons, for example, because an update was canceled. To check why a resource update failed, use the DescribeStackResources action, and view the resource status reason.
            Warning
            Specify this property to skip rolling back resources that AWS CloudFormation can't successfully roll back. We recommend that you troubleshoot resources before skipping them. AWS CloudFormation sets the status of the specified resources to UPDATE_COMPLETE and continues to roll back the stack. After the rollback is complete, the state of the skipped resources will be inconsistent with the state of the resources in the stack template. Before performing another stack update, you must update the stack or resources to be consistent with each other. If you don't, subsequent stack updates might fail, and the stack will become unrecoverable.
            Specify the minimum number of resources required to successfully roll back your stack. For example, a failed resource update might cause dependent resources to fail. In this case, it might not be necessary to skip the dependent resources.
            To specify resources in a nested stack, use the following format: NestedStackName.ResourceLogicalID . If the ResourceLogicalID is a stack resource (Type: AWS::CloudFormation::Stack ), it must be in one of the following states: DELETE_IN_PROGRESS , DELETE_COMPLETE , or DELETE_FAILED .
            (string) --

    :type ClientRequestToken: string
    :param ClientRequestToken: A unique identifier for this ContinueUpdateRollback request. Specify this token if you plan to retry requests so that AWS CloudFormation knows that you're not attempting to continue the rollback to a stack with the same name. You might retry ContinueUpdateRollback requests to ensure that AWS CloudFormation successfully received them.

    :rtype: dict
    :return: {}

    """
    pass


def t_ARRAY(t):
    """([ ]+)array[ ]element[ ]index:[ ](\\d+)\\n"""
    tab = int(len(t.lexer.lexmatch.group(13)) / 2)
    index = int(t.lexer.lexmatch.group(14))
    t.value = [tab, {'index': index, 'value': None}]
    return t


def parse_wildcards(props):
    """Pull out the wildcard attributes from the Component props.

    Parameters
    ----------
    props: dict
        Dictionary with {propName: propMetadata} structure

    Returns
    -------
    list
        List of Dash valid wildcard prefixes
    """
    list_of_valid_wildcard_attr_prefixes = []
    for wildcard_attr in ['data-*', 'aria-*']:
        if wildcard_attr in props:
            list_of_valid_wildcard_attr_prefixes.append(wildcard_attr[:-1])
    return list_of_valid_wildcard_attr_prefixes


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


@staticmethod
def observation_names():
    """ Get the names for each key in an observation dictionary.

        Returns
        -------
        observation_names : List[int]
        """
    return ['board', 'pieces', 'score', 'player']


@staticmethod
def date_diff(time_point_1=None, time_point_2=None):
    """Return (duration, is_negative) between two TimePoint objects.

        duration -- is a Duration instance.
        is_negative -- is "-" if time_point_2 is in the past of time_point_1.
        """
    if time_point_2 < time_point_1:
        return time_point_1 - time_point_2, '-'
    else:
        return time_point_2 - time_point_1, ''


def build_template(data):
    """
    Build and return an addressbook file template
    """
    template = (
        '# abook addressbook file\n\n[format]\nprogram=abook\nversion=0.6.1\n\n'
        )
    for index, entry in enumerate(data):
        template += (
            f"\n[{index}]\nname={entry['name']}\nemail={','.join(entry['email'])}\n"
            )
        if entry['notes']:
            template += f"notes={entry['notes']}\n"
        if entry['custom1']:
            template += f"custom1={entry['custom1']}\n"
    template += '\n'
    return template


def pair_table_to_dot_bracket(pt, strand_break='+'):
    """
    Inverse of the make_pair_table function.
    """
    assert len(strand_break) == 1
    out = []
    for si, strand in enumerate(pt):
        if out:
            out.append(strand_break)
        for di, pair in enumerate(strand):
            if pair is None:
                out.append('.')
            else:
                locus = si, di
                if locus < pair:
                    out.append('(')
                else:
                    out.append(')')
    return out


def load_images(url, format='auto', with_path=True, recursive=True,
    ignore_failure=True, random_order=False):
    """
    Loads images from a directory. JPEG and PNG images are supported.

    Parameters
    ----------
    url : str
        The string of the path where all the images are stored.

    format : {'PNG' | 'JPG' | 'auto'}, optional
        The format of the images in the directory. The default 'auto' parameter
        value tries to infer the image type from the file extension. If a
        format is specified, all images must be of that format.

    with_path : bool, optional
        Indicates whether a path column is added to the SFrame. If 'with_path'
        is set to True,  the returned SFrame contains a 'path' column, which
        holds a path string for each Image object.

    recursive : bool, optional
        Indicates whether 'load_images' should do recursive directory traversal,
        or a flat directory traversal.

    ignore_failure : bool, optional
        If true, prints warning for failed images and keep loading the rest of
        the images.

    random_order : bool, optional
        Load images in random order.

    Returns
    -------
    out : SFrame
        Returns an SFrame with either an 'image' column or both an 'image' and
        a 'path' column. The 'image' column is a column of Image objects. If
        with_path is True, there is also a 'path' column which contains the image
        path for each of each corresponding Image object.

    Examples
    --------

    >>> url ='https://static.turi.com/datasets/images/nested'
    >>> image_sframe = turicreate.image_analysis.load_images(url, "auto", with_path=False,
    ...                                                       recursive=True)
    """
    from ... import extensions as _extensions
    from ...util import _make_internal_url
    url = _make_internal_url(url)
    return _extensions.load_images(url, format, with_path, recursive,
        ignore_failure, random_order)


@classmethod
def _get_mapping(cls, component):
    """Return a dict of attributes of a given component on the class

        """
    mapping = {}
    for klass in cls.__mro__:
        for key, value in klass.__dict__.items():
            if isinstance(value, component):
                if key not in mapping:
                    mapping[key] = value.name
    return mapping


@staticmethod
def file_diff_cmd(r, f):
    """Get diff for one file, f."""
    return ['hg', 'diff', '-r', r.rev, f]


@classmethod
def members(cls):
    """ Get the members dictionary for the type.

        Returns
        -------
        result : dict
            The dictionary of members defined on the class. User code
            should not modify the contents of the dict.

        """
    return cls.__atom_members__


def __init__(context, request, field):
    """
        adapts context/request and field because query params might affect how we render
        """


def is_url(text):
    """ Check if the given text looks like a URL. """
    if text is None:
        return False
    text = text.lower()
    return text.startswith('http://') or text.startswith('https://'
        ) or text.startswith('urn:') or text.startswith('file://')


def apply(hub, subs, low):
    """
    Look up the transparetn requisites as defined in state modules and apply
    them to the respective low chunks
    """
    treq = hub.idem.treq.gather(subs, low)
    refs = {}
    for ind, chunk in enumerate(low):
        path = f"{chunk['state']}.{chunk['fun']}"
        if path not in refs:
            refs[path] = []
        if ind not in refs[path]:
            refs[path].append(ind)
    for chunk in low:
        if not chunk['state'] in treq:
            continue
        if not chunk['fun'] in treq[chunk['state']]:
            continue
        rule = treq[chunk['state']][chunk['fun']]
        for req, r_refs in rule.items():
            for ref in r_refs:
                if ref not in refs:
                    continue
                for rind in refs[path]:
                    req_chunk = low[rind]
                    if req not in chunk:
                        chunk[req] = []
                    chunk[req].append({req_chunk['state']: req_chunk['__id__']}
                        )
    return low


@classmethod
def update_all(cls, image):
    """
        Method updating all real classes inherited from ImageRelatedMixin
        Used when an image is updated: each instance should be updated as ref_image and ref_alt are denormalized from image

        Args:
            image (stack_it.Image instance): All related "ImageRelatedMixin" related to this instance will be updated
        """
    subclasses = cls.__subclasses__()
    for cl in subclasses:
        if cl._meta.abstract:
            cl.update_all(image)
        else:
            cl.objects.filter(image=image).update(ref_image=image.image,
                ref_alt=image.alt)


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

        :param AllowDownloadEnabledDetails val:
        :rtype: EventDetails
        """
    return cls('allow_download_enabled_details', val)


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

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

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


def one_deviance_ic(y, preds):
    """
    Compute the IC for one cross-entropy

    @param y: the outcome
    @param preds: the predictions based on a given subset of features

    @return the IC for cross-entropy
    """
    import sklearn.metrics as skm
    import numpy as np
    cross_entropy = -2 * skm.log_loss(y_true=y, y_pred=preds, normalize=True)
    p = np.mean(y, axis=0)
    denom = -1 * np.sum(np.log(p))
    ic_cross_entropy = -2 * np.sum(y * np.log(preds), axis=1) - cross_entropy
    ic_denom = -1.0 / p * ((y == 1) - p)
    grad = np.array([1.0 / denom, -1 * cross_entropy / denom ** 2])
    return np.dot(grad, np.transpose(np.hstack(ic_cross_entropy, ic_denom)))


def modified(number, percent):
    """return the amount (or any other number) with added margin given by percent parameter
    (result has type float)
    """
    if percent:
        return number * (100 + percent) / 100.0
    else:
        return float(number)


def is_one_dimensional(a):
    """
    Helper function to determine if value is one dimensional.

    Parameters
    ----------
    a : array_like
        Object to test.

    Returns
    -------
    True or false respectively.
    """
    return a.ndim == 1


@classmethod
def get_serialization_instance(cls, value):
    """Returns the native object corresponding to the serialized form passed
        in the ``value`` argument.

        :param value: This argument can be:
            * A list or tuple of native types aligned with cls._type_info.
            * A dict of native types.
            * The native type itself.

            If the value type is not a ``list``, ``tuple`` or ``dict``, the
            value is returned untouched.
        """
    if isinstance(value, list) or isinstance(value, tuple):
        assert len(value) <= len(cls._type_info)
        cls_orig = cls
        if cls.__orig__ is not None:
            cls_orig = cls.__orig__
        inst = cls_orig()
        keys = cls.get_flat_type_info(cls).keys()
        for i in range(len(value)):
            setattr(inst, keys[i], value[i])
    elif isinstance(value, dict):
        cls_orig = cls
        if cls.__orig__ is not None:
            cls_orig = cls.__orig__
        inst = cls_orig()
        for k in cls.get_flat_type_info(cls):
            setattr(inst, k, value.get(k, None))
    else:
        inst = value
    return inst


@staticmethod
def from_io_control(fobj):
    """
        Call TIOCGWINSZ (Terminal I/O Control to Get the WINdow SiZe)
        where ``fobj`` is a file object (e.g. ``sys.stdout``),
        returning the terminal width assigned to that file.

        See the ``ioctl``, ``ioctl_list`` and tty_ioctl`` man pages
        for more information.
        """
    import fcntl, termios, array
    winsize = array.array('H', [0] * 4)
    if not fcntl.ioctl(fobj.fileno(), termios.TIOCGWINSZ, winsize, True):
        return winsize[1]


def psi_MgOH_Cl_HCO3_HMW84(T, P):
    """c-a-a': magnesium-hydroxide chloride bicarbonate [HMW84]."""
    psi = 0
    valid = T == 298.15
    return psi, valid


@classmethod
def get_dict_value(cls, dict_IN, name_IN, default_IN=None):
    """
        Accepts dictionary, name, and optional default value (if no default
           provided, default is None).  If dictionary or name missing, returns
           default.  If name not present in dictionary, returns default.  If name
           in dictionary, returns whatever is mapped to name.

        Parameters:
        - dict_IN - dictionary we are looking in.
        - name_IN - name we are looking for in dictionary.
        - default_IN (defaults to None) - default value to return if problem or not found in dict.

        Returns:
        - value_OUT - value mapped to name_IN in dict_IN, else the default value if problems or if not found in dict.
        """
    value_OUT = None
    if cls.is_dict(dict_IN) == True:
        if name_IN:
            if name_IN in dict_IN:
                value_OUT = dict_IN.get(name_IN, default_IN)
            else:
                value_OUT = default_IN
        else:
            value_OUT = default_IN
    else:
        value_OUT = default_IN
    return value_OUT


def p_shift_expr_1(p):
    """shift_expr : arith_expr"""
    p[0] = p[1]


def get_null_keywords_es(es, size):
    """
    Get from ElasticSearch the news entries which don't contain keywords.

    :param es: ElasticSearch connection
    :param size: limit of news which are retrieved
    :return: list of news without keywords
    """
    result = es.search(index='sitemaps', q='-news\\:keywords:*',
        _source_includes='news:keywords', size=size)
    return result['hits']['hits']


def change_fleet_direction(ai_settings, aliens):
    """Drop the entire fleet and change the fleet's direction."""
    for alien in aliens.sprites():
        alien.rect.y += ai_settings.fleet_drop_speed
    ai_settings.fleet_direction *= -1


def __find_name_column(df, scientific_names):
    """Return a tuple of (name_column, overla_size)."""
    max_overlap, name_col_name = -1, None
    for col_name in df.columns:
        unique_col_vals = set(df[col_name])
        overlap_size = len(unique_col_vals & scientific_names)
        if overlap_size > max_overlap:
            max_overlap = overlap_size
            name_col_name = col_name
    return name_col_name, max_overlap


def chi_sq_2(frame):
    """Computes the chi-square statistic of the found distributions

    Args:
        frame: DataFrame with Found, Expected and their difference columns.

    Returns:
        The computed Chi square statistic
    """
    exp_counts = frame.Counts.sum() * frame.Expected
    dif_counts = frame.Counts - exp_counts
    return (dif_counts ** 2 / exp_counts).sum()


def hextoi(subject):
    """Given a string representing an integer in hexadecimal notation, return
    the integer in base 10 notation.
    """
    try:
        return int(subject, 16)
    except ValueError:
        return None


@classmethod
def _get_checks(klass):
    """ Return sequence of check functions for this class """
    return ()


@classmethod
def get_p(cls):
    """
        Get p value of metric.
        """
    pass


def ma(series, n):
    """
    简单移动平均线: 求series序列n周期的简单移动平均

        计算公式:
        ma(x, 5) = (x(1) + x(2) + x(3) + x(4) + x(5)) / 5

        注意:
        1. 简单移动平均线将设定周期内的值取平均值, 其中各元素的权重都相等
        2. n为0的情况下, 或当n为有效值但当前的series序列元素个数不足n个, 函数返回 NaN 序列

    Args:
        series (pandas.Series): 数据序列

        n (int): 周期

    Returns:
        pandas.Series: 简单移动平均值序列

    Example::

        from tqsdk import TqApi, TqSim, tafunc

        api = TqApi(TqSim())
        klines = api.get_kline_serial("CFFEX.IF1908", 24 * 60 * 60)
        ma = tafunc.ma(klines.close, 5)
        print(list(ma))
    """
    ma_data = series.rolling(n).mean()
    return ma_data


def beautify_lr_sensitivity(fig, ax):
    """Beautify a learning rate sensitivity plot.

    This function adds axis labels and removes spines to create a nicer learning
    rate sensitivity plot.

    Args:
        fig (matplotlib.figure): Handle to the matplotlib figure of the learning
            rate sensitivity plot.
        ax (list): List of lists of matplotlib axis of the learning rate
            sensitivity plots.

    Returns:
        matplotlib.figure: Handle to the beautified matplotlib figure of the
        learning rate sensitivity plot.
        list: List of lists of the beautified matplotlib axis of the learning
        rate sensitivity plots.

    """
    fig.suptitle('Learning rate sensitivity', fontsize=20)
    for i in range(ax.shape[0]):
        for j in range(ax.shape[1]):
            ax[i][j].get_yaxis().set_visible(False)
            ax[i][j].spines['top'].set_visible(False)
            ax[i][j].spines['right'].set_visible(False)
            ax[i][j].spines['left'].set_visible(False)
            if i == 0:
                ax[i][j].get_xaxis().set_visible(False)
            if i == 1:
                ax[i][j].set_xlabel('Learning Rate')
    return fig, ax


def windows_folder_path(folder_path):
    """convert '/' to '\\' in folder_path and assert ending in '\\'"""
    folder_path = folder_path.replace('/', '\\')
    if folder_path.endswith('\\'):
        pass
    else:
        folder_path = folder_path + '\\'
    return folder_path


@staticmethod
def file_filter(current_file, files_to_exclude):
    """
        This method weeds out unwanted files
        :param current_file:
        :param files_to_exclude:
        :return:
        """
    files_to_exclude.add('MANIFEST.json')
    if current_file in files_to_exclude:
        return False
    elif current_file.endswith(('.pyc', '.DS_Store', '.mar')):
        return False
    return True


def relu(data=None, out=None, name=None, **kwargs):
    """Computes rectified linear activation.

    .. math::
       max(features, 0)

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

       - relu(default) = default
       - relu(row_sparse) = row_sparse
       - relu(csr) = csr

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

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

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

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


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

        Internally set flags such that it is marked as not present on the
        server.

        :param dict kwargs: Each of the named arguments will be set as
                            attributes on the resulting Resource object.
        """
    return cls(kwargs, loaded=False)


def error(r):
    """
    Manually calculate the error according to Wilks definition; compare to bse.
    Proves that the bse parameter is equal to Equation 7.18b in Wilks.
    """
    se2 = (r.resid.values ** 2).sum() / (r.nobs - 2)
    xfact2 = 12 / (r.nobs ** 3 - r.nobs)
    sigma = se2 ** 0.5 * xfact2 ** 0.5
    print('Provided: %.10f, manually calculated: %.10f' % (r.bse.x1, sigma))
    return


def distcalib(param, xref, mzref, axis):
    """
    computes the residual to minimize when calibrating
    basically a wrapper around axis.ppm_error
    """
    axis.calibA = param[0]
    axis.calibB = param[1]
    try:
        axis.calibC = param[2]
    except IndexError:
        pass
    return axis.ppm_error(xref, mzref)


def check_input_and_output_types(operator, good_input_types=None,
    good_output_types=None):
    """
    Check if the type(s) of input(s)/output(s) is(are) correct

    :param operator: A Operator object
    :param good_input_types: A list of allowed input types (e.g., [FloatTensorType, Int64TensorType]) or None. None
    means that we skip the check of the input types.
    :param good_output_types: A list of allowed output types. See good_input_types for its format.
    """
    if good_input_types is not None:
        for variable in operator.inputs:
            if type(variable.type) not in good_input_types:
                raise RuntimeError(
                    'Operator %s (type: %s) got an input %s with a wrong type %s. Only %s are allowed'
                     % (operator.full_name, operator.type, variable.
                    full_name, type(variable.type), good_input_types))
    if good_output_types is not None:
        for variable in operator.outputs:
            if type(variable.type) not in good_output_types:
                raise RuntimeError(
                    'Operator %s (type: %s) got an output %s with a wrong type %s. Only %s are allowed'
                     % (operator.full_name, operator.type, variable.
                    full_name, type(variable.type), good_output_types))


def world_add():
    """Add Rigid Body simulation world to the current scene

    """
    pass


def GetNTARealType():
    """Gets the name of the NuPIC floating point base type,
  which is used for most internal calculations.
  This base type name can be used with GetBasicTypeFromName(),
  GetBasicTypeSize(), and GetNumpyDataType().
  """
    return 'NTA_Real'


def writelines(fn, lst):
    """
    Writes all lines in a given list to a text file
    :param fn: filename
    :param lst: list of strings
    """
    with open(fn, 'w') as f:
        for s in lst:
            f.write(s + '\n')


def sec2unit(value, force=None):
    """Convert a value in seconds in the most appropriate unit
        or in the required unit
        force:   unit required"""
    unit = 'sec'
    if value is None:
        return value, ''
    if force == unit:
        return value, unit
    if value >= 60 and value % 60.0 == 0:
        value /= 60
        unit = 'min'
        if force == unit:
            return value, unit
    if value >= 60 and value % 60.0 == 0:
        value /= 60
        unit = 'hour'
        if force == unit:
            return value, unit
    if value >= 24 and value % 24.0 == 0:
        value /= 24
        unit = 'day'
    return value, unit


def enable_high_precision(on=True):
    """
    启用高精度键控, 缺点是会占满一个核心的 CPU 资源.

    @参数 on(bool): 是否启用
    """
    global high_precision
    high_precision = on


def reconfigure_vm(session, vm_ref, config_spec):
    """Reconfigure a VM according to the config spec."""
    reconfig_task = session._call_method(session.vim, 'ReconfigVM_Task',
        vm_ref, spec=config_spec)
    session._wait_for_task(reconfig_task)


@classmethod
def from_parent(cls, parent, **kw):
    """
        The public  constructor
        """
    return super().from_parent(parent=parent, **kw)


def _char_in_braces(full_s, char_position):
    """

    Checks if a given position in a string lies between braces.
    Note: This is a rough solution, but more than sufficient. A robust solution would require a state machine.

    :param full_s: a string.
    :type full_s: ``str``
    :param char_position: a position in the string.
    :type char_position: ``int``
    :return: ``True`` if yes, else ``False``
    :rtype: bool
    """
    if not isinstance(full_s, str):
        raise ValueError('`full_s` must be a string.')
    if not isinstance(char_position, int):
        raise ValueError('`char_position` must be an int.')
    for pair in ('()', '[]', '{}'):
        if pair[0] in full_s[:char_position] and pair[1] in full_s[
            char_position:]:
            return True
    else:
        return False


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

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

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


def wrap_list(list_, idx):
    """Return value at index, wrapping if necessary.

    Parameters
    ----------
    list_ : :class:`list`
        List to wrap around.
    idx : :class:`int`
        Index of item to return in list.

    Returns
    -------
    :class:`list` element
        Item at given index, index will be wrapped if necessary.
    """
    return list_[idx % len(list_)]


def _is_emoji(content):
    """
    功能： 判断是否原生 emoji 表情，搜狗输入法表情 ❤ ✨ 等会判断为false。

    :param content: 需要判断的表情符号。
    :return: True/False
    """
    if not content:
        return False
    if u'😀' <= content and content <= u'🙏':
        return True
    elif u'🌀' <= content and content <= u'🗿':
        return True
    elif u'🚀' <= content and content <= u'\U0001f6ff':
        return True
    elif u'\U0001f1e0' <= content and content <= u'🇿':
        return True
    else:
        return False


def unquote(value):
    """Removes left most and right most quote for str parsing."""
    return value.lstrip('"').rstrip('"')


def release_dict(d, d_list, holdbacks):
    """Ensures that only new variables are returned"""
    response = dict()
    for i in d:
        if not i in d_list and not i in holdbacks:
            response[i] = d[i]
    return response


def _load_configuration(conf, env_var):
    """Load default configuration settings into the given :class:`Config`
    instance and optionally try to load additional settings from the file
    pointed to by the given environmental variable.

    The environmental variable will be quietly ignored if it is not set or
    it does not point to a valid configuration file.
    """
    conf.from_object('avalon.settings')
    if env_var is None:
        return False
    return conf.from_envvar(env_var, silent=True)


@classmethod
def block_size(cls, header_chunk):
    """Return the total block size in chunks, given the header chunks"""
    if cls.header_type(header_chunk) == 'file':
        return cls.header_size(header_chunk)
    elif cls.header_type(header_chunk) == 'data':
        return cls.data_block_size(header_chunk)
    raise ValueError('Cannot determine size of unknown block type')


def get_uri_filter(app):
    """
    Return a filter function that takes a URI and returns whether it should
    be filter out from the swagger documentation or not.

    Arguments:
        app: The application to take `config.API_URI_FILTER` from. Possible
             values for this config option are: `slash` (to keep URIs that
             end with a `/`), `all` (to keep all URIs). All other values
             default to keep all URIs that don't end with a `/`.

    Returns:
        `True` if the URI should be *filtered out* from the swagger
        documentation, and `False` if it should be kept in the documentation.
    """
    choice = getattr(app.config, 'API_URI_FILTER', None)
    if choice == 'slash':
        return lambda uri: not uri.endswith('/')
    if choice == 'all':
        return lambda uri: False
    return lambda uri: len(uri) > 1 and uri.endswith('/')


def __help_whoami():
    """Function gives description and usage about 'whoami' command
    """
    print('Description: This prints user name.')
    print('Usage: whoami')


def getId():
    """Return content identifier in Zope.
        (Zope API)
        """


def get_authorization_header(token):
    """Auth header used in all API calls."""
    return {'Authorization': f"Bearer {token.info['access_token']}"}


def taxon_rank(name, database=None):
    """
    Make a taxon rank

    :param name: [Array] A taxonomic name
    :param database: [String] A database name

    :return: A dict

    Usage::

        from pytaxa import constructors as cs
        cs.taxon_rank("species")
        cs.taxon_rank("genus", "ncbi")
    """
    return {'name': name, 'database': database}


def restore_address_to_classic(DryRun=None, PublicIp=None):
    """
    Restores an Elastic IP address that was previously moved to the EC2-VPC platform back to the EC2-Classic platform. You cannot move an Elastic IP address that was originally allocated for use in EC2-VPC. The Elastic IP address must not be associated with an instance or network interface.
    See also: AWS API Documentation

    Examples
    This example restores the specified Elastic IP address to the EC2-Classic platform.
    Expected Output:

    :example: response = client.restore_address_to_classic(
        DryRun=True|False,
        PublicIp='string'
    )

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

    :type PublicIp: string
    :param PublicIp: [REQUIRED]
            The Elastic IP address.

    :rtype: dict
    :return: {
        'Status': 'MoveInProgress'|'InVpc'|'InClassic',
        'PublicIp': 'string'
    }

    """
    pass


def get_int_attr(node, attribute):
    """Cast an element attribute to an int or return None if not present"""
    attr = node.get(attribute)
    return None if attr is None else int(attr)


@classmethod
def handle_cursor(cls, cursor, query, session):
    """Handle a live cursor between the execute and fetchall calls

        The flow works without this method doing anything, but it allows
        for handling the cursor and updating progress information in the
        query object"""
    pass


@staticmethod
def __symmetric_difference(first_neighbors_dict, second_neighbors_dict):
    """
        Calculates the difference of weights of first and second node dicts,
        doing also a symmetric difference between the sets of nodes.

        :param first_neighbors_dict: dict, keys: node_pub_keys,
                                           values: node weights
        :param second_neighbors_dict: dict, keys: node_pub_keys,
                                            values: node weights
        :return: dict, keys: node_pub_keys, values: node weights
        """
    first_nodes = set(first_neighbors_dict.keys())
    second_nodes = set(second_neighbors_dict.keys())
    nodes_intersection = first_nodes.intersection(second_nodes)
    unique_first_nodes = first_nodes - nodes_intersection
    unique_second_nodes = second_nodes - nodes_intersection
    diff_neighbor_dict = {}
    for n in unique_first_nodes:
        diff_neighbor_dict[n] = first_neighbors_dict[n]
    for n in unique_second_nodes:
        diff_neighbor_dict[n] = second_neighbors_dict[n]
    for n in nodes_intersection:
        delta = first_neighbors_dict[n] - second_neighbors_dict[n]
        if delta != 0.0:
            diff_neighbor_dict[n] = delta
    return diff_neighbor_dict


@staticmethod
def _add_additional_byte(record):
    """
            Adds fake byte after the mode one (byte is 00)
        """
    return record[:8] + '00' + record[8:]


def factoryURL():
    """ Return URL of factory form """


@classmethod
def fromdjango(cls, obj):
    """Create a new :class:`ResourceKind` object
        from a Django model class or instance.
        """
    meta = obj._meta
    return cls(f'{meta.app_label}.{meta.object_name}')


@classmethod
def zero(cls):
    """
        Return the polynomial ring's neutral element of addition: the zero
        polynomial.
        """
    R = cls.polynomial_ring()
    return cls(R.zero(), R.zero())


def get_instances_output(instances):
    """
    @type instances: list
    """
    ret = ''
    for instance in instances:
        ret += '{0}\n'.format(instance.get('InstanceId'))
    if ret:
        return ret.rstrip()


def _prepareTime(time):
    """Get time in the proper shape
    ex : 174512 for 17h 45m 12s
    ex : 094023 for 09h 40m 23s"""
    time = str(time)
    time = '000000' + time
    time = time[len(time) - 6:]
    return time


@staticmethod
def create_reply(message, ephemeral=False) ->dict:
    """
        Create a reply suitable to send directly back to the invoking HTTP request

        Args:
          message: Text to send
          ephemeral: Whether the response should be limited to a single user, or to
                broadcast the reply (_and_ the user's original invocation) to the
                channel publicly
        """
    if ephemeral:
        return {'text': message, 'response_type': 'ephemeral'}
    else:
        return {'text': message, 'response_type': 'in_channel'}


def _init_worker(model, variable_name, coefficient):
    """
    Initialize a global model object for multiprocessing.

    Parameters
    ----------
    model : cobra.Model
        The metabolic model under investigation.
    variable_name: str
        The name of the variable representing the metabolite exchange.
    coefficient: int
        The value of the metabolite's stoichiometric coefficient: -1 to test
        if the model can produce the metabolite and 1 to test if it can be
        consumed.

    """
    global _model
    global _sink
    global _coefficient
    _model = model
    _sink = model.variables[variable_name]
    _model.objective = _sink
    _coefficient = coefficient


def parse_whitelist_file(whitelist_path: str) ->list:
    """
    Receives a whitelist_path containing 1 IP/CIDR per line and returns a list
    """
    with open(whitelist_path, 'r') as whitelist_file:
        whitelist = whitelist_file.read().splitlines()
    return whitelist


def core_text_draw_func_basic(ticks, texts, level, f, g, dx_units, dy_units,
    angles, tick_lenght, text_distance, text_attrs, c, tick_info):
    """
    Core basic method to draw texts
    ticks: list of tick values to be drawn (not here)
    texts: list of text values to be drawn
    level: drawn level
    f,g: x,y functions
    dx_units, dy_units: unity vector components
    angles: angles of ticks
    tick_lenght: tick lenght
    text_distance: distance where text is drawn
    text_attr: attributes (alignment, etc.) provided to the function
    c: canvas to draw
    tick_info: general hook for axis dict
    """
    ti = tick_info
    n_texts = len(texts)
    if len(dx_units) < n_texts:
        print('too few dx_units !')
    if len(dy_units) < n_texts:
        print('too few dy_units !')
    if len(angles) < n_texts:
        print('too few angles !')
    for i, text_value in enumerate(texts):
        x = f(text_value) + text_distance * dy_units[i]
        y = g(text_value) - text_distance * dx_units[i]
        text_color = ti['text_color']
        if not ti['text_colors'] is None:
            text_color = ti['level_text_color'][level]
        text_size = ti['text_sizes'][level]
        if ti['text_format_func'] is None:
            text = ti['text_format'] % text_value
        else:
            text = ti['text_format_func'](text_value)
        c.text(x, y, text, text_attrs[i] + [text_color, text_size])


def remap(value, source_range, target_range):
    """Remap a value from the source range to the target range.

    Examples ::

         >>> remap(50, (0, 100), (0, 10))
         5.0

         >>> remap(5, (0, 10), (0, 100))
         50.0

         >>> remap(5, (0, 10), (10, 20))
         15.0

         >>> remap(15, (10, 20), (0, 10))
         5.0

    :param value: The value to be remapped.

    :param source_range: The source range for :code:`value`
    :type source_range: tuple

    :param target_range: The target range for :code:`value`
    :type target_range: tuple

    """
    s0, s1 = source_range
    t0, t1 = target_range
    S = s1 - s0
    T = t1 - t0
    return t0 + (value - s0) / S * T


def migrate(engine):
    """Return the number of rows migrated."""
    return 0


def theta_AsO4_Cl_M83(T, P):
    """a-a': arsenate chloride [M83]."""
    theta = 0.06
    valid = T == 298.15
    return theta, valid


def construct_identifier(*args):
    """ Create a post identifier from comment/post object or arguments.

    Examples:

        ::
            construct_identifier('username', 'permlink')
            construct_identifier({'author': 'username',
                'permlink': 'permlink'})
    """
    if len(args) == 1:
        op = args[0]
        author, permlink = op['author'], op['permlink']
    elif len(args) == 2:
        author, permlink = args
    else:
        raise ValueError('construct_identifier() received unparsable arguments'
            )
    author = author.replace('@', '')
    fields = dict(author=author, permlink=permlink)
    return '@{author}/{permlink}'.format(**fields)


def dummy(name, kwargs):
    """
    A convenience method to get a {type} object just by providing a string.

    Parameters
    ----------

    name : {{ {options} }}
        Name of the {type}.

    kwargs : dict
        Dictionary that should be used to call the method mapped to the {type} factory function.

    Returns
    -------
    class : {clazz}
        An {type} object based on the string. `None` if the {type} was not found.

    """
    pass


def on_syntax_error_request(server, request, connection_handler, game):
    """ Manage ERR request

        :param server: server which receives the request
        :param request: request to manage
        :param connection_handler: connection handler from which the request was sent
        :param game: the game
        :return: the list of responses
    """
    del server, request, connection_handler, game


def chip_converter(chip):
    """Converts a chip name to usable string."""
    chip_map = {'3xc': 'TC', 'wildcard': 'WC', 'bboost': 'BB', 'freehit': 'FH'}
    return chip_map[chip]


def send_arduino(msg, serial_connection):
    """
    Send the *msg* over the *serial_connection*

    Adds a hexadecimal number of 6 bytes to the start of the message before
    sending it. "hello there" -> "0x000bhello there"

    Parameters
    ----------
    msg : str or bytes
        the message you want to send
    serial_connection : object
        the :code:`serial.Serial` object you want to use for sending
    """
    if not isinstance(msg, bytes):
        msg = str(msg).encode()
    length = '{0:#0{1}x}'.format(len(msg), 6).encode()
    data = length + msg
    serial_connection.write(data)


@classmethod
def from_metadata_list(cls, metadata_list):
    """Get metadata objects from a list of metadata."""
    return map(lambda info: cls(**info), metadata_list)


def approve_request(session, request_id, return_type=None, **kwargs):
    """
    Approve VPSAOS account requests.

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

    :type request_id: str
    :param request_id: Request ID. Required.

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

    :rtype: dict, str
    :returns: A dictionary or JSON data set as a string depending on
        return_type parameter.
    """
    path = '/api/requests/{0}/approve.json'.format(request_id)
    return session.post_api(path=path, return_type=return_type, **kwargs)


def sequence(items=None, **keywords):
    """
    Makes sequence or sequence expression.

    ..  container:: example

        ..  container:: example

            Makes sequence:

            >>> abjad.sequence([1, 2, [3, [4]], 5])
            Sequence([1, 2, [3, [4]], 5])

        ..  container:: example expression

            Makes sequence expression:

            >>> expression = abjad.sequence()
            >>> expression([1, 2, [3, [4]], 5])
            Sequence([1, 2, [3, [4]], 5])

    ..  container:: example

        Flattens, reverses and slices sequence:

        ..  container:: example

            >>> sequence_ = abjad.sequence([1, 2, [3, [4]], 5])
            >>> sequence_
            Sequence([1, 2, [3, [4]], 5])

            >>> sequence_ = sequence_.flatten(depth=-1)
            >>> sequence_
            Sequence([1, 2, 3, 4, 5])

            >>> sequence_ = sequence_.reverse()
            >>> sequence_
            Sequence([5, 4, 3, 2, 1])

            >>> sequence_ = sequence_[-3:]
            >>> sequence_
            Sequence([3, 2, 1])

        ..  container:: example expression

            >>> expression = abjad.sequence()
            >>> expression = expression.flatten(depth=-1)
            >>> expression = expression.reverse()
            >>> expression = expression[-3:]
            >>> expression([1, 2, [3, [4]], 5])
            Sequence([3, 2, 1])

    Returns sequence when ``items`` is not none.

    Returns sequence expression when ``items`` is none.
    """
    import abjad
    if items is not None:
        return abjad.Sequence(items=items, **keywords)
    else:
        expression = abjad.Expression()
        expression = expression.sequence(**keywords)
        return expression


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

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

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


def deregister_managed_instance(InstanceId=None):
    """
    Removes the server or virtual machine from the list of registered servers. You can reregister the instance again at any time. If you don't plan to use Run Command on the server, we suggest uninstalling the SSM Agent first.
    See also: AWS API Documentation

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

    :type InstanceId: string
    :param InstanceId: [REQUIRED]
            The ID assigned to the managed instance when you registered it using the activation process.

    :rtype: dict
    :return: {}

    """
    pass


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

    The ".dev0" means dirty.

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


def generate_presigned_url(ClientMethod=None, Params=None, ExpiresIn=None,
    HttpMethod=None):
    """
    Generate a presigned url given a client, its method, and arguments

    :type ClientMethod: string
    :param ClientMethod: The client method to presign for

    :type Params: dict
    :param Params: The parameters normally passed to
            ClientMethod.

    :type ExpiresIn: int
    :param ExpiresIn: The number of seconds the presigned url is valid
            for. By default it expires in an hour (3600 seconds)

    :type HttpMethod: string
    :param HttpMethod: The http method to use on the generated url. By
            default, the http method is whatever is used in the method's model.

    """
    pass


def SizeBenefitAccHosp(t):
    """Accidental hospitalization benefit per policy"""
    return 0


def nodebookmarks(node):
    """Return the list of bookmarks pointing to the specified node."""


@staticmethod
def tmpl_num(number, count=2):
    """Pad decimal number with leading zeros

        * synopsis: ``%num{number,count}``
        * description: Pad decimal number with leading zeros.
        * example: ``%num{$track,3}``
        """
    return str(number).zfill(int(count))


def label(field):
    """Return a label for a data field suitable for use on a graph axis.

    This returns the attribute 'long_name' if it exists, or the field name,
    followed by the units attribute if it exists.

    Parameters
    ----------
    field : NXfield
        NeXus field used to construct the label.

    Returns
    -------
    str
        Axis label.
    """
    if 'long_name' in field.attrs:
        return field.long_name
    elif 'units' in field.attrs:
        return '%s (%s)' % (field.nxname, field.units)
    else:
        return field.nxname


def modification_date():
    """
            Returns a DateTime indicating the time  a thread was last updated.
        """


@classmethod
def find(cls, db, token):
    """Find a token object by value.

        Returns None if not found.

        `kind='user'` only returns API tokens for users
        `kind='service'` only returns API tokens for services
        """
    prefix_match = cls.find_prefix(db, token)
    for orm_token in prefix_match:
        if orm_token.match(token):
            return orm_token


def init(deb1, deb2=False):
    """Initialize DEBUG and DEBUGALL.

    Allows other modules to set DEBUG and DEBUGALL, so their
    call to dprint or dprintx generate output.

    Args:
        deb1 (bool): value of DEBUG to set
        deb2 (bool): optional - value of DEBUGALL to set,
                     defaults to False.

    """
    global DEBUG
    global DEBUGALL
    DEBUG = deb1
    DEBUGALL = deb2


def timestamp_from_datetime(datetime):
    """
        Convert from datetime format to timestamp format
        Input: Time in datetime format
        Output: Time in timestamp format
    """
    return datetime.strftime('%Y-%m-%dT%H:%M:%S.%fZ')


def unmap(data, count, inds, fill=0):
    """ Unmap a subset of item (data) back to the original set of items (of
    size count) """
    if data.dim() == 1:
        ret = data.new_full((count,), fill)
        ret[inds] = data
    else:
        new_size = (count,) + data.size()[1:]
        ret = data.new_full(new_size, fill)
        ret[(inds), :] = data
    return ret


def _default_converter(cls, value):
    """A default converter method that tries to deserialize objects."""
    if isinstance(value, dict):
        return cls.from_jsonld(value)
    return value


def __hyp2f1(c, m, x, tol):
    """ Computes 1/f(P) = hyp2f1(1, -m, N-m, -x).

    c   -- coefficients computed by fe.__hyp2f1_coefficients.
    m   -- a positive integer.
    x   -- a real number.
    tol -- error tolerance.
    """
    h1 = 1.0
    mlt = x
    k = 1
    while True:
        u = c[k] * mlt
        h1 += u
        if k == m or abs(u / h1) <= tol:
            break
        k += 1
        mlt *= x
    return h1


@staticmethod
def __check_inner_object(obj: dict, child: str) ->dict:
    """
        Check inner object for named child dict key
        We often get a dict object which contains a single key. The value of this key is itself a dict
        and we need to know if the child key name exists on either the outer dict or the inner dict
        return the inner dict if the child key name is found there, or punt and return the outer dict
        otherwise

        :param obj: dict to check for child key name
        :param child: name of a key we want to find
        :return: inner dict if it contains the child key, outer dict otherwise
        """
    if child in obj:
        return obj
    if len(obj.keys()) == 1:
        inner_obj = obj[list(obj)[0]]
        if child in inner_obj:
            return inner_obj
    return obj


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


def pytest_match_skip_reason(request, message):
    """The reason the test was caught by match_skip."""
    print(message)


def device_type(ctx):
    """Return a str representing device type"""
    pass


def lin_interp(oldpos, newpos, oldtow, newtow, triggertow):
    """
    Linearly interpolates distance.
    Interpolation accurate to the mm.

    Parameters
    ----------
    o : integer
      distance previous to trigger
    n : integer
      distance prior to trigger
    oldtow : integer
      TOW of data packet previous to trigger
    newtow : integer
      TOW of data packet after trigger
    triggertow : integer
      TOW of trigger
    """
    if not oldtow < triggertow < newtow:
        print('TOW values ERROR at {0}'.format(triggertow))
    if newtow - oldtow > 3000:
        print('Interpolation end-points for Trigger at TOW {0} too far away'
            .format(triggertow))
    d = float(newpos - oldpos)
    t = newtow - oldtow
    v = d / t
    return oldpos + v * (triggertow - oldtow)


@classmethod
def _from_dict(cls, _dict):
    """Initialize a DocumentCounts object from a json dictionary."""
    args = {}
    if 'available' in _dict:
        args['available'] = _dict.get('available')
    if 'processing' in _dict:
        args['processing'] = _dict.get('processing')
    if 'failed' in _dict:
        args['failed'] = _dict.get('failed')
    if 'pending' in _dict:
        args['pending'] = _dict.get('pending')
    return cls(**args)


def _find_next_link(root, current_joint, next_link_name):
    """
    Find the next link in the URDF tree

    Parameters
    ----------
    root
    current_joint: xml.etree.ElementTree
        The current URDF joint
    next_link_name: str
        Optional : The name of the next link. If not provided, find it automatically as the first child of the joint.
    """
    has_next = False
    next_link = None
    if next_link_name is None:
        next_link_name = current_joint.find('child').attrib['link']
    for urdf_link in root.findall('link'):
        if urdf_link.attrib['name'] == next_link_name:
            next_link = urdf_link
            has_next = True
    return has_next, next_link


def initialize_notebook():
    """Initialize the IPython notebook display elements"""
    try:
        from IPython.core.display import display, HTML
    except ImportError:
        print('IPython Notebook could not be loaded.')
    load_lib = """
                function vct_load_lib(url, callback){
                      if(typeof d3 !== 'undefined' &&
                         url === 'http://d3js.org/d3.v3.min.js'){
                        callback()
                      }
                      var s = document.createElement('script');
                      s.src = url;
                      s.async = true;
                      s.onreadystatechange = s.onload = callback;
                      s.onerror = function(){
                        console.warn("failed to load library " + url);
                        };
                      document.getElementsByTagName("head")[0].appendChild(s);
                };
                var vincent_event = new CustomEvent(
                  "vincent_libs_loaded",
                  {bubbles: true, cancelable: true}
                );
                """
    lib_urls = ["'http://d3js.org/d3.v3.min.js'",
        "'http://d3js.org/d3.geo.projection.v0.min.js'",
        "'http://wrobstory.github.io/d3-cloud/d3.layout.cloud.js'",
        "'http://wrobstory.github.io/vega/vega.v1.3.3.js'"]
    get_lib = """vct_load_lib(%s, function(){
                  %s
                  });"""
    load_js = get_lib
    ipy_trigger = 'window.dispatchEvent(vincent_event);'
    for elem in lib_urls[:-1]:
        load_js = load_js % (elem, get_lib)
    load_js = load_js % (lib_urls[-1], ipy_trigger)
    html = (
        """
           <script>
               %s
               function load_all_libs(){
                  console.log('Loading Vincent libs...')
                  %s
               };
               if(typeof define === "function" && define.amd){
                    if (window['d3'] === undefined ||
                        window['topojson'] === undefined){
                        require.config(
                            {paths: {
                              d3: 'http://d3js.org/d3.v3.min',
                              topojson: 'http://d3js.org/topojson.v1.min'
                              }
                            }
                          );
                        require(["d3"], function(d3){
                            console.log('Loading Vincent from require.js...')
                            window.d3 = d3;
                            require(["topojson"], function(topojson){
                                window.topojson = topojson;
                                load_all_libs();
                            });
                        });
                    } else {
                        load_all_libs();
                    };
               }else{
                    console.log('Require.js not found, loading manually...')
                    load_all_libs();
               };

           </script>"""
         % (load_lib, load_js))
    return display(HTML(html))


@classmethod
def delete_data(cls, name):
    """
        Deletes the attribute with the given name from the thread local object
        """
    try:
        return delattr(cls.__locals, name)
    except AttributeError:
        return None


@classmethod
def from_text_bounded(cls, text, box_size, max_font_size, font_fn, *args,
    min_font_size=6, **kwargs):
    """Create image from text, reducing the font size until it fits. Inefficient."""
    return cls.generate_bounded(box_size, range(max_font_size,
        min_font_size - 1, -1), lambda size: cls.from_text(text, font_fn(
        size), *args, **kwargs))


def write_sms_bathy(triangles, nodes, z, filename):
    """
    Writes out the additional bathymetry file sometimes output by SMS. Not sure
    why this is necessary as it's possible to put the depths in the other file,
    but hey ho, it is obviously sometimes necessary.

    Parameters
    ----------
    triangles : np.ndarray
        Integer array of shape (ntri, 3). Each triangle is composed of
        three points and this contains the three node numbers (stored in
    nodes) which refer to the coordinates in `x' and `y' (see below). Give as
        a zero-indexed array.
    nodes : np.ndarray
        Integer number assigned to each node.
    z : np.ndarray
        Depth values at each node location.
    filename : str
        Full path of the output file name.

    """
    fname = open(filename, 'w')
    node_number = len(nodes)
    element_number = len(triangles[:, (0)])
    header = (
        """DATASET
OBJTYEP = "mesh2d"
BEGSCL
ND  {:<6d}
NC  {:<6d}
NAME "Z_interp"
TS 0 0
"""
        .format(int(node_number), int(element_number)))
    fname.write(header)
    for depth in z:
        fname.write('{:.5f}\n'.format(float(depth)))
    fname.write('ENDDS\n')
    fname.close()


def a2z(a):
    """ converts from scale factor to  redshift """
    return 1.0 / a - 1.0


@classmethod
def from_settings(cls, settings=None, storage=None):
    """Create from settings.

        Parameters
        ----------
        settings : `dict`, optional
            Settings (default: None).
        storage : `type`, optional
            Storage class (default: cls.DEFAULT_STORAGE)

        Returns
        -------
        `markovchain.Markov`
        """
    if storage is None:
        storage = cls.DEFAULT_STORAGE
    return cls.from_storage(storage(settings=settings))


def _common_parser():
    """Returns a parser with common command-line options for all the scripts
    in the fortpy suite.
    """
    import argparse
    parser = argparse.ArgumentParser(add_help=False)
    parser.add_argument('-examples', action='store_true', help=
        'See detailed help and examples for this script.')
    parser.add_argument('-verbose', action='store_true', help=
        'See verbose output as the script runs.')
    parser.add_argument('-action', nargs=1, choices=['save', 'print'],
        default='print', help=
        'Specify what to do with the output (print or save)')
    parser.add_argument('-debug', action='store_true', help=
        'Print verbose calculation information for debugging.')
    return parser


def six_hump_camel_func(x):
    """
    Definition of the six-hump camel
    """
    x1 = x[0]
    x2 = x[1]
    term1 = (4 - 2.1 * x1 ** 2 + x1 ** 4 / 3) * x1 ** 2
    term2 = x1 * x2
    term3 = (-4 + 4 * x2 ** 2) * x2 ** 2
    return term1 + term2 + term3


def update_notification_settings(HITTypeId=None, Notification=None, Active=None
    ):
    """
    The UpdateNotificationSettings operation creates, updates, disables or re-enables notifications for a HIT type. If you call the UpdateNotificationSettings operation for a HIT type that already has a notification specification, the operation replaces the old specification with a new one. You can call the UpdateNotificationSettings operation to enable or disable notifications for the HIT type, without having to modify the notification specification itself by providing updates to the Active status without specifying a new notification specification. To change the Active status of a HIT type's notifications, the HIT type must already have a notification specification, or one must be provided in the same call to UpdateNotificationSettings .
    See also: AWS API Documentation

    :example: response = client.update_notification_settings(
        HITTypeId='string',
        Notification={
            'Destination': 'string',
            'Transport': 'Email'|'SQS',
            'Version': 'string',
            'EventTypes': [
                'AssignmentAccepted'|'AssignmentAbandoned'|'AssignmentReturned'|'AssignmentSubmitted'|'AssignmentRejected'|'AssignmentApproved'|'HITCreated'|'HITExpired'|'HITReviewable'|'HITExtended'|'HITDisposed'|'Ping',
            ]
        },
        Active=True|False
    )

    :type HITTypeId: string
    :param HITTypeId: [REQUIRED]
            The ID of the HIT type whose notification specification is being updated.

    :type Notification: dict
    :param Notification: The notification specification for the HIT type.
            Destination (string) -- [REQUIRED]The destination for notification messages. or email notifications (if Transport is Email), this is an email address. For Amazon Simple Queue Service (Amazon SQS) notifications (if Transport is SQS), this is the URL for your Amazon SQS queue.
            Transport (string) -- [REQUIRED]The method Amazon Mechanical Turk uses to send the notification. Valid Values: Email | SQS.
            Version (string) --The version of the Notification API to use. Valid value is 2006-05-05.
            EventTypes (list) --The list of events that should cause notifications to be sent. Valid Values: AssignmentAccepted | AssignmentAbandoned | AssignmentReturned | AssignmentSubmitted | AssignmentRejected | AssignmentApproved | HITCreated | HITExtended | HITDisposed | HITReviewable | HITExpired | Ping. The Ping event is only valid for the SendTestEventNotification operation.
            (string) --

    :type Active: boolean
    :param Active: Specifies whether notifications are sent for HITs of this HIT type, according to the notification specification. You must specify either the Notification parameter or the Active parameter for the call to UpdateNotificationSettings to succeed.

    :rtype: dict
    :return: {}

    :returns:
    (dict) --

    """
    pass


def compress_level(level: int) ->None:
    """
    Set compress level

    Args:
        level: int
            An integer from 0 to 9 controlling the level of compression;
            1 is fastest and produces the least compression, 9 is slowest
            and produces the most. 0 is no compression. The default value
            is 0.
    """
    global __compress_level
    __compress_level = level


def get_one_of(d, keys):
    """ Returns the (key, value) pair of the first key of `keys` found in `d`.
	"""
    for key in keys:
        try:
            return key, d[key]
        except KeyError:
            pass
    raise KeyError('None of the {} keys could be found'.format(len(keys)))


def sortM20(cells):
    """needs a doc string"""
    T = []
    for i, M in enumerate(cells):
        T.append((M[0], i))
    D = dict(zip(T, cells))
    T.sort()
    T.reverse()
    X = []
    for key in T:
        X.append(D[key])
    return X


def deleteLink(nodeA, nodeB):
    """Delete a link between two node objects.

    This function can be empty. Used for optional complex database quieries.

    Parameters:
        nodeA (MgvNode): source node.
        nodeB (MgvNode): destination node.
    """
    return


def p_opt_if_exists(p):
    """opt_IF_EXISTS : IF EXISTS"""
    p[0] = True


def keying_set_path_add():
    """Add empty path to active Keying Set

    """
    pass


@classmethod
def format_z(cls, offset):
    """ Format `timedelta` into %z """
    sec = offset.total_seconds()
    return '{s}{h:02d}{m:02d}'.format(s='-' if sec < 0 else '+', h=abs(int(
        sec / 3600)), m=int(sec % 3600 / 60))


@classmethod
def from_items(cls, connection, items, casout=None, **kwargs):
    """
        Create a CASTable from a (key, value) pairs

        Parameters
        ----------
        connection : :class:`CAS`
            The :class:`CAS` connection to read the data into.
        items : tuples
            The tuples containing the data.  The values should be arrays
            or :class:`pandas.Series`.
        casout : string or :class:`CASTable`, optional
            The output table specification.  This includes the following parameters.
                name : string, optional
                    Name of the output CAS table.
                caslib : string, optional
                    CASLib for the output CAS table.
                label : string, optional
                    The label to apply to the output CAS table.
                promote : boolean, optional
                    If True, the output CAS table will be visible in all sessions.
                replace : boolean, optional
                    If True, the output CAS table will replace any existing CAS.
                    table with the same name.
        **kwargs : keyword arguments
            Keyword arguments sent to :meth:`pandas.DataFrame.from_items`.

        See Also
        --------
        :meth:`pandas.DataFrame.from_items`

        Returns
        -------
        :class:`CASTable`

        """
    return cls._from_any('items', connection, items, casout=casout, **kwargs)


def bbox_equals(src_bbox, dst_bbox, x_delta=None, y_delta=None):
    """
    Compares two bbox and checks if they are equal, or nearly equal.

    :param x_delta: how precise the comparison should be.
                    should be reasonable small, like a tenth of a pixel.
                    defaults to 1/1.000.000th of the width.
    :type x_delta: bbox units

    >>> src_bbox = (939258.20356824622, 6887893.4928338043,
    ...             1095801.2374962866, 7044436.5267618448)
    >>> dst_bbox = (939258.20260000182, 6887893.4908000007,
    ...             1095801.2365000017, 7044436.5247000009)
    >>> bbox_equals(src_bbox, dst_bbox, 61.1, 61.1)
    True
    >>> bbox_equals(src_bbox, dst_bbox, 0.0001)
    False
    """
    if x_delta is None:
        x_delta = abs(src_bbox[0] - src_bbox[2]) / 1000000.0
    if y_delta is None:
        y_delta = x_delta
    return abs(src_bbox[0] - dst_bbox[0]) < x_delta and abs(src_bbox[1] -
        dst_bbox[1]) < x_delta and abs(src_bbox[2] - dst_bbox[2]
        ) < y_delta and abs(src_bbox[3] - dst_bbox[3]) < y_delta


def _get_native_location(name):
    """
    Fetches the location of a native MacOS library.
    :param name: The name of the library to be loaded.
    :return: The location of the library on a MacOS filesystem.
    """
    return '/System/Library/Frameworks/{0}.framework/{0}'.format(name)


def _find_exon(subexon_table, subexon_id_cluster):
    """Return a list with the 'ExonID's of a particular subexon."""
    return subexon_table.loc[subexon_table['SubexonIDCluster'] ==
        subexon_id_cluster, 'ExonIDCluster'].unique().tolist()


def psi_H_Na_Br_PK74(T, P):
    """c-c'-a: hydrogen sodium bromide [PK74]."""
    psi = -0.012
    valid = T == 298.15
    return psi, valid


def getProperties():
    """Gets the properties as dictionary.

        keep_entries, copy_to_logfile, ignored_exceptions
        """


def uniq(obj, uniqs, got_uniqs):
    """ see if this object is uniq. """
    if not uniqs:
        return False
    for key in uniqs:
        val = obj.get(key, None)
        if val and val not in got_uniqs.get(key, []):
            got_uniqs.register(key, val)
            return True
        else:
            return False
    return True


def palettecolor_isolate(affect_visibility: bool=False):
    """Toggle whether the active color is the only one that is editable and/or visible

    :param affect_visibility: Affect Visibility, In addition to toggling the editability, also affect the visibility
    :type affect_visibility: bool
    """
    pass


@staticmethod
def edit(*_, **__):
    """Dummy function to disable writing to content."""
    raise NotImplementedError('Cannot edit a revision of a page.')


def vec2tuple(x):
    """ Converts a VECTOR3D to a Tuple """
    return x.x, x.y, x.z


def is_number_const(string):
    """ Returns value which indicates whether the string represents a number constant. """
    try:
        float(string)
        return True
    except ValueError:
        return False


@classmethod
def find_by_order(cls, store, work_order):
    """Find all items on of the given work_order

        :param work_order: |work_order|
        """
    return store.find(cls, work_order_id=work_order.id)


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

        :param SharedLinkCreateDetails val:
        :rtype: EventDetails
        """
    return cls('shared_link_create_details', val)


def parse_js_date(date):
    """
    Translate the easy-to-use JavaScript format strings to Python's cumbersome
    strftime format. Also, this is some ugly code -- and it's completely
    order-dependent.
    """
    if 'A' in date:
        date = date.replace('A', '%p')
    elif 'a' in date:
        date = date.replace('a', '%P')
    if 'HH' in date:
        date = date.replace('HH', '%H')
    elif 'H' in date:
        date = date.replace('H', '%k')
    elif 'hh' in date:
        date = date.replace('hh', '%I')
    elif 'h' in date:
        date = date.replace('h', '%l')
    if 'mm' in date:
        date = date.replace('mm', '%min')
    elif 'm' in date:
        date = date.replace('m', '%min')
    if 'ss' in date:
        date = date.replace('ss', '%S')
    elif 's' in date:
        date = date.replace('s', '%S')
    if 'SSS' in date:
        date = date.replace('SSS', '%3')
    if 'YYYY' in date:
        date = date.replace('YYYY', '%Y')
    elif 'YY' in date:
        date = date.replace('YY', '%y')
    if 'MMMM' in date:
        date = date.replace('MMMM', '%B')
    elif 'MMM' in date:
        date = date.replace('MMM', '%b')
    elif 'MM' in date:
        date = date.replace('MM', '%m')
    elif 'M' in date:
        date = date.replace('M', '%m')
    if 'dddd' in date:
        date = date.replace('dddd', '%A')
    elif 'ddd' in date:
        date = date.replace('ddd', '%a')
    elif 'dd' in date:
        date = date.replace('dd', '%w')
    elif 'd' in date:
        date = date.replace('d', '%u')
    if 'DDDD' in date:
        date = date.replace('DDDD', '%j')
    elif 'DDD' in date:
        date = date.replace('DDD', '%j')
    elif 'DD' in date:
        date = date.replace('DD', '%d')
    elif 'D' in date:
        date = date.replace('D', '%d')
    elif 'L' in date:
        date = date.replace('L', '%Y-%m-%dT%H:%M:%S')
    if '%min' in date:
        date = date.replace('%min', '%M')
    return date


@staticmethod
def get_jenkins_plugin_name():
    """Gets the name of the Jenkins plugin associated with this PyJen plugin

        This static method is used by the PyJen plugin API to associate this
        class with a specific Jenkins plugin, as it is encoded in the config.xml

        :rtype: :class:`str`
        """
    return (
        'org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject'
        )


@staticmethod
def metadata_id(item):
    """Extracts the identifier from a Redmine item."""
    return str(item['id'])


def select_nth(nth: int=2, skip: int=1, offset: int=0):
    """Deselect every other vertex

    :param nth: Nth Selection
    :type nth: int
    :param skip: Skip
    :type skip: int
    :param offset: Offset
    :type offset: int
    """
    pass


def add_var_from_expression(model, name, expr, lb=None, ub=None):
    """Add a variable to a model equaling an expression."""
    var = model.problem.Variable(name, lb=lb, ub=ub)
    const = model.problem.Constraint((var - expr).expand(), lb=0, ub=0,
        name=name + '_equality')
    model.add_cons_vars([var, const])
    return var


@classmethod
def get_market_spread(cls, pair):
    """return first buy order and first sell order"""
    from decimal import Decimal
    order_book = cls.get_market_order_book(pair)
    ask = order_book['asks'][0][0]
    bid = order_book['bids'][0][0]
    return Decimal(ask) - Decimal(bid)


@classmethod
def elastic_mapping(cls):
    """
        Return an ES mapping for the current class. Should basically be some
        form of ``return ESMapping(...)``.
        """
    raise NotImplementedError('ES classes must define a mapping')


def createMainWidget(argv):
    """
    Function to create the main widget.

    @param argv list of commandline parameters (list of strings)
    @return reference to the main widget (QWidget)
    """
    from SqlBrowser.SqlBrowser import SqlBrowser
    if len(argv) > 1:
        connections = argv[1:]
    else:
        connections = []
    browser = SqlBrowser(connections)
    return browser


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

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

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


def _execute(q, table, context):
    """
    Takes an SqlAlchemy query (q) that is (at its base) a Select on an
    object table (table), and it returns the object.

    Analogous with _execute_with_revision, so takes the same params, even
    though it doesn't need the table.
    """
    model = context['model']
    session = model.Session
    return session.execute(q)


def showInvLines(rh):
    """
    Produce help output related to command synopsis

    Input:
       Request Handle
    """
    if rh.subfunction != '':
        rh.printLn('N', 'Usage:')
    rh.printLn('N', '  python ' + rh.cmdName + ' PowerVM <userid>')
    rh.printLn('N', '                    [isreachable | pause | ' +
        'status | unpause]')
    rh.printLn('N', '  python ' + rh.cmdName + ' PowerVM <userid>')
    rh.printLn('N', '                    [on | reset] --wait --state ' +
        '[on | up] --maxwait <secs>')
    rh.printLn('N', '                    --poll <secs>')
    rh.printLn('N', '  python ' + rh.cmdName + ' PowerVM <userid>')
    rh.printLn('N', '                    [off | reboot | softoff] ' +
        '--maxwait <secs> --poll <secs>')
    rh.printLn('N', '  python ' + rh.cmdName + ' PowerVM ' + '<userid> wait')
    rh.printLn('N', '                    --state [down | on | off | up] ' +
        '--maxwait <secs>')
    rh.printLn('N', '                    --poll <secs>')
    rh.printLn('N', '  python ' + rh.cmdName + ' PowerVM help')
    rh.printLn('N', '  python ' + rh.cmdName + ' PowerVM version')
    return


def showOperandLines(rh):
    """
    Produce help output related to operands.

    Input:
       Request Handle
    """
    if rh.function == 'HELP':
        rh.printLn('N', '  For the DeleteVM function:')
    else:
        rh.printLn('N', 'Sub-Functions(s):')
    rh.printLn('N', '      directory     - ' +
        'Delete a virtual machine from the user directory.')
    rh.printLn('N', '      help          - ' +
        'Displays this help information.')
    rh.printLn('N', '      version       - ' +
        'Show the version of the power function')
    if rh.subfunction != '':
        rh.printLn('N', 'Operand(s):')
    rh.printLn('N', '      <userid>      - ' +
        'Userid of the target virtual machine')
    return


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

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

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

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

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

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


def write(schemaNode, schema):
    """Write the metadata contained in the given schema, to the
        schemaNode. The node will already exist and be populated with
        standard data.
        """


def get_machine_count(ip_config):
    """Get total machine count
    """
    with open(ip_config) as f:
        machine_count = len(f.readlines())
    return machine_count


@classmethod
def default_content_type(cls):
    """
        Default content_type.
        """
    return 'plain'


def escape(s):
    """
    Escape a string.
    """
    s = s.replace('\\\\', '\\\\\\\\')
    s = s.replace('"', '\\"')
    s = '"%s"' % s
    return s


def is_set(value):
    """Checks if the given value is a set object or not.

    Args:
        value (mixed): Value passed in by the user.

    Returns:
        bool: True if the given value is a set else False.

    Example:

        >>> is_set(set([1, 2]))
        True
        >>> is_set([1, 2, 3])
        False

    .. versionadded:: 4.0.0
    """
    return isinstance(value, set)


def _find_from_file(full_doc, from_file_keyword):
    """
    Finds a line in <full_doc> like

        <from_file_keyword> <colon> <path>

    and return path
    """
    path = None
    for line in full_doc.splitlines():
        if from_file_keyword in line:
            parts = line.strip().split(':')
            if len(parts) == 2 and parts[0].strip() == from_file_keyword:
                path = parts[1].strip()
                break
    return path


def _model_field_values(model_instance) ->dict:
    """Return model fields values (with the proper type) as a dictionary."""
    return model_instance.schema().dump(model_instance)


def contours(img, c):
    """
        Draw contours on image

    """
    raise NotImplementedError


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

    The ".dev0" means dirty.

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


def isint(s):
    """
    Функция, которая возращает True, если  строка является целым числом, и False в ином случае.
    Parameters
    ----------
    s (str) : строка с целым числом.

    Returns
    -------
    (boolean) True, если  строка является целым числом, и False в ином случае.
    """
    if isinstance(s, str):
        try:
            s = int(s)
            return True
        except:
            return False
    else:
        return False


@classmethod
def _strip_commas(cls, kw):
    """Strip out any leading/training commas from the token"""
    kw = kw[:-1] if kw[-1] == ',' else kw
    return kw[1:] if kw[0] == ',' else kw


@staticmethod
def check_for_export(context, volume_id):
    """Make sure volume is exported.

        :param context: the context
        :param volume_id: the volume id
        """
    pass


def __new__(cls, content, default=None, project=None, option=None):
    """Set endpoint sources."""
    endpoint = str.__new__(cls, content)
    endpoint.default = default
    endpoint.project = project
    endpoint.option = option
    return endpoint


def split_by_n(seq, chunk_size):
    """ Generator splitting a sequence into chunks """
    while seq:
        yield seq[:chunk_size]
        seq = seq[chunk_size:]


def bulk_docs(docs, **kwargs):
    """Create, update or delete multiple documents.

    http://docs.couchdb.org/en/stable/api/database/bulk-api.html#post--db-_bulk_docs

    :param list docs: The sequence of documents to be sent.
    :param kwargs: (optional) Arguments that :meth:`requests.Session.request` takes.
    :rtype: (str, str, dict)
    """
    if 'json' not in kwargs or not isinstance(kwargs['json'], dict):
        kwargs['json'] = {}
    kwargs['json']['docs'] = docs
    return 'POST', '_bulk_docs', kwargs


def create_domain_sequence(domains, keep_unknown=True, fmt_fn=lambda x: x):
    """
    We can pass a <fmt_fn> to reformat domain names (e.g. turn PF07005.14
    into PF07005). By default, the identity function is used, which just
    returns the input as is.

    If <keep_unknown>, all ORFs w/o domain calls are turned into "unknown"
    domains, 1 per ORF.
    """
    from collections import defaultdict
    from nanotext.utils import split_orf_uid
    d = defaultdict(list)
    for i in domains:
        d[split_orf_uid(i.fields[0])].append(fmt_fn(i.fields[3]))
    result = defaultdict(list)
    cache_orf = 0
    cache_contig = ''
    for k, v in sorted(d.items()):
        contig, orf = k
        if cache_contig != contig:
            cache_contig = contig
            cache_orf = 0
        if keep_unknown and cache_orf + 1 != orf:
            result[contig].extend(['unknown'] * (orf - cache_orf - 1))
        result[contig].extend(v)
        cache_orf = orf
    return result


@classmethod
def parse_args(cls, subparsers):
    """Add Cloud Object Storage arguments to command line parser."""
    cos_oo_parser = subparsers.add_parser('cos', description=cls.__doc__)
    cos_oo_parser.add_argument('-e', '--endpoint-url', help=
        'endpoint URL of the S3 storage')
    cos_oo_parser.add_argument('-s', '--instance-id', help=
        'service instance id')
    cos_oo_parser.add_argument('-u', '--access-key', help=
        'acccess key id of HMAC credentials')
    cos_oo_parser.add_argument('-p', '--secret-key', help=
        'secret access key of HMAC credentials')
    cos_oo_parser.add_argument('local_path', nargs='?', default=None, help=
        'path in the local file system of the file to be uploaded')
    cos_oo_parser.add_argument('bucket', help='target s3 bucket')
    cos_oo_parser.add_argument('remote_path', help=
        """path on Cloud Object Storage where the file
                                  will be stored"""
        )


def copyDisplayProperties(displayCtx, src, dest, displayExclude=None,
    optExclude=None, displayArgs=None, optArgs=None):
    """Copies all properties from the ``src`` :class:`.Display` and
    :class:`.DisplayOpts` instances to the ``dest`` instances.

    :arg displayCtx:     The :class:`.DisplayContext`

    :arg displayExclude: Collection of :class:`.Display` properties which
                         should not be copied

    :arg optExclude:     Collection of :class:`.DisplayOpts` properties which
                         should not be copied

    :arg displayArgs:    Values to be used instead of the ``src`` ``Display``
                         values.

    :arg optArgs:        Values to be used instead of the ``src``
                         ``DisplayOpts`` values.
    """
    if displayExclude is None:
        displayExclude = []
    if optExclude is None:
        optExclude = []
    if displayArgs is None:
        displayArgs = {}
    if optArgs is None:
        optArgs = {}
    srcDisplay = displayCtx.getDisplay(src)
    destDisplay = displayCtx.getDisplay(dest)
    for prop in srcDisplay.getAllProperties()[0]:
        if prop in displayExclude:
            continue
        if not srcDisplay.propertyIsEnabled(prop
            ) or not destDisplay.propertyIsEnabled(prop):
            continue
        val = displayArgs.get(prop, getattr(srcDisplay, prop))
        if prop == 'overlayType':
            choices = destDisplay.getProp('overlayType').getChoices(destDisplay
                )
            if val not in choices:
                continue
        setattr(destDisplay, prop, val)
    srcOpts = displayCtx.getOpts(src)
    destOpts = displayCtx.getOpts(dest)
    for prop in srcOpts.getAllProperties()[0]:
        if prop in optExclude:
            continue
        if not hasattr(destOpts, prop):
            continue
        if not srcOpts.propertyIsEnabled(prop
            ) or not destOpts.propertyIsEnabled(prop):
            continue
        val = optArgs.get(prop, getattr(srcOpts, prop))
        setattr(destOpts, prop, val)


def _make_tree_defs(mod_files_list):
    """get a list of 2-uple (module, list_of_files_which_import_this_module),
    it will return a dictionary to represent this as a tree
    """
    tree_defs = {}
    for mod, files in mod_files_list:
        node = tree_defs, ()
        for prefix in mod.split('.'):
            node = node[0].setdefault(prefix, [{}, []])
        node[1] += files
    return tree_defs


@classmethod
def from_orm(cls, orm_server):
    """Create a server from an orm.Server"""
    return cls(orm_server=orm_server)


def is_seq(o):
    """Check if the object is a sequence.

    Parameters
    ----------
    o : any object
      The object to check

    Returns
    -------
    is_seq : bool, scalar
      True if *o* is a sequence, False otherwise
    """
    return hasattr(o, '__len__')


@staticmethod
def _normalize_hdf5_name(name: str) ->str:
    """ Handles names with / in them, which is disallowed in HDF5 """
    if ':' in name:
        raise ValueError("':' not allowed in names")
    return name.replace('/', ':')


@staticmethod
def _get_mouse_button_number(event):
    """Get the button number."""
    return event.buttonNumber()


@staticmethod
def _is_empty(value):
    """Check whether the given value should be considered "empty"."""
    return value is None or value == '' or isinstance(value, (list, tuple,
        dict)) and not value


@staticmethod
def stopid(stop):
    """Key to sort a list of stops by their Stop ID
        """
    return stop.stopid


def ensure_object_is_string(item, title):
    """
    Checks that the item is a string. If not, raises ValueError.
    """
    assert isinstance(title, str)
    if not isinstance(item, str):
        msg = '{} must be a string. {} passed instead.'
        raise TypeError(msg.format(title, type(item)))
    return None


def generate_int(field, factory):
    """Generate an int.

    :returns: a unique integer.
    :return_type: int
    """
    return factory.getUniqueInteger()


def vertex_weight_delete(weight_group: int=-1):
    """Delete this weight from the vertex (disabled if vertex group is locked)

    :param weight_group: Weight Index, Index of source weight in active vertex group
    :type weight_group: int
    """
    pass


@staticmethod
def intersection_point(center_x, center_y, source_x, source_y, width,
    height=None):
    """Determines where the triangle centered at (center_x, center_y)
        intersects with a line drawn from (source_x, source_y) to
        (center_x, center_y).

        @see: ShapeDrawer.intersection_point"""
    height = height or width
    return center_x, center_y


@staticmethod
def _allocate_space(current_directory) ->int:
    """Attempt to allocate directory `data{n}`, increment until success.

        Returns
        -------
        _postfix : int
            The number corresponding to the allocated directory.
        """
    _postfix = 0
    while True:
        _attempt = current_directory.joinpath('data' + str(_postfix))
        if not _attempt.exists():
            _attempt.mkdir(parents=True)
            break
        else:
            _postfix += 1
    return _postfix


def get_network_type_from_other_config(bridge, port_name):
    """Return network_type stored in OVSDB other_config metadata.

    :param bridge: OVSBridge instance where port is.
    :param port_name: Name of the port.
    """
    other_config = bridge.db_get_val('Port', port_name, 'other_config')
    return other_config.get('network_type')


def atse_reRegisterObject(object):
    """ re-registering object """


def _from_hass_brightness(brightness):
    """Convert Home Assistant brightness units to percentage."""
    return brightness / 255


def is_file_like(obj):
    """Check file like object

    Args:
        obj:
            file like object.

    Returns:
        bool: file like object or not
    """
    if not (hasattr(obj, 'read') or hasattr(obj, 'write')):
        return False
    if not hasattr(obj, '__iter__'):
        return False
    return True


def sign_data(priv_key, data, encoded=True):
    """
    Create a signature for a set of data using private key
    :param priv_key: Private key
    :param data: String data that the signature is being created for
    :param encoded: Boolean. True for base64 encoded data input
    False for raw data input
    :return: Base64 encoded signature
    """
    from Crypto.PublicKey import RSA
    from Crypto.Signature import PKCS1_v1_5
    from Crypto.Hash import SHA256
    from base64 import b64encode, b64decode
    rsakey = RSA.importKey(priv_key)
    signer = PKCS1_v1_5.new(rsakey)
    digest = SHA256.new()
    if encoded:
        digest.update(b64decode(data))
    else:
        digest.update(data)
    sign = signer.sign(digest)
    return b64encode(sign).decode('unicode_escape')


@classmethod
def from_inventory(cls, inventory, grid=None):
    """
        Creates an `EODataCube` instance from a given inventory.

        Parameters
        ----------
        inventory : GeoDataFrame
            Contains information about the dimensions (columns) and each filepath (rows).
        grid : pytileproj.base.TiledProjection, optional
            Tiled projection/grid object/class (e.g. `Equi7Grid`, `LatLonGrid`).

        Returns
        -------
        EODataCube
            Data cube consisting of data stored in `inventory`.
        """
    return cls(inventory=inventory, grid=grid)


def smoothstep(a, b, x):
    """ Returns the Hermite interpolation (cubic spline) for x between a and b.
        The return value between 0.0-1.0 eases (slows down) as x nears a or b.
    """
    if x < a:
        return 0.0
    if x >= b:
        return 1.0
    x = float(x - a) / (b - a)
    return x * x * (3 - 2 * x)


def __deserialize_file(response):
    """Deserializes body to file

    More specifically it just returns a pointer to the binary content
    of the response, so the user can decide what do do with the data.
    """
    return response.content


def process_attributes(cas_response):
    """Handles processing the attributes of a CAS3 SAML 1.1(?) response.

    I've seen three different types:
    1) The <cas:authenticationSuccess> element has several <cas:attribute>
       children, each of which has a 'name' and 'value' attribute.
    2) The <cas:authenticationSuccess> element has one <cas:attributes> child,
       which has several <cas:attribute> children, each of which has sibling
       <cas:name> and <cas:value> children
    3) The <cas:authenticationSuccess> element has several children, of the
       form <cas:{attribute name}>{attribute value}</cas:{attribute_name}>

    This should returns a dict version of the attributes, no matter what form
    they take (or, god forbid, a mix for some reason)

    TODO this needs testing for every case still!
    """
    out = {}
    nsmap = {'cas': 'http://www.yale.edu/tp/cas'}
    loose_attributes = cas_response.findall('*/cas:attribute', nsmap)
    for attribute in loose_attributes:
        key = None
        value = None
        key_elt = attribute.find('cas:name', nsmap)
        value_elt = attribute.find('cas:value', nsmap)
        if key_elt and value_elt:
            key = key_elt.text
            value = value_elt.text
        if attribute.attrib:
            key = attribute.attrib['name']
            value = attribute.attrib['value']
        if key and value:
            out[key] = value
    named_attributes = cas_response.xpath(
        '*/cas:attributes/*[not(cas:attribute)]', namespaces=nsmap)
    for attribute in named_attributes:
        key = attribute.tag.split('}')[-1]
        value = attribute.text
        if key and value:
            out[key] = value
    return out


@classmethod
def rolling_mean(cls, df, columns, groupby_column, n=0, min_periods=3):
    """
        Returns a DataFrame with the rolling mean of some columns.
        df: Dataframe.
        columns: (str, list) Column names to apply the rolling mean.
        column_id: (str, list) Column names to use as a grouper.
        n: Window for the rolling. 0 is equivalent to a rolling historical mean.
        min_periods: Minimum number of periods to show the rolling.
        """
    if isinstance(columns, str):
        columns = [columns]
    if isinstance(groupby_column, str):
        groupby_column = [groupby_column]
    all_columns = columns + groupby_column
    if n > 0:
        return df[all_columns].groupby(groupby_column).rolling(min_periods=
            min_periods, window=n).mean().reset_index(drop=True)[columns]
    else:
        return df[all_columns].groupby(groupby_column).expanding(min_periods
            =min_periods).mean().reset_index(drop=True)[columns]


def randomize_iteration(randomize=True):
    """
    Fake implementation.
    In CodeSkulptor this function modify the default behaviour
    of iterations on ``dict`` and ``set``.
    In SimpleGUICS2Pygame this function does nothing.

    See `CodeSkulptor3 randomize_iteration documentation`_.

    .. _`CodeSkulptor3 randomize_iteration documentation`: https://py3.codeskulptor.org/docs.html#randomize-iteration

    (Available in CodeSkulptor
    but *not in CodeSkulptor documentation*!)

    :randomize bool:
    """


def compute_normalized_license(declared_license):
    """
    Return a normalized license_expression string using the declared_license
    field. Return 'unknown' if there is a declared license but it cannot be
    detected (including on errors) and return None if there is no declared
    license.
    """
    if not declared_license or not declared_license.strip():
        return
    from packagedcode import licensing
    try:
        return licensing.get_normalized_expression(declared_license)
    except Exception:
        return 'unknown'


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

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

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


def handle_lrr_message(sender, message):
    """
    Handles message events from the AlarmDecoder.
    """
    print(sender, message.partition, message.event_type, message.event_data)


def check_args(data):
    """
    这里如果判断  参数都小于10 认为可以通过检查
    :param data:
    :return:
    """
    args = data.get('args')
    max_value = max(args)
    if max_value > 10:
        return True
    return False


@classmethod
def verify(cls, token, source, **kwds):
    """
        Convenience wrapper around :meth:`TOTP.from_source` and :meth:`TOTP.match`.

        This parses a TOTP key & configuration from the specified source,
        and tries and match the token.
        It's designed to parallel the :meth:`freenet_passlib_170.ifc.PasswordHash.verify` method.

        :param token:
            Token string to match.

        :param source:
            Serialized TOTP key.
            Can be anything accepted by :meth:`TOTP.from_source`.

        :param \\*\\*kwds:
            All additional keywords passed to :meth:`TOTP.match`.

        :return:
            A :class:`TotpMatch` instance, or raises a :exc:`TokenError`.
        """
    return cls.from_source(source).match(token, **kwds)


def farm_get_msg():
    """Reads a mule farm message.

     * http://uwsgi.readthedocs.io/en/latest/Embed.html

     .. warning:: Bytes are returned for Python 3.

     :rtype: bytes|str|None

     :raises ValueError: If not in a mule
     """


def quaternion_real(quaternion):
    """Return real part of quaternion.

    >>> quaternion_real([3, 0, 1, 2])
    3.0

    """
    return float(quaternion[0])


def stage(hub, name):
    """
    Apply the exclude value
    """
    low = hub.idem.treq.apply(hub.idem.RUNS[name]['subs'], hub.idem.RUNS[
        name]['low'])
    hub.idem.RUNS[name]['low'] = low


def unshuffle(sinogram):
    """ unshuffle singram by angle

    Return a list of 51 sinograms, by unshuffling the provided
    sinogram; so that all projections in the result correspond
    to the same gantry rotation angle, analogous to a fluence map.

    Parameters
    ----------
    sinogram : np.array

    Returns
    -------
    unshuffled: list of sinograms

    """
    unshufd = [[] for i in range(51)]
    idx = 0
    for prj in sinogram:
        unshufd[idx].append(prj)
        idx = (idx + 1) % 51
    return unshufd


def birch_murnaghan(volumes, volume0, bulk_modulus0, bulk_deriv0):
    """
    This evaluates the Birch Murnaghan equation of states
    """
    PV = []
    EV = []
    v0 = volume0
    bm = bulk_modulus0
    dbm = bulk_deriv0
    for vol in volumes:
        pv_val = 3 * bm / 2.0 * ((v0 / vol) ** (7 / 3.0) - (v0 / vol) ** (5 /
            3.0)) * (1 + 3 / 4.0 * (dbm - 4) * ((v0 / vol) ** (2 / 3.0) - 1))
        PV.append(pv_val)
        ev_val = 9 * bm * v0 / 16.0 * ((dbm * (v0 / vol) ** (2 / 3.0) - 1) **
            3 * ((v0 / vol) ** (2 / 3.0) - 1) ** 2 * (6 - 4 * (v0 / vol) **
            (2 / 3.0)))
        EV.append(ev_val)
    return EV, PV


def frozen():
    """Returns true if application is frozen"""
    import sys
    return hasattr(sys, 'frozen')


def PolsAccDeath(t):
    """Number of policies: Accidental death"""
    return 0


def Iterate(c):
    """
    Python generator to iterate through a collection of BTK objects (Points, Analogs, Events and Metadata).

    For example:

    for i in btk.Iterate(acq.GetPoints()):
        print i.GetLabel()
    """
    i = c.Begin()
    while i != c.End():
        yield i.value()
        i.incr()