def tricky_split(line, delim):
    """tricky_split(line, delim) - split line by delimiter delim, but ignoring
       delimiters found inside ()'s, []'s, {}'s, '''s and ""'s.

       eg: tricky_split("email(root,'hi there'),system('echo hi, mum')", ',')
       would return: [ "email(root,'hi there')", "system('echo hi, mum')" ]
    """
    parenCnt = 0
    curlyCnt = 0
    squareCnt = 0
    doubleqCnt = 0
    quoteCnt = 0
    list = []
    current = ''
    for c in line:
        if c == '(':
            parenCnt = parenCnt + 1
        elif c == ')':
            parenCnt = parenCnt - 1
        elif c == '{':
            curlyCnt = curlyCnt + 1
        elif c == '}':
            curlyCnt = curlyCnt - 1
        elif c == '[':
            squareCnt = squareCnt + 1
        elif c == ']':
            squareCnt = squareCnt - 1
        elif c == '"':
            doubleqCnt = 1 - doubleqCnt
        elif c == "'":
            quoteCnt = 1 - quoteCnt
        elif c == delim:
            if (parenCnt == 0 and curlyCnt == 0 and squareCnt == 0 and
                doubleqCnt == 0 and quoteCnt == 0):
                list.append(current)
                current = ''
                continue
        current = current + c
    if len(current) > 0:
        list.append(current)
    return list


def _token_from_text(data):
    """str -> Tuple[str, str]"""
    return data.strip().strip(')').rsplit('(', 1)


def convert_bool(value):
    """helper to make sure bools are bools"""
    if value in (True, False):
        return value
    if value is None:
        return False
    if str(value).lower() in ('true', '1'):
        return True
    return False


def is_a_sequence(var, allow_none=False):
    """ Returns True if var is a list or a tuple (but not a string!)
    """
    return isinstance(var, (list, tuple)) or var is None and allow_none


def save_classifications(savedir, classifications, labels):
    """Read and return a list of parameters and samples stored in the result
    files

    Parameters
    ----------
    result_files: list
        list of result files
    classifications: dict
        dictionary of classification probabilities
    """
    import os
    import json
    base_path = os.path.join(savedir, '{}_{}_prior_pe_classification.json')
    for num, i in enumerate(classifications):
        for prior in i.keys():
            with open(base_path.format(labels[num], prior), 'w') as f:
                json.dump(i[prior], f)


@classmethod
def from_trackable(cls, trackable):
    """Return :class:`.Cache` instance from :class:`.Trackable`.

        This only makes sense, if trackable is currently placed in cache. Otherwise it will have
        unexpected behavior.

        :param .Trackable trackable: Source trackable.
        """
    return cls(trackable.geocaching, None, url=trackable.location_url)


def fireSystemEvent(eventType):
    """
        Fire a system-wide event.

        System-wide events are things like 'startup', 'shutdown', and
        'persist'.
        """


def application_package_reference_format(value):
    """Space-separated application IDs with optional version in 'id[#version]' format."""
    app_reference = value.split('#', 1)
    package = {'application_id': app_reference[0]}
    try:
        package['version'] = app_reference[1]
    except IndexError:
        pass
    return package


def mean(a, b):
    """
    Функция для расчета среднего значения
    """
    return (a + b) / 2


@classmethod
def from_nlp(cls, nlp, **cfg):
    """Factory to add to Language.factories via entry point."""
    return cls(nlp.vocab, **cfg)


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 to_integer(obj):
    """Converts `obj` to an integer.

    Args:
        obj (str|int|float): Object to convert.

    Returns:
        int: Converted integer or ``0`` if it can't be converted.

    Example:

        >>> to_integer(3.2)
        3
        >>> to_integer('3.2')
        3
        >>> to_integer('3.9')
        3
        >>> to_integer('invalid')
        0

    .. versionadded:: 4.0.0
    """
    try:
        num = int(float(obj))
    except (ValueError, TypeError):
        num = 0
    return num


@classmethod
def showSelector(class_, config, layout):
    """We must show the language selector if the p_config requires it and if
           there is more than 2 supported languages. Moreover, on some layouts,
           switching the language is not allowed."""
    if not config.languageSelector or config.forcedLanguage:
        return
    if len(config.languages) < 2:
        return
    return layout not in ('edit', 'search')


def scale_down(src_size, size):
    """Scales down crop size if it's larger than image size.

    If width/height of the crop is larger than the width/height of the image,
    sets the width/height to the width/height of the image.

    Parameters
    ----------
    src_size : tuple of int
        Size of the image in (width, height) format.
    size : tuple of int
        Size of the crop in (width, height) format.

    Returns
    -------
    tuple of int
        A tuple containing the scaled crop size in (width, height) format.

    Example
    --------
    >>> src_size = (640,480)
    >>> size = (720,120)
    >>> new_size = mx.img.scale_down(src_size, size)
    >>> new_size
    (640,106)
    """
    w, h = size
    sw, sh = src_size
    if sh < h:
        w, h = float(w * sh) / h, sh
    if sw < w:
        w, h = sw, float(h * sw) / w
    return int(w), int(h)


def nodeFilter(node):
    """Return True or False to determine whether to include the given node
        in the tree. Nodes are dicts with at least one key - 'item', the
        catalog brain of the object the node represents.
        """


@classmethod
def get_user(cls, pk):
    """Return user instance for given id"""
    raise NotImplementedError('Implement in subclass')


def get_import_path(_class):
    """
    Returns import path for a given class.
    """
    return '{}.{}'.format(_class.__module__, _class.__name__)


def get_stack_status(heat_cli, stack_id):
    """
    Returns the current status of the Heat stack
    :param heat_cli: the OpenStack heat client
    :param stack_id: the ID of the heat stack to retrieve
    :return:
    """
    return heat_cli.stacks.get(stack_id).stack_status


def tm(request):
    """Return shared transaction manager (from request)

    This is used together with "with" syntax for wrapping mutating
    code into a request owned transaction.

    :param request: request owning the transaction

    Example::

        with tm(request) as txn:  # begin transaction txn

            # do something

        # transaction txn commits or raises ConflictError

    """
    assert getattr(request, 'conn', None) is not None, 'Request has no conn'
    return request.conn.transaction_manager


def format_list(items, bullet='-', indent=0):
    """ Formats a list of strings. """
    prefix = ' ' * indent + bullet + ' '
    return prefix + prefix.join(items)


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

        :param PasswordChangeDetails val:
        :rtype: EventDetails
        """
    return cls('password_change_details', val)


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


def print_splitter_line():
    """
    Displays a dash separator in the form of a 10 dash (for separating test results)
    :return: None
    """
    print('-' * 10)


def ibatch(iterable, chunk_size=1):
    """
    Takes an iterable and yields individuals while chunking for performance.
    :param iterable: The iterable object to be chunked.
    :param chunk_size: Number of items to chunk before yielding individuals.
    :return: iterable
    """
    chunk_count = 0
    while 1:
        start = chunk_size * chunk_count
        data = iterable[start:start + chunk_size]
        try:
            for i in range(chunk_size):
                yield data[i]
        except IndexError:
            return
        chunk_count += 1


def p_compound_stmt(p):
    """compound_stmt : if_stmt
                     | if_else_stmt
                     | for_stmt
                     | do_stmt
                     | loop_stmt
                     | with_stmt
                     | repeat_stmt
                     | funcdef """
    p[0] = ['STATEMENTS', [p[1]]]


def is_json_metadata(text):
    """Is this a JSON metadata?"""
    first_curly_bracket = text.find('{')
    if first_curly_bracket < 0:
        return False
    first_equal_sign = text.find('=')
    if first_equal_sign < 0:
        return True
    return first_curly_bracket < first_equal_sign


def add_diff_cli_args(parser):
    """Adds a set of arguments for CLI diff commands (i.e. not web).
    """
    parser.add_argument('--color-words', action='store_true', default=False,
        help=
        'whether to pass the --color-words flag to any internal calls to git diff'
        )


@classmethod
def find(cls, db, name):
    """Find a user by name.
        Returns None if not found.
        """
    return db.query(cls).filter(cls.name == name).first()


def subnet_provides_public_ip_mapping(subnet):
    """True iff subnet will map public ips on launch"""
    return subnet['MapPublicIpOnLaunch']


def check_positive_integer(name, value):
    """Check a value is a positive integer.

    Returns the value if so, raises ValueError otherwise.

    """
    try:
        value = int(value)
        is_positive = value > 0
    except ValueError:
        raise ValueError('%s should be an integer; got %r' % (name, value))
    if is_positive:
        return value
    else:
        raise ValueError('%s should be positive; got %r' % (name, value))


@classmethod
def _get_all_parameters(cls):
    """Yield all parameters as tuples of (name,obj)"""
    for name in cls.get_all_parameter_names():
        yield name, getattr(cls, name)


def atse_schemataMoveRight(schema_id, schema_template, name, RESPONSE=None):
    """ move a schemata to the right"""


def degrees(data=None, out=None, name=None, **kwargs):
    """Converts each element of the input array from radians to degrees.

    .. math::
       degrees([0, \\pi/2, \\pi, 3\\pi/2, 2\\pi]) = [0, 90, 180, 270, 360]

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

       - degrees(default) = default
       - degrees(row_sparse) = row_sparse
       - degrees(csr) = csr

    Defined in src/operator/tensor/elemwise_unary_op_trig.cc:L274

    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 types_key(cls):
    """ Get the key used for specifying types to include from a file or namespace

        Override this method to use a different name for 'data_types'
        """
    return cls.__types_key


@classmethod
def parse_n_atoms(cls, filename, **kwargs):
    """Read the coordinate file and deduce the number of atoms

        Returns
        -------
        n_atoms : int
          the number of atoms in the coordinate file

        Raises
        ------
        NotImplementedError
          when the number of atoms can't be deduced
        """
    raise NotImplementedError('{} cannot deduce the number of atoms'.format
        (cls.__name__))


def make_data_tlsa(tlsa):
    "Make a tlsa data block for a 'config' chunk.\n\n    The format is:\n\n    +-1----+-2----+-N--------+-1--+-M-----------+-1--+\n    | spec | port | protocol | \x00 | tlsa_domain | \x00 |\n    +------+------+----------+----+-------------+----+\n\n    spec: the byte value is calculated as:\n        (36 * usage) + (6 * selector) + (matching type).\n        E.g., (usage, selector, matching type) = (3,1,1):\n            spec value = 3*36 + 1*6 + 1 = 115\n\n    Args:\n        tlsa (Tlsa): object containing the TLSA data.\n\n    Returns:\n        bytes: the data block as a byte string.\n    "
    return (36 * int(tlsa.usage) + 6 * int(tlsa.selector) + int(tlsa.matching)
        ).to_bytes(1, byteorder='big') + int(tlsa.port).to_bytes(2,
        byteorder='big') + tlsa.protocol.encode(
        ) + b'\x00' + tlsa.domain.encode() + b'\x00'


def absolute_lateral_stability(F_y, F_z, F_R, mu, W_sub, gamma_SC
    ) ->'abs_lat_stab_uty':
    """Absolute lateral stability unity check.
    Reference:
    DNVGL-RP-F109 (2017-05)
        sec:3.6.1, eq:3.38, page:31
    """
    abs_lat_stab_uty = gamma_SC * (F_y + mu * F_z) / (mu * W_sub + F_R)
    return abs_lat_stab_uty


def unimap(fname, species, ptm=None, mutation=None):
    """ The UniMap is a first attempt to make a universal PTMS reprository to help users to
	map PTMs to protein list and/or mutations to PTMs sites."""
    with open('pyntheon-data.txt', 'w') as ac:
        if species in ('arbacia', 'ap'):
            fname2 = 'Arbacia+punctulata-PTMs.txt'
        elif species in ('branchiostoma', 'bf'):
            fname2 = 'Branchiostoma+floridae-PTMs.txt'
        elif species in ('celegans', 'ce'):
            fname2 = 'Caenorhabditis+elegans-functional_data.txt'
        elif species in ('ciona', 'ci'):
            fname2 = 'Ciona+intestinalis-PTMs.txt'
        elif species in ('daphnia', 'dm'):
            fname2 = 'Daphnia+magna-PTMs.txt'
        elif species in ('euprymna', 'es'):
            fname2 = 'Euprymna+scolopes-PTMs.txt'
        elif species in ('galleria', 'gm'):
            fname2 = 'Galleria+mellonella-PTMs.txt'
        elif species in ('gryllus', 'gb'):
            fname2 = 'Gryllus+bimaculatus-PTMs.txt'
        elif species in ('hydra', 'hy'):
            fname2 = 'Hydra-PTMs.txt'
        elif species in ('loligo', 'lp'):
            fname2 = 'Loligo+pealei-PTMs.txt'
        elif species in ('nematostella', 'nv'):
            fname2 = 'Nematostella+vectensis-PTMs.txt'
        elif species in ('oikopleura', 'od'):
            fname2 = 'Oikopleura+dioica-PTMs.txtx'
        elif species in ('platynereis', 'pd'):
            fname2 = 'Platynereis+dumerilii-PTMs.txt'
        elif species in ('pristionchus', 'pp'):
            fname2 = 'Pristionchus+pacificus-PTMs.txt'
        elif species in ('schmidtea', 'sm'):
            fname2 = 'Schmidtea+mediterranea-PTMs.txt'
        elif species in ('symsagittifera', 'sr'):
            fname2 = 'Symsagittifera+roscoffensis-PTMs.txt'
        elif species in ('tribolium', 'tc'):
            fname2 = 'Tribolium+castaneum-PTMs.txt'
        elif species in ('amphimedon', 'aq'):
            fname2 = 'Amphimedon+queenslandica-PTMs.txt'
        elif species in ('aplysia', 'acc'):
            fname2 = 'Aplysia-PTMs.txt'
        elif species in ('ecoli', 'ec'):
            fname2 = 'Escherichia+coli-functional_data.txt'
        elif species in ('mycobacterium', 'mb'):
            fname2 = 'Mycobacterium+tuberculosis-functional_data.txt'
        elif species in ('ashbya', 'ag'):
            fname2 = 'Ashbya+gossypii.gff-PTMs.txt'
        elif species in ('Aspergillus+nidulans.gff-PTMs.txt', 'an'):
            fname2 = 'Aspergillus+nidulans.gff-PTMs.txt'
        elif species in ('coprinus', 'cc'):
            fname2 = 'Coprinus+cinereus-functional_data.txt'
        elif species in ('cryptococcus', 'cn'):
            fname2 = 'Cryptococcus+neoformans.gff-PTMs.txt'
        elif species in ('neurospora', 'nc'):
            fname2 = 'Neurospora+crassa-PTMs.txt'
        elif species in ('schizophyllum', 'sc'):
            fname2 = 'Schizophyllum+commune.gff-PTMs.txt'
        elif species in ('schizosaccharomyces', 'sp'):
            fname2 = 'Schizosaccharomyces+pombe.gff-PTMs.txt'
        elif species in ('ustilago', 'um'):
            fname2 = 'Ustilago+maydis-PTMs.txt'
        elif species in ('scerevisiae', 'sce'):
            fname2 = 'yeast-functional_data.txt'
        elif species in ('herpes', 'hsv'):
            fname2 = 'Herpes+simplex+virus-PTMs.txt'
        elif species in ('plambda', 'pl'):
            fname2 = 'Phage+lambda-PTMs.txt'
        elif species in ('Phi_X_174', 'px'):
            fname2 = 'Phi+X+174-PTMs.txt'
        elif species in ('sv40', 'sv'):
            fname2 = 'SV40-PTMs.txt'
        elif species in ('T4phage', 't4'):
            fname2 = 'T4+phage-PTMs.txt'
        elif species in ('tmvirus', 'tmv'):
            fname2 = 'Tobacco+mosaic+virus-PTMs.txt'
        elif species in ('chlamydomonas', 'cr'):
            fname2 = 'Chlamydomonas+reinhardtii.gff-PTMs.txt'
        elif species in ('dictyostelium', 'dd'):
            fname2 = 'Dictyostelium+discoideum.gff-PTMs.txt'
        elif species in ('emiliania', 'eh'):
            fname2 = 'Emiliania+huxleyi.gff-PTMs.txt'
        elif species in ('tetrahymena', 'tt'):
            fname2 = 'Tetrahymena+thermophila.gff-PTMs.txt'
        elif species in ('thalassiosira', 'tp'):
            fname2 = 'Thalassiosira+pseudonana.gff-PTMs.txt'
        elif species in ('aliivibrio', 'af'):
            fname2 = 'uniprot-Aliivibrio+fischeri.gff-PTMs.txt'
        elif species in ('bacillus', 'bs'):
            fname2 = 'uniprot-Bacillus+subtilis.gff-PTMs.txt'
        elif species in ('caulobacter', 'cac'):
            fname2 = 'uniprot-Caulobacter+crescentus.gff-PTMs.txt'
        elif species in ('pseudomonas', 'pf'):
            fname2 = 'uniprot-Pseudomonas+fluorescens.gff-PTMs.txt'
        elif species in ('synechocystis', 'sy'):
            fname2 = 'uniprot-Synechocystis.gff-PTMs.txt'
        elif species in ('mycoplasma', 'mg'):
            fname2 = 'uniprot-Mycoplasma+genitalium.gff-PTMs.txt'
        elif species in ('arabidopsis', 'at'):
            fname2 = 'arabidopsis+thaliana-functional_data.txt'
        elif species in ('brachypodium', 'bd'):
            fname2 = 'Brachypodium+distachyon.gff-PTMs.txt'
        elif species in ('lemna', 'lg'):
            fname2 = 'Lemna+gibba.gff-PTMs.txt'
        elif species in ('lotus', 'lj'):
            fname2 = 'Lotus+japonicus.gff-PTMs.txt'
        elif species in ('medicago', 'mt'):
            fname2 = 'Medicago+truncatula.gff-PTMs.txt'
        elif species in ('mimulus', 'mig'):
            fname2 = 'Mimulus+guttatus.gff-PTMs.txt'
        elif species in ('nicotiana', 'nb'):
            fname2 = 'Nicotiana+benthamiana.gff-PTMs.txt'
        elif species in ('oryza', 'os'):
            fname2 = 'Oryza+sativa.gffPTMs.txt'
        elif species in ('physcomitrella', 'php'):
            fname2 = 'Physcomitrella+patens.gff-PTMs.txt'
        elif species in ('populus', 'pt'):
            fname2 = 'Populus+trichocarpa.gff-PTMs.txt'
        elif species in ('selaginella', 'sem'):
            fname2 = 'Selaginella+moellendorffii.gff-PTMs.txt'
        elif species in ('setaria', 'sev'):
            fname2 = 'Setaria+viridis.gff-PTMs.txt'
        elif species in ('tobacco', 'tb'):
            fname2 = 'Tobacco+BY-2+cells.gff-PTMs.txt'
        elif species in ('zea', 'zm'):
            fname2 = 'Zea+mays.gff-PTMs.txt'
        elif species in ('anolis', 'ac'):
            fname2 = 'Anolis+carolinensis.gffPTMs.txt'
        elif species in ('bombina', 'bm'):
            fname2 = 'Bombina+maxima.gff-PTMs.txt'
        elif species in ('bombina', 'bo'):
            fname2 = 'Bombina+orientalis.gff-PTMs.txt'
        elif species in ('canis', 'cl'):
            fname2 = 'Canis+lupus.gff-PTMs.txt'
        elif species in ('cavia', 'cp'):
            fname2 = 'Cavia+porcellus.gff-PTMs.txt'
        elif species in ('columba', 'cld'):
            fname2 = 'Columba+livia+domestica.gff-PTMs.txt'
        elif species in ('drosophila', 'do'):
            fname2 = 'drosophila-functional_data.txt'
        elif species in ('felis', 'fc'):
            fname2 = 'Felis+catus.gff-PTMs.txt'
        elif species in ('gallus', 'gg'):
            fname2 = 'Gallus+gallus.gff-PTMs.txt'
        elif species in ('gasterosteus', 'ga'):
            fname2 = 'Gasterosteus+aculeatus.gff-PTMs.txt'
        elif species in ('heterocephalus', 'hg'):
            fname2 = 'Heterocephalus+glaber.gff-PTMs.txt'
        elif species in ('hsapiens', 'hs'):
            fname2 = 'human-functional_data.txt'
        elif species in ('mesocricetus', 'ma'):
            fname2 = 'Mesocricetus+auratus.gff-PTMs.txt'
        elif species in ('mus', 'mus'):
            fname2 = 'Mus+musculus.gff-PTMs.txt'
        elif species in ('myotis', 'ml'):
            fname2 = 'Myotis+lucifugus.gff-PTMs.txt'
        elif species in ('oryzias', 'ol'):
            fname2 = 'Oryzias+latipes.gff-PTMs.txt'
        elif species in ('petromyzon', 'pem'):
            fname2 = 'Petromyzon+marinus.gff-PTMs.txt'
        elif species in ('poecilia', 'pr'):
            fname2 = 'Poecilia+reticulata-PTMs.txt'
        elif species in ('rattus', 'rn'):
            fname2 = 'Rattus+norvegicus.gff-PTMs.txt'
        elif species in ('rhesus', 'rm'):
            fname2 = 'Rhesus+macaque.gff-PTMs.txt'
        elif species in ('sigmodon', 'sh'):
            fname2 = 'Sigmodon+hispidus.gff-PTMs.txt'
        elif species in ('takifugu', 'tr'):
            fname2 = 'Takifugu+rubripes.gff-PTMs.txt'
        elif species in ('xenopus', 'xl'):
            fname2 = 'Xenopus+laevis.gff-PTMs.txt'
        elif species in ('xenopust', 'xt'):
            fname2 = 'Xenopus+tropicalis.gff-PTMs.txt'
        elif species in ('zebra', 'zf'):
            fname2 = 'Zebra+finch.gff-PTMs.txt'
        else:
            raise ValueError('species name does not exits')
        with open(fname2, 'rU') as pm:
            for line in pm:
                line = line.split()
                with open(fname, 'rU') as user:
                    for e in user:
                        e = e.split()
                        if ptm:
                            if e[0] == line[0]:
                                with open('pyntheon-data.txt', 'a') as ac:
                                    ac.write('\t'.join(line) + '\n')
                        elif mutation:
                            if e[0] == line[0] and e[1] == line[1]:
                                with open('pyntheon-mutation-data.txt', 'a'
                                    ) as ac:
                                    ac.write('\t'.join(line) + '\n')
                                    pass
                            elif e[0] == line[0] and e[1] == line[2]:
                                with open('pyntheon-mutation-data.txt', 'a+'
                                    ) as ac:
                                    ac.write('\t'.join(line) + '\n')
                        else:
                            return 'data not found'


def action_parse(action):
    """
    Internal method to parse and validate actions, which are required for some methods
    like toggle_activist_code() and toggle_volunteer_action()
    """
    action = action.capitalize()
    if action not in ('Apply', 'Remove'):
        raise ValueError("Action must be either 'Apply' or 'Remove'")
    return action


def vdiff(v1, v2):
    """Return the vector difference of `v1` and `v2` (`v1-v2`)."""
    x1, y1, z1 = v1
    x2, y2, z2 = v2
    return x1 - x2, y1 - y2, z1 - z2


def calc_shear_vel_mcgann_2015_cpt(cpt):
    """
    Computes the shear wave velocity profile according to :cite:`McGann:2015fd`

    Parameters
    ----------
    cpt: liquepy.field.CPT object

    Returns
    -------
    array_like
        Shear wave velocity profile corresponding to the depths in the CPT.
    """
    return 18.4 * cpt.q_c ** 0.144 * cpt.f_s ** 0.0832 * cpt.depth ** 0.278


def set_compat_six_eight(flag_value):
    """Allow backwards compatibility with calculations bug from Thinc 6.8"""
    global REPRODUCE_BUG
    REPRODUCE_BUG = flag_value


@classmethod
def extract_tags(cls, obj):
    """ Extract tags from the given object

        :param Any obj: Object to use as context
        :return: Tags to add on span
        :rtype: dict
        """
    return dict(uuid=obj.uuid, entrypoint=obj.__class__.path)


@staticmethod
def gui_dict(generic):
    """
        Return a dictionary with functions that will be shown in the
        configuration gui for the calculator node.
        """
    return {}


def edge_distances(peak, feature):
    """
    Return distances between peak and feature edges

    Arguments:
      peak (Peak): peak instance
      feature (Feature): feature instance

    Returns:
      tuple: a pair of distances, the first being the
        smallest distance between an edge of the peak
        region and an edge of the feature region and
        the second being the distance from the same peak
        edge to the opposite feature edge.
        Both distances are zero if the peak is entirely
        contained within the feature (or vice versa).
        If there is partial overlap then the smallest
        distance is returned as zero, the second is
        the amount of the peak that lies outside the
        feature.

    """
    if (peak.start >= feature.start and peak.end <= feature.end or feature.
        start >= peak.start and feature.end <= peak.end):
        return 0, 0
    ds_fs = abs(peak.start - feature.start)
    ds_fe = abs(peak.start - feature.end)
    de_fs = abs(peak.end - feature.start)
    de_fe = abs(peak.end - feature.end)
    if peak.start >= feature.start and peak.start <= feature.end:
        return 0, de_fe
    if peak.end >= feature.start and peak.end <= feature.end:
        return 0, ds_fs
    if ds_fe < de_fs:
        return ds_fe, ds_fs
    else:
        return de_fs, de_fe


def set_node_attributes(G, values, name=None):
    """Sets node attributes from a given value or dictionary of values.

    .. Warning:: The call order of arguments `values` and `name`
        switched between v1.x & v2.x.

    Parameters
    ----------
    G : NetworkX Graph

    values : scalar value, dict-like
        What the node attribute should be set to.  If `values` is
        not a dictionary, then it is treated as a single attribute value
        that is then applied to every node in `G`.  This means that if
        you provide a mutable object, like a list, updates to that object
        will be reflected in the node attribute for every node.
        The attribute name will be `name`.

        If `values` is a dict or a dict of dict, it should be keyed
        by node to either an attribute value or a dict of attribute key/value
        pairs used to update the node's attributes.

    name : string (optional, default=None)
        Name of the node attribute to set if values is a scalar.

    Examples
    --------
    After computing some property of the nodes of a graph, you may want
    to assign a node attribute to store the value of that property for
    each node::

        >>> G = nx.path_graph(3)
        >>> bb = nx.betweenness_centrality(G)
        >>> isinstance(bb, dict)
        True
        >>> nx.set_node_attributes(G, bb, 'betweenness')
        >>> G.nodes[1]['betweenness']
        1.0

    If you provide a list as the second argument, updates to the list
    will be reflected in the node attribute for each node::

        >>> G = nx.path_graph(3)
        >>> labels = []
        >>> nx.set_node_attributes(G, labels, 'labels')
        >>> labels.append('foo')
        >>> G.nodes[0]['labels']
        ['foo']
        >>> G.nodes[1]['labels']
        ['foo']
        >>> G.nodes[2]['labels']
        ['foo']

    If you provide a dictionary of dictionaries as the second argument,
    the outer dictionary is assumed to be keyed by node to an inner
    dictionary of node attributes for that node::

        >>> G = nx.path_graph(3)
        >>> attrs = {0: {'attr1': 20, 'attr2': 'nothing'}, 1: {'attr2': 3}}
        >>> nx.set_node_attributes(G, attrs)
        >>> G.nodes[0]['attr1']
        20
        >>> G.nodes[0]['attr2']
        'nothing'
        >>> G.nodes[1]['attr2']
        3
        >>> G.nodes[2]
        {}

    """
    if name is not None:
        try:
            for n, v in values.items():
                try:
                    G.nodes[n][name] = values[n]
                except KeyError:
                    pass
        except AttributeError:
            for n in G:
                G.nodes[n][name] = values
    else:
        for n, d in values.items():
            try:
                G.nodes[n].update(d)
            except KeyError:
                pass


@staticmethod
def kl(x, y):
    """ The kl(x, y) to use for this arm."""
    raise NotImplementedError(
        'This method kl(x, y) has to be implemented in the class inheriting from Arm.'
        )


@staticmethod
def _get_or_add_xml_to_member(clsdict):
    """
        Add the xml -> enum value mapping to the enumeration class state
        """
    if '_xml_to_member' not in clsdict:
        clsdict['_xml_to_member'] = dict()
    return clsdict['_xml_to_member']


def int_to_bin(number, width=32):
    """
    Convert an integer into its binary representation in a bytes object.
    Width is the amount of bits to generate. If width is larger than the actual
    amount of bits required to represent number in binary, sign-extension is
    used. If it's smaller, the representation is trimmed to width bits.
    Each "bit" is either '\\x00' or '\\x01'. The MSBit is first.

    Examples:

        >>> int_to_bin(19, 5)
        b'\\x01\\x00\\x00\\x01\\x01'
        >>> int_to_bin(19, 8)
        b'\\x00\\x00\\x00\\x01\\x00\\x00\\x01\\x01'
    """
    if number < 0:
        number += 1 << width
    i = width - 1
    bits = bytearray(width)
    while number and i >= 0:
        bits[i] = number & 1
        number >>= 1
        i -= 1
    return bytes(bits)


def draw_rect(canvas, pos, size, line_width, line_color, fill_color=None):
    """
    Draw a rectangle.

    :param canvas: simplegui.Canvas
    :param pos: (int or float, int or float) or [int or float, int or float]
    :param size: (int or float, int or float) or [int or float, int or float]
    :param line_width: int >= 0
    :param line_color: str
    :param fill_color: str
    """
    assert isinstance(pos, (tuple, list)), type(pos)
    assert len(pos) == 2, len(pos)
    assert isinstance(pos[0], (int, float)), type(pos[0])
    assert isinstance(pos[1], (int, float)), type(pos[1])
    assert isinstance(size, (tuple, list)), type(size)
    assert len(size) == 2, len(size)
    assert isinstance(size[0], (int, float)), type(size[0])
    assert isinstance(size[1], (int, float)), type(size[1])
    assert isinstance(line_width, (int, float)), type(line_width)
    assert line_width >= 0, line_width
    assert isinstance(line_color, str), type(str)
    assert fill_color is None or isinstance(fill_color, str), type(str)
    x0 = pos[0]
    y0 = pos[1]
    width = size[0] - 1
    height = size[1] - 1
    canvas.draw_polygon(((x0, y0), (x0 + width, y0), (x0 + width, y0 +
        height), (x0, y0 + height)), line_width, line_color, fill_color)


@staticmethod
def mean(tensor, axis=None):
    """Compute the mean of a tensor, optionally along an axis.

        Parameters
        ----------
        tensor : tensor
        axis : int, optional
            If provided, the mean is computed along this axis.

        Returns
        -------
        out : scalar or tensor
        """
    raise NotImplementedError


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

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


def getappattr(path):
    """Gets attribute from the current_app recursively,
    e.g. getappattr('amqp.get_task_consumer')``."""
    from celery import current_app
    return current_app._rgetattr(path)


@classmethod
def get_subclass(cls, obj):
    """ Get the subclass to use when instantiating a polymorphic object.
            The default implementation looks at ``cls.config_polymorphic``
            to get the name of an attribute.  Subclasses automatically
            register their value for that attribute on creation via their
            ``config_polymorphic_identity`` field.  This process is then
            repeated recursively until None is returned (indicating that the
            current class is the correct one)

            This method can be overridden to allow any method you would like
            to use to select subclasses. It should return either the subclass
            to use or None, if the original class should be used.
        """
    if cls.config_polymorphic is None:
        return
    value = obj.get(cls.config_polymorphic)
    value = cls._subclasses.get(value)
    if value == cls or value is None:
        return None
    sub_value = value.get_subclass(obj)
    if sub_value is None:
        return value
    return sub_value


def _get_default_caseposneg(testcase):
    """Return the default value for caseposneg custom field."""
    return 'negative' if 'negative' in testcase.name.lower() else 'positive'


@staticmethod
def deserialize(content):
    """Default implementation; treat the content as bytes"""
    return content


def bounding_box(rects):
    """
    Get a new Rect which circumscribes all the rects.

    :param list rects
    :return bounding Rect
    :rtype Rect
    """
    top = float('inf')
    left = float('inf')
    bottom = 0
    right = 0
    for rect in rects:
        top_left, bottom_right = rect
        top = min(top, top_left[1])
        left = min(left, top_left[0])
        bottom = max(bottom, bottom_right[1])
        right = max(right, bottom_right[0])
    return (left, top), (right, bottom)


def weighted_sample(bn, e):
    """Sample an event from bn that's consistent with the evidence e;
    return the event and its weight, the likelihood that the event
    accords to the evidence."""
    w = 1
    event = dict(e)
    for node in bn.nodes:
        Xi = node.variable
        if Xi in e:
            w *= node.p(e[Xi], event)
        else:
            event[Xi] = node.sample(event)
    return event, w


@staticmethod
def update_file(source, dest):
    """
		Updates a file with new contents.

		The method opens destination files and append the lines from the source.

		:param str source: Path to file with new contents
		:param str dest: Path to project's (destination) file
		:return: None
		"""
    with open(source, 'r') as source_file, open(dest, 'a') as dest_file:
        dest_file.writelines(source_file.readlines())


def EMA(df, n, price='Close'):
    """
    Exponential Moving Average
    Returns: list of floats = jhta.EMA(df, n, price='Close')
    Source: https://www.fmlabs.com/reference/default.htm?url=ExpMA.htm
    """
    ema_list = []
    for i in range(len(df[price])):
        if i + 1 < n:
            ema = float('NaN')
        else:
            if ema != ema:
                ema = df[price][i]
            k = 2 / (n + 1)
            ema = k * df[price][i] + (1 - k) * ema
        ema_list.append(ema)
    return ema_list


def immutable_dict_2_dict(imm_dict):
    """ Function to convert an Immutable Dictionary to a Mutable one
    Convert multi valued and keys ending with [] to lists
    """
    m_dict = {}
    for key, val in imm_dict.to_dict(flat=False).items():
        if len(val) > 1 or key.endswith('[]'):
            m_dict[key.strip('[]')] = val
        else:
            m_dict[key] = val[0]
    return m_dict


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


def is_path_empty(path):
    """
    `if not path` will not always return if a path is empty
    because of Path objects. Instead do `if is_path_empty(path)`
    """
    return not path or str(path) == '.'


def _create_grouped_output_selection_nrql(output_function, output_config,
    conditions):
    """Create a grouped output selection."""
    function = output_config['function']
    label = output_config.get('label')
    if label:
        label_nrql = f' AS `{label}`'
    else:
        label_nrql = ''
    condition = output_config['condition']
    if condition in conditions:
        condition_nrql = conditions[condition].nrql
    else:
        condition_nrql = condition
    return f'{output_function}({function}, WHERE {condition_nrql}){label_nrql}'


@classmethod
def get_format_string(cls):
    """See RepositoryFormat.get_format_string()."""
    return b'Bazaar-NG Knit Repository Format 1'


def additional_file(remote, local):
    """
    Create step additional file

    :param remote: the remote file of the additional file
    :type remote: string

    :param local: the local file of the additional file
    :type local: string

    :return:
    :rtype map
    """
    return {'remote': remote, 'local': local}


def order():
    """Return an integer that can be used to order a resource.

    The function returns a larger integer each time it is called.  A
    resource can use this to set it's ``bobo_order`` attribute.
    """
    global _order
    _order += 1
    return _order


@classmethod
def guess_instance(cls, value, callback=None):
    """Haphazardly attempt to convert `value` to a `cls` instance.

        If `value` is None or already a `cls` instance, return it. If `value`
        is a number (or looks like one if you squint just right), assume it's
        a database primary key and let SQLAlchemy sort things out. Otherwise,
        fall back to resolving it using `callback` (if specified); this could
        e.g. be a function that looks up instances by name (though that won't
        work if the name begins with a digit). Otherwise, raise Exception.
        """
    if value is None:
        return None
    if isinstance(value, cls):
        return value
    if isinstance(value, int):
        return cls.get(value)
    if isinstance(value, str) and value.isdigit():
        return cls.get(int(value))
    if callback is not None:
        return callback(value)
    raise Exception(
        'given object must be int, long or Instance of %s got %s, no callback provided'
         % (cls, type(value)))


@staticmethod
def from_string(string):
    """
            returns a Python list containing the ordinal values of *string*'s
            chars (should also for unicode objects)
        """
    return map(ord, string)


def parse_and_bind(unused_command):
    """An empty implementation of readline.parse_and_bind."""


@staticmethod
def _bool_translate(thing):
    """Translate the thing into a boolean."""
    return False if str(thing).lower() == 'false' else bool(thing)


def compact_dict(dct):
    """
        Compacts a dct by removing pairs with a None value, meaning 0, None, [], {}, False, etc
    :param dct:
    :return: The filtered dict
    """
    return dict(filter(lambda key_value: key_value[1], dct.items()))


def formula_2002(foyer_fiscal, period, parameters):
    """
        Crédit d'impôt pour dépense d'acquisition ou de transformation d'un véhicule GPL ou mixte
        2002-2007
        """
    f7up = foyer_fiscal('f7up', period)
    f7uq = foyer_fiscal('f7uq', period)
    acqgpl = parameters(period).impot_revenu.credits_impot.acqgpl
    return f7up * acqgpl.mont_up + f7uq * acqgpl.mont_uq


def pop_dict_last_item(dictionary):
    """
        Until python 3.5 the popitem() has has a bug where it does not accepts the last=False argument
        https://bugs.python.org/issue24394 TypeError: popitem() takes no keyword arguments, then,
        automatically detect which one we have here:
        https://docs.python.org/3/library/collections.html#collections.OrderedDict.popitem
    """
    dictionary.popitem(last=True)


def printProgressBar(iteration, total, prefix='', suffix='', decimals=1,
    length=100, fill='█'):
    """
        Call in a loop to create terminal progress bar
        @params:
            iteration   - Required  : current iteration (Int)
            total       - Required  : total iterations (Int)
            prefix      - Optional  : prefix string (Str)
            suffix      - Optional  : suffix string (Str)
            decimals    - Optional  : positive number of decimals in percent complete (Int)
            length      - Optional  : character length of bar (Int)
            fill        - Optional  : bar fill character (Str)
        """
    percent = ('{0:.' + str(decimals) + 'f}').format(100 * (iteration /
        float(total)))
    filledLength = int(length * iteration // total)
    bar = fill * filledLength + '-' * (length - filledLength)
    print('\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix), end='\r')
    if iteration == total:
        print()


def get_single(x, name):
    """Make sure only a single element is used
    """
    if isinstance(x, list):
        if len(x) == 1:
            return x[0]
        else:
            raise ValueError('Only a single {} can be used with --singularity'
                .format(name))
    else:
        return x


def serialize_dt(value):
    """Serializes parameter if it is datetime."""
    return value.isoformat() if hasattr(value, 'isoformat') else value


@staticmethod
def get_or_new_from_json_dict_with_types(data, cls_map, type_key='type'):
    """Get `cls` object w/ deserialization from json by using type key hint if needed.

        If data is instance of one of cls, return data.
        Else if data is instance of dict, create instance from dict.
        Else, return None.

        :param data:
        :param cls_map:
        :param type_key:
        :rtype: object
        :return:
        """
    if isinstance(data, tuple(cls_map.values())):
        return data
    elif isinstance(data, dict):
        type_val = data[type_key]
        if type_val in cls_map:
            return cls_map[type_val].new_from_json_dict(data)
    return None


def do_use_container(**kwargs):
    """
    Decide whether to use a container or not.

    :param kwargs: dictionary of key-word arguments.
    :return: True if function has decided that a container should be used, False otherwise (boolean).
    """
    use_container = False
    job = kwargs.get('job', False)
    copytool = kwargs.get('copytool', False)
    if job:
        if job.is_analysis() and job.imagename:
            use_container = False
        elif not (job.platform or job.alrbuserplatform):
            use_container = False
        else:
            queuedata = job.infosys.queuedata
            container_name = queuedata.container_type.get('pilot')
            if container_name == 'singularity':
                use_container = True
    elif copytool:
        use_container = True
    return use_container


@staticmethod
def _handle_selection(selection):
    """
        Dummy placeholder for returning selection from
        ``android.app.Activity.onActivityResult()``.

        .. versionadded:: 1.4.0
        """
    return selection


def with_metaclass(meta, *bases):
    """Create a base class with a metaclass."""
    return meta('NewBase', bases, {})


def life(args):
    """
    this is my First Python Package.
    this is my life log
    """
    res = False
    if type(args) == int:
        sum = 0
        for i in range(args + 1):
            sum += i
        res = True
    else:
        sum = '{0} 不是整数，无法计算'.format(args)
    return res, sum


def count_to_str(count, word):
    """
    Merge count and word with (or without) plural ending

    :type count: int
    :type word: str

    :rtype: str
    """
    return ' '.join((str(count), word + 's' if count > 1 else word))


def __rpow__(cls, left_other):
    """The expression `n**token` for an int `n` is "n or more occurrences of"
        `token`."""
    return cls.prod_rule_funs['nOrMore'](left_other, cls)


def iterkeys():
    """iterate over keys; equivalent to __iter__"""


@classmethod
def run(cls, excl_fpath, res_fpath, dset, save_flag=True,
    distance_upper_bound=0.03, map_chunk=2560, max_workers=None):
    """Run parallel mapping and save to h5 file.

        Parameters
        ----------
        excl_fpath : str
            Filepath to exclusions h5 (tech layer). dset will be
            created in excl_fpath.
        res_fpath : str
            Filepath to .h5 resource file that we're mapping to.
        dset : str
            Dataset name in excl_fpath to save mapping results to.
        save_flag : bool
            Flag to write techmap to excl_fpath.
        kwargs : dict
            Keyword args to initialize the TechMapping object.

        Returns
        -------
        lats : np.ndarray
            2D un-projected latitude array of tech exclusion points.
            0's if no res point found. Shape is equal to exclusions shape.
        lons : np.ndarray
            2D un-projected longitude array of tech exclusion points.
            0's if no res point found. Shape is equal to exclusions shape.
        ind_all : np.ndarray
            Index values of the NN resource point. -1 if no res point found.
            2D integer array with shape equal to the exclusions extent shape.
        """
    kwargs = {'distance_upper_bound': distance_upper_bound, 'map_chunk':
        map_chunk, 'max_workers': max_workers}
    with cls(excl_fpath, res_fpath, dset, **kwargs) as mapper:
        lats, lons, ind = mapper._parallel_resource_map()
        distance_upper_bound = mapper._distance_upper_bound
    if save_flag:
        mapper.save_tech_map(lats, lons, ind, excl_fpath, res_fpath, dset,
            distance_upper_bound)
    return lats, lons, ind


def graph_select(location: float=(0.0, 0.0), extend: bool=False):
    """Select graph curves

    :param location: Location, Mouse location to select nearest entity
    :type location: float
    :param extend: Extend, Extend selection rather than clearing the existing selection
    :type extend: bool
    """
    pass


def lru(loads):
    """Always pick the front of the line.

    The content of `loads` is ignored.

    Assumes LRU ordering of loads, with oldest first.
    """
    return 0


@classmethod
def put(cls, value, size):
    """Write test memory."""
    cls.ram.put(cls.pos, value, size)
    for i in range(size // 16):
        i = i
        cls.pos = (cls.pos + 1) % 2 ** 16
        cls.max_pos = max(cls.max_pos, cls.pos)


def filter_soup(soup, mode='html', **kwargs):
    """Turn a multicode block into the correct syntax for minitabs, but only
       in the HTML version."""
    if mode != 'html':
        return
    multicodes = soup.find_all(class_='multicode')
    index1 = 0
    for cb_area in multicodes:
        cb_area['id'] = 'code-%d' % index1
        codetabs_ul = soup.new_tag('ul')
        codetabs_ul['class'] = 'codetabs'
        cb_area.insert(0, codetabs_ul)
        pres = cb_area.find_all('pre')
        index2 = 0
        for pre in pres:
            linkid = 'code-%d-%d' % (index1, index2)
            code_sample_wrapper = soup.new_tag('div', id=linkid)
            code_sample_wrapper['class'] = 'code_sample'
            code_sample_wrapper['style'] = 'position: static;'
            pre.wrap(code_sample_wrapper)
            linkback = soup.new_tag('a', href='#%s' % linkid)
            linkback_li = soup.new_tag('li')
            linkback_li.append(linkback)
            codetabs_ul.append(linkback_li)
            prev_p = code_sample_wrapper.find_previous_sibling('p')
            try:
                label = ''.join(prev_p.em.strings)
            except AttributeError:
                label = 'Code Sample %d-%d' % (index1, index2)
            linkback.string = label
            prev_p.decompose()
            index2 += 1
        index1 += 1


def ensure_ref_position_is_valid(ref_position, num_alts, param_title):
    """
    Ensures that `ref_position` is None or an integer that is in the interval
    `[0, num_alts - 1]`. If None, ensures that intercepts are not the
    parameters being estimated. Raises a helpful ValueError if otherwise.

    Parameters
    ----------
    ref_position : int.
        An integer denoting the position in an array of parameters that will
        be constrained for identification purposes.
    num_alts : int.
        An integer denoting the total number of alternatives in one's universal
        choice set.
    param_title : {'intercept_names', 'shape_names'}.
        String denoting the name of the parameters that are being estimated,
        with a constraint for identification. E.g. 'intercept_names'.

    Returns
    -------
    None.
    """
    assert param_title in ['intercept_names', 'shape_names']
    try:
        assert ref_position is None or isinstance(ref_position, int)
    except AssertionError:
        msg = 'ref_position for {} must be an int or None.'
        raise TypeError(msg.format(param_title))
    if param_title == 'intercept_names':
        try:
            assert ref_position is not None
        except AssertionError:
            raise ValueError('At least one intercept should be constrained.')
    try:
        if ref_position is not None:
            assert ref_position >= 0 and ref_position <= num_alts - 1
    except AssertionError:
        msg = 'ref_position must be between 0 and num_alts - 1.'
        raise ValueError(msg)
    return None


def stability_selection_to_threshold(stability_selection, n_boots):
    """Converts user inputted stability selection to an array of
    thresholds. These thresholds correspond to the number of bootstraps
    that a feature must appear in to guarantee placement in the selection
    profile.

    Parameters
    ----------
    stability_selection : int, float, or array-like
        If int, treated as the number of bootstraps that a feature must
        appear in to guarantee placement in selection profile. If float,
        must be between 0 and 1, and is instead the proportion of
        bootstraps.

    n_boots: int
        The number of bootstraps that will be used for selection
    """
    if isinstance(stability_selection, float):
        selection_threshold = int(stability_selection * n_boots)
    elif isinstance(stability_selection, int):
        selection_threshold = stability_selection
    else:
        raise ValueError('Stability selection must be a valid float or int.')
    if not (selection_threshold <= n_boots and selection_threshold >= 1):
        raise ValueError(
            'Stability selection thresholds must be within the correct bounds.'
            )
    return selection_threshold


def SSMT2text(Opr):
    """From superspace group matrix/translation operator returns text version"""
    XYZS = 'x', 'y', 'z', 't'
    TRA = ('   ', 'ERR', '1/6', '1/4', '1/3', 'ERR', '1/2', 'ERR', '2/3',
        '3/4', '5/6', 'ERR')
    Fld = ''
    M, T = Opr
    for j in range(4):
        IJ = ''
        for k in range(4):
            txt = str(int(round(M[j][k])))
            txt = txt.replace('1', XYZS[k]).replace('0', '')
            if '2' in txt:
                txt += XYZS[k]
            if IJ and M[j][k] > 0:
                IJ += '+' + txt
            else:
                IJ += txt
        IK = int(round(T[j] * 12)) % 12
        if IK:
            if not IJ:
                break
            if IJ[0] == '-':
                Fld += (TRA[IK] + IJ).rjust(8)
            else:
                Fld += (TRA[IK] + '+' + IJ).rjust(8)
        else:
            Fld += IJ.rjust(8)
        if j != 3:
            Fld += ', '
    return Fld


def _filter_str(file_ext='') ->str:
    """ Return a file dialog filter string based on a file extension. It should not include the dot.
        If <file_ext> is empty, return a filter string matching any file. """
    if not file_ext:
        return 'All files (*.*)'
    return f'{file_ext.upper()} files (*.{file_ext})'


def get_description_value(obj):
    """
    Returns object description from LLDB value.

    :param lldb.SBValue obj: LLDB value object.
    :return: Object description from LLDB value.
    :rtype: str | None
    """
    desc = None if obj is None else obj.GetObjectDescription()
    if desc == '<nil>':
        desc = None
    return desc


@staticmethod
def _mutate(gene, position):
    """
        This function does the actual mutation of the gene at a specific
        position.

        """
    if gene[position] == '0':
        gene = ''.join([gene[:position], '1', gene[position + 1:]])
    else:
        gene = ''.join([gene[:position], '0', gene[position + 1:]])
    return gene


def getValues(name):
    """
        Get the values associated with the given header name.

        If the given name is L{bytes}, the value will be returned as the raw
        header L{bytes}.

        If the given name is L{Text}, the name will be encoded as ISO-8859-1
        and the value will be returned as text, by decoding the raw header
        value bytes with ISO-8859-1.

        @param name: The name of the header to look for.

        @return: The values of the header with the given name.
        """


def session_ended(method):
    """Apply this decorator to a method of class :class:`.HermesSnipsComponent`
    to register it as a callback to be triggered when the dialogue manager ends
    a session.
    """
    method.session_ended = True
    return method


@classmethod
def to_string(cls, u):
    """
        Convert a unit object to a string.
        """
    raise NotImplementedError(f'Can not output in {cls.__name__} format')


def get_share_counter_good():
    """Return the number of distinct good shares that were found. For
        mutable files, this counts shares for the 'best' version."""


def close_window():
    """Closes the pythonGraph window.

    An error is raised if the graphics window is not open.

    .. code-block:: python

        pythonGraph.close_window()

    """
    quit()


def report_copy():
    """Copy selected reports to Clipboard

    """
    pass


@classmethod
def get_by_deployable_id(cls, context, deployable_id):
    """Get an attribute by deployable_id"""
    db_attr = cls.dbapi.attribute_get_by_deployable_id(context, deployable_id)
    return cls._from_db_object_list(db_attr, context)


@staticmethod
def do_nothing_attr_stub(context, attr_name, param, node):
    """ Just stub for do nothing on handling attribute attempt """


def step(f):
    """
    The step decorator. Makes a method a step in the workflow.
    """
    f.is_step = True
    f.decorators = []
    try:
        f.name = f.__name__
    except:
        f.name = f.__func__.func_name
    return f


@staticmethod
def _initialise_states(dict_desc, dict_param, kwa):
    """
        This function initialises the model states before starting the simulations.
        If a warm-up run is used, this initialisation happens before the start of the warm-up run.
        If no warm-up is used, this initialisation happens before the start of the actual simulation run.
        """
    area_m2 = dict_desc['area']
    my_dict = dict()
    try:
        my_dict.update({'r_s_v_h2o': kwa['aar'] * kwa['r-o_ratio'] / 1000 *
            area_m2 / 8766 * dict_param['r_p_k_h2o']})
    except KeyError:
        my_dict.update({'r_s_v_h2o': 0.0})
    return my_dict


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

        :param TeamMergeRequestExpiredType val:
        :rtype: EventType
        """
    return cls('team_merge_request_expired', val)


@staticmethod
def clean_penn_tree(penn_tree):
    """ Clean from the tree all knows problems.

        :param penn_tree: the plain text tree

        :return: cleaned tree
        """
    penn_tree = penn_tree.strip()
    return penn_tree


def lf(*args, **kwargs):
    """
    shortcut of list(filter(*args, **kwags))

    :param args:
    :param kwargs:
    :return:
    """
    return list(filter(*args, **kwargs))


def bits_to_bytes(a, reverse=True):
    """
    Function that converts bit string into a given number of bytes.

    :param str a: Bytes to convert.
    :param bool reverse: Whether or not to reverse the byte list.

    :return: List of bytes.
    """
    bytelist = []
    if len(a) % 8 != 0:
        padding = 8 - len(a) % 8
        a = '0' * padding + a
    for i in range(len(a) // 8):
        bytelist.append(int(a[8 * i:8 * (i + 1)], 2))
    if reverse:
        bytelist.reverse()
    return bytelist


def deg2pix(degrees, ppd):
    """Return degrees converted to pixels at ppd pixels/degree."""
    return int(degrees * ppd)


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

        :param NoPasswordLinkGenCreateReportDetails val:
        :rtype: EventDetails
        """
    return cls('no_password_link_gen_create_report_details', val)


@classmethod
def configure(cls, profile_name, config_items=None):
    """
        When given a profile name and dict of config items will write the
        config file to disk.  If a `profile_name` is given that already exists
        on the profile then the `profile_name` on the profile will be
        completely replaced with the values from config_items
        :param profile_name: The name of the profile to write
        :param config_items: A dict of items that should be written to the
        config
        """
    if config_items is None:
        config_items = {}
    with open(cls.config_path(), 'a') as cfg:
        config_string = f'[{profile_name}]\n'
        for config_key, config_value in config_items.items():
            config_string += f'{config_key}={config_value}\n'
        cfg.write(config_string)


def common_segment_count(path, value):
    """Return the number of path segments common to both"""
    i = 0
    if len(path) <= len(value):
        for x1, x2 in zip(path, value):
            if x1 == x2:
                i += 1
            else:
                return 0
    return i


def resource_listdir(resource_name):
    """List of resource names in the directory (like ``os.listdir()``)"""


@staticmethod
def evaluate(x, z):
    """One dimensional RedshiftScaleFactor model function"""
    return (1 + z) * x


def get_schema():
    """Schema structure of this resource

    :return: schema dictionary
    :rtype: dict
    """
    return {'allow_unknown': True, 'auth_field': '_user', 'item_methods': [
        'GET', 'PATCH', 'PUT', 'DELETE'], 'schema': {'schema_version': {
        'type': 'integer', 'default': 1}, 'host': {'schema_version': 1,
        'type': 'string'}, '_user': {'schema_version': 1, 'type':
        'objectid', 'data_relation': {'resource': 'user', 'embeddable':
        True}}}, 'schema_deleted': {}}


def iterate_path_definitions(paths):
    """Iterate over all `PathDefinition` instances in `paths`

    :param dict[str, dict[str, flask_rebar.rebar.PathDefinition]] paths:
    :return Iterator[PathDefinition]
    """
    for methods in paths.values():
        for definition in methods.values():
            yield definition


def ScenarioStep(Stage, Step, Description):
    """
	Return a comment string for TBGen scenario describing a new Step.
	"""
    return (
        """
GPIO COMMENT  "---------------------------------------------"
GPIO COMMENT  "# {Stage}.{Step} {Desc}"
GPIO COMMENT  "---------------------------------------------" """
        .format(Stage=Stage, Step=Step, Desc=Description.replace('\n', ' / ')))


def resolve_absolute_path(filename):
    """Fetch filename from absolute path"""
    return filename.split('/')[-1]


def condition_4i(eptm):
    """
    Return an index over the faces violating condition 4 i in Okuda et al 2013,
    that is edges (from the same face) sharing two vertices simultaneously.
    """
    num_srces = eptm.edge_df.groupby('face')['srce'].apply(lambda s: len(
        set(s)))
    num_sides = eptm.face_df['num_sides']
    return eptm.face_df[(num_srces != num_sides) | (num_sides < 3)].index


@staticmethod
def strtobytes(source):
    """Convert string to bytes tuple used for all crypto methods.

        Args:
            source: String for conversion.

        Returns:
            Tuple containing bytes from converted source string.
        """
    return tuple(bytearray(source, 'utf-8'))


def err(error):
    """
        Utility function for returning serializable json payload.
    """
    return {error.__name__: error.todict()}


@classmethod
def flushIndexes(cls):
    """Drops all the indexes attached to the object's class. Ex
		Transcript.flushIndexes()"""
    return cls._wrapped_class.flushIndexes()


def get_disabled_plugins():
    """Returns a list of plugins that are disabled in the config."""


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


@staticmethod
def p_daq_config_type(p):
    """daq_config_type : STATIC
                           | DYNAMIC"""
    p[0] = p[1]


def traverse_using(iterator, obj, visitors):
    """visit the given expression structure using the given iterator of
    objects.

    :func:`.visitors.traverse_using` is usually called internally as the result
    of the :func:`.visitors.traverse` or :func:`.visitors.traverse_depthfirst`
    functions.

    :param iterator: an iterable or sequence which will yield
     :class:`_expression.ClauseElement`
     structures; the iterator is assumed to be the
     product of the :func:`.visitors.iterate` or
     :func:`.visitors.iterate_depthfirst` functions.

    :param obj: the :class:`_expression.ClauseElement`
     that was used as the target of the
     :func:`.iterate` or :func:`.iterate_depthfirst` function.

    :param visitors: dictionary of visit functions.  See :func:`.traverse`
     for details on this dictionary.

    .. seealso::

        :func:`.traverse`

        :func:`.traverse_depthfirst`

    """
    for target in iterator:
        meth = visitors.get(target.__visit_name__, None)
        if meth:
            meth(target)
    return obj


@staticmethod
def __initialize_variables(vars_dict: dict) ->dict:
    """
        Ensure the proper default values are configured for each type of variable that may be present in the skillet

        :param vars_dict: Skillet 'variables' stanza
        :return: variables stanza with default values correctly parsed
        """
    for variable in vars_dict:
        default = variable.get('default', '')
        type_hint = variable.get('type_hint', 'text')
        if type_hint == 'dropdown' and 'dd_list' in variable:
            for item in variable.get('dd_list', []):
                if 'key' in item and 'value' in item:
                    if default == item['key'] and default != item['value']:
                        variable['default'] = item['value']
        elif type_hint == 'radio' and 'rad_list' in variable:
            rad_list = variable['rad_list']
            for item in rad_list:
                if 'key' in item and 'value' in item:
                    if default == item['key'] and default != item['value']:
                        variable['default'] = item['value']
        elif type_hint == 'checkbox' and 'cbx_list' in variable:
            cbx_list = variable['cbx_list']
            for item in cbx_list:
                if 'key' in item and 'value' in item:
                    if default == item['key'] and default != item['value']:
                        variable['default'] = item['value']
    return vars_dict


@classmethod
def split(cls, elem, tag, **namespaces):
    """Split the given elem at tag, returning a list of elements with the same attributes.
        Use XML.xpath() syntax for the tag when it has a namespace; the namespace prefix
        must exist in the **namespaces
        """


def rect_areas(rects):
    """Return an np.array of the areas of the rectangles

        :param rects: a list of rectangles, each specified as (x, y, w, h)
        :type rects: list
        :return: an numpy array of corresponding areas
        :rtype: :class:`numpy.ndarray`
        """
    w = rects[:, (2)]
    h = rects[:, (3)]
    return w * h


def get_sort_order(qdict, default, allowed_values=None):
    """Return a sort order from a querydict object

    :param QueryDict qdict: the object to analyse
    :param string default: the default sort order if no one is found
    :param list allowed_values: an optional list of allowed values
    :return: a 2uple of strings
    """
    sort_order = qdict.get('sort_order', default)
    if sort_order.startswith('-'):
        sort_dir = '-'
        sort_order = sort_order[1:]
    else:
        sort_dir = ''
    if allowed_values is not None and sort_order not in allowed_values:
        return default, ''
    return sort_order, sort_dir


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 field_to_dynamo_type(field):
    """ Returns the dynamo type character given the field. """
    raise NotImplementedError('Child class must implement field_to_dynamo_type'
        )


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,


def _set_from_address(web3, transaction_options):
    """set the from address in the transaction options

    transact() will not fill the from field by asking the node
    we need to do that ourselves
    """
    if 'from' not in transaction_options:
        transaction_options['from'
            ] = web3.eth.defaultAccount or web3.eth.accounts[0]


def channels_group(name: str='NewGroup'):
    """Add selected F-Curves to a new group

    :param name: Name, Name of newly created group
    :type name: str
    """
    pass


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


def getBroadcastAllowed():
    """
        Checks if broadcast is currently allowed on this port.

        @return: Whether this port may broadcast.
        @rtype: L{bool}
        """


def _mix_colors(c1, c2, v):
    """Mixes two colors according to v in the 0-1 range
    where 0 only r1 and 1 only r2 and e.g. 0.5 is exactly in between"""
    r1, g1, b1 = c1
    r2, g2, b2 = c2
    return int(r2 * v + r1 * (1 - v)), int(g2 * v + g1 * (1 - v)), int(b2 *
        v + b1 * (1 - v))


@classmethod
def _test_scheme(cls, scheme):
    """
            Test if a scheme is valide or raise BadScheme

            :param bytes scheme: A scheme
            :raises BadScheme: if ``scheme`` is not a valid scheme
        """
    if scheme not in cls.schemes_salt and scheme not in cls.schemes_nosalt:
        cls._raise_bad_scheme(scheme, cls.schemes_salt | cls.schemes_nosalt,
            'The scheme %r is not valid. Valide schemes are %s.')


def get_programming_language(repo_info):
    """Return programming language used for repository"""
    try:
        return repo_info.find('span', {'itemprop': 'programmingLanguage'}
            ).text.strip()
    except AttributeError:
        return


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


@classmethod
def new(cls, poly, func, auto=True):
    """Construct new ``RootSum`` instance."""
    rational = cls._is_func_rational(poly, func)
    if not rational or not auto:
        return cls._new(poly, func, auto)
    else:
        return cls._rational_case(poly, func)


def csv_format(s):
    """
    cleans syntax problems for csv output
  """
    s = s.replace('"', "'")
    s = s.replace('\n', ' ')
    s = s.replace('\x00D', '')
    return '"%s"' % s


def classname(obj):
    """Returns the name of an objects class"""
    return obj.__class__.__name__


def AR_8(dul):
    """Association release AR-8.

    On receiving association release request while local is requesting release
    then issue release collision indication

    State-event triggers: Sta7 + Evt12

    References
    ----------
    1. DICOM Standard 2015b, PS3.8, Table 9-7, "Associate Establishment
       Related Actions"

    Parameters
    ----------
    dul : pynetdicom.dul.DULServiceProvider
        The DICOM Upper Layer Service instance for the local AE

    Returns
    -------
    str
        Either Sta9 or Sta10, the next state of the state machine
    """
    dul.to_user_queue.put(dul.primitive)
    if dul.assoc.is_requestor:
        return 'Sta9'
    return 'Sta10'


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 text_nodes_acl_xml(root_xml_content):
    """Receive XML object and return list of lists of strings"""
    text_nodes = []
    for sentence in root_xml_content.iter('S'):
        sentence_text = list(sentence.itertext())
        text_nodes.append(sentence_text)
    return text_nodes


def estimate():
    """Estimate running time of upgrade in seconds (optional)."""
    return 1


def _default_keep_signal(sig):
    """
    If ``plots`` is not specified in ``metadata``, this function determines
    which channels are plotted by default.
    """
    return not sig.name.startswith('Analog Input #') and sig.name != 'Clock'


def _seek_generator(f):
    """Yields seek position for each line.

    Args:
        f (file): the file object

    """
    yield 0
    for line in f:
        yield f.tell()


@staticmethod
def format_recommendations(msg, recommendations):
    """Add recommendations to the given message.

        The recommendation string looks like:
            <msg> Did you mean:
            <recommendations[0]>
            <recommendations[1]>
            <recommendations[2]>
        """
    if recommendations:
        msg += ' Did you mean:'
        for rec in recommendations:
            msg += '\n    %s' % rec
    return msg


def det(A=None, name=None, attr=None, out=None, **kwargs):
    """Compute the determinant of a matrix.
    Input is a tensor *A* of dimension *n >= 2*.

    If *n=2*, *A* is a square matrix. We compute:

      *out* = *det(A)*

    If *n>2*, *det* is performed separately on the trailing two dimensions
    for all inputs (batch mode).

    .. note:: The operator supports float32 and float64 data types only.
    .. note:: There is no gradient backwarded when A is non-invertible (which is
              equivalent to det(A) = 0) because zero is rarely hit upon in float
              point computation and the Jacobi's formula on determinant gradient
              is not computationally efficient when A is non-invertible.

    Examples::

       Single matrix determinant
       A = [[1., 4.], [2., 3.]]
       det(A) = [-5.]

       Batch matrix determinant
       A = [[[1., 4.], [2., 3.]],
            [[2., 3.], [1., 4.]]]
       det(A) = [-5., 5.]

    Defined in src/operator/tensor/la_op.cc:L973

    Parameters
    ----------
    A : Symbol
        Tensor of square matrix

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

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


def extend_index_list(lst, repeats):
    """Extend an integer index list by repeating some number of times such that the extra
    indices added are new and follow the same ordering as the existing elements.

    Parameters
    ----------
    lst : list of int
    repeats : int

    Returns
    -------
    new_idx : list of int
        Returned list has length `len(lst) * repeats`.

    Examples
    --------
    >>> extend_index_list([0, 1, 2], 2)
    [0, 1, 2, 3, 4, 5]

    >>> extend_index_list([0, 0, 1, 1], 3)
    [0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5]

    >>> extend_index_list([4, 1, 2], 2)
    [4, 1, 2, 8, 5, 6]

    """
    new_idx = []
    for i in lst:
        if i < 0:
            raise ValueError('List elements must be positive or zero.')
        new_idx.append(i)
    for _ in range(repeats - 1):
        next_avail_idx = max(new_idx) + 1
        new_idx.extend([(next_avail_idx + i - min(lst)) for i in lst])
    return new_idx


def other():
    """
    Note to contributors:
        Other algorithms for masking transient noise must be named with the
        author or method name. If already published, the full citation must be
        provided. Please, add "unpub." otherwise. E.g: Smith et al. (unpub.)

        Please, check DESIGN.md to adhere to our coding style.
    """


@classmethod
def get_column_range(cls, height, width, start_index=0):
    """get_column_range
        Gets the range for the table to be used when writing the excel file.

        Height corresponds to the number of rows in the table
        Width refers to the number of columns in the table
        start_index is the column to start at, which is A

        the initial and final letters are found by index a string of letters
        of the alphabet.

        Example:
            height = 7, width = 3, start_index = 0

            initial column letter will be A
            initial column cell will be 1

            final column letter will be C
            final column cell will be 7

            resulting pair for column range is A1:C7

        :param height:
        :param width:
        :param start_index:
        :return: Initial column letter, initial column cell index, final letter, final index
        """
    letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    if width > 26:
        raise ValueError('width can not exceed 26 columns. [VALUE {}]'.
            format(str(width)))
    init_letter = letters[start_index]
    init_pos = init_letter + str(start_index + 1)
    final_letter = letters[width - 1]
    final_pos = final_letter + str(height)
    return init_letter, init_pos, final_letter, final_pos


def zap_all():
    """Clear all data out of the database."""


@classmethod
def _get_notification_exchanges(cls):
    """Return a list of oslo exchanges this plugin cares about"""


def test_string_content(string):
    """
    Detects if string is integer, float or string.

    Parameters
    ----------
    string : string
        An input string to be tested.

    Returns
    -------
    string
        A string with value 'int' if input is an integer,
        'float' if the input is a float and 'string' if it
        is just a regular string.

    """
    try:
        float(string)
        return 'int' if string.count('.'
            ) == 0 and 'e' not in string and 'E' not in string else 'float'
    except ValueError:
        return 'string'


def keyconfig_preset_add(name: str='', remove_active: bool=False):
    """Add or remove a Key-config Preset

    :param name: Name, Name of the preset, used to make the path name
    :type name: str
    :param remove_active: remove_active
    :type remove_active: bool
    """
    pass


def _as_list(arr):
    """Make sure input is a list of mxnet NDArray"""
    if not isinstance(arr, (list, tuple)):
        return [arr]
    return arr


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

        :param GroupDescriptionUpdatedDetails val:
        :rtype: EventDetails
        """
    return cls('group_description_updated_details', val)


def bresenham(coords_a, coords_b):
    """
    Given the start and end coordinates, return all the coordinates lying
    on the line formed by these coordinates, based on Bresenham's algorithm.
    http://en.wikipedia.org/wiki/Bresenham's_line_algorithm#Simplification
    """
    line = []
    x0, y0 = coords_a
    x1, y1 = coords_b
    dx = abs(x1 - x0)
    dy = abs(y1 - y0)
    sx = 1 if x0 < x1 else -1
    sy = 1 if y0 < y1 else -1
    err = dx - dy
    while True:
        line += [[x0, y0]]
        if x0 == x1 and y0 == y1:
            break
        e2 = err * 2
        if e2 > -dy:
            err = err - dy
            x0 = x0 + sx
        if e2 < dx:
            err = err + dx
            y0 = y0 + sy
    return line


def key(*args):
    """
    join the arguments in the format of donkey

    Arguments
    ---------
    args: list of string

    Examples
    --------
    >>>key( 'a', 'b', 'c' )
    'a__b__c'
    """
    return '__'.join(args)


def format_uptime(uptime_in_seconds):
    """Format number of seconds into human-readable string.

    :param uptime_in_seconds: The server uptime in seconds.
    :returns: A human-readable string representing the uptime.

    >>> uptime = format_uptime('56892')
    >>> print(uptime)
    15 hours 48 min 12 sec
    """
    m, s = divmod(int(uptime_in_seconds), 60)
    h, m = divmod(m, 60)
    d, h = divmod(h, 24)
    uptime_values = []
    for value, unit in ((d, 'days'), (h, 'hours'), (m, 'min'), (s, 'sec')):
        if value == 0 and not uptime_values:
            continue
        elif value == 1 and unit.endswith('s'):
            unit = unit[:-1]
        uptime_values.append('{0} {1}'.format(value, unit))
    uptime = ' '.join(uptime_values)
    return uptime


@classmethod
def validate(cls, value: str) ->None:
    """Value validation method.

    Valid values are ``OPEN`` and ``CLOSED``.

    Args:
      value (str): The value to validate.

    Raises:
      ValueError: Raises ValueError if an invalid value has been specified.
    """
    super().validate(value)
    if value not in ['OPEN', 'CLOSED']:
        raise ValueError()


def allPossibleCombinations(barcode):
    """ returns a list of all possible combinations of a barcode with one mismatch"""
    combinations = list()
    for i in range(len(barcode)):
        newbarcode = list(barcode)
        newbarcode[i] = 'N'
        combinations.append(''.join(newbarcode))
    return combinations


def definesReturn(dataType: 'TType') ->'TType':
    """
    A simple decorator to set __pure__ equal to __return__.
    If used with definesBind, definesReturn must be applied
    first (i.e. be a more inner decorator).
    """
    dataType.__pure__ = dataType.__return__
    return dataType


def download_blob(cursor, oid, tid, filename):
    """Download a blob into a file.

        Returns the size of the blob file in bytes.
        """


def vertex_parent_set():
    """Parent selected objects to the selected vertices

    """
    pass


def _loop_once():
    """Run the main loop once
    """
    pass


def RF(val):
    """NumberReferences"""
    return val


def ghost_curves_create():
    """Create snapshot (Ghosts) of selected F-Curves as background aid for active Graph Editor

    """
    pass


def tf_type_string(tf_type: str) ->str:
    """
  Convert tf.<dtype> to (str) striping tf. in the process.
  """
    return str(tf_type).replace("<dtype: '", '').replace("'>", '')


def deltaFrames(t1, t2, frameRate):
    """Returns the number of frames between t1 and t2
    positive if t1<=t2, negative otherwise"""
    if t1 > t2:
        return -(t1 - t2).seconds * frameRate
    else:
        return (t2 - t1).seconds * frameRate


def get_model_pk_attr_name(model_class):
    """
    Get the primary key attribute name from a Declarative model class

    :param Type[DeclarativeMeta] model_class: a Declarative class

    :return: str: a Column name
    """
    primary_key_columns = list(filter(lambda attr_col: attr_col[1].
        primary_key, model_class.__mapper__.columns.items()))
    if len(primary_key_columns) == 1:
        return primary_key_columns.pop()[0]
    elif len(primary_key_columns) < 1:
        raise RuntimeError(f"Couldn't find attribute for {model_class}")
    else:
        raise RuntimeError('Multiple primary keys still not supported')


def removePOS(sentence):
    """
    Removes the part of speech from a string sentence.
    """
    cleansentence = []
    for word in sentence.split():
        cleansentence.append(word.split('/')[0])
    return ' '.join(cleansentence)


def phasename(phaseID):
    """
    Take a phase ID and return the name of the phase.

    Parameters
    ------------
    phaseID : :class:`str`
        ID for the particular phase (e.g. 'olivine_0')

    Returns
    --------
    :class:`str`
        Name of the phase.
    """
    if phaseID.find('_') > 0:
        n = phaseID[:phaseID.find('_')]
    else:
        n = phaseID
    return n


def select(extend: bool=False, location: float=(0.0, 0.0)):
    """Select tracking markers

    :param extend: Extend, Extend selection rather than clearing the existing selection
    :type extend: bool
    :param location: Location, Mouse location in normalized coordinates, 0.0 to 1.0 is within the image bounds
    :type location: float
    """
    pass


def reverse_force_list(data):
    """Unwrap data from list if its length is == 1."""
    if isinstance(data, (list, tuple, set)) and len(data) == 1:
        return data[0]
    return data


@classmethod
def from_string(cls, loc, **kws):
    """ Create an interval from a chrx:start-end style string """
    toks = loc.split(':')
    chrom = toks[0]
    start, end = map(int, toks[1].split('-'))
    if len(toks) == 3:
        try:
            strand = int(toks[2])
        except ValueError:
            strand = toks[2]
            if strand == '+':
                strand = 1
            elif strand == '-':
                strand = -1
            elif strand == '':
                strand = None
            else:
                raise Exception('Unknown strand %s' % strand)
    else:
        strand = None
    return cls(start, end, chrom=chrom, strand=strand, **kws)


def computechangesetcopies(ctx):
    """return the copies data for a changeset

    The copies data are returned as a pair of dictionnary (p1copies, p2copies).

    Each dictionnary are in the form: `{newname: oldname}`
    """
    p1copies = {}
    p2copies = {}
    p1 = ctx.p1()
    p2 = ctx.p2()
    narrowmatch = ctx._repo.narrowmatch()
    for dst in ctx.files():
        if not narrowmatch(dst) or dst not in ctx:
            continue
        copied = ctx[dst].renamed()
        if not copied:
            continue
        src, srcnode = copied
        if src in p1 and p1[src].filenode() == srcnode:
            p1copies[dst] = src
        elif src in p2 and p2[src].filenode() == srcnode:
            p2copies[dst] = src
    return p1copies, p2copies


@classmethod
def to_xml(cls, enum_val):
    """
        Return the XML value of the enumeration value *enum_val*.
        """
    if enum_val not in cls._member_to_xml:
        raise ValueError("value '%s' not in enumeration %s" % (enum_val,
            cls.__name__))
    return cls._member_to_xml[enum_val]


def _auc(fpr, tpr):
    """Calculate AUC given FPR and TPR values.

    Note that this function assumes the FPR and TPR values are sorted according to monotonically
    increasing probability thresholds.
    """
    widths = fpr[:-1] - fpr[1:]
    heights = (tpr[:-1] + tpr[1:]) / 2
    return (widths * heights).sum()


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


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

        :param NoteAclLinkType val:
        :rtype: EventType
        """
    return cls('note_acl_link', val)


def _send_buffer(c, buf):
    """Send a buffer object to a pipe connection."""
    c.send(buf.metadata)
    c.send_bytes(buf.data)


def render_hiddenfield(field, attrs):
    """
	Return input as a hidden field.
	"""
    if not '_no_wrapper' in attrs:
        attrs['_no_wrapper'] = 1
    return field


def get_db_client():
    """
    Gets instance of MongoDB client for you to make DB queries.
    :return: MongoDBClient
    """
    from fastapi_contrib.db.client import MongoDBClient
    client = MongoDBClient()
    return client


def box_encode(samples=None, matches=None, anchors=None, refs=None, means=
    None, stds=None, out=None, name=None, **kwargs):
    """Encode bounding boxes training target with normalized center offsets.
        Input bounding boxes are using corner type: `x_{min}, y_{min}, x_{max}, y_{max}`.) array

    Defined in src/operator/contrib/bounding_box.cc:L210

    Parameters
    ----------
    samples : NDArray
        (B, N) value +1 (positive), -1 (negative), 0 (ignore)
    matches : NDArray
        (B, N) value range [0, M)
    anchors : NDArray
        (B, N, 4) encoded in corner
    refs : NDArray
        (B, M, 4) encoded in corner
    means : NDArray
        (4,) Mean value to be subtracted from encoded values
    stds : NDArray
        (4,) Std value to be divided from encoded values

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

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


@staticmethod
def fit_deriv(x, amplitude, x_0, fwhm):
    """
        Drude1D model function derivatives.
        """
    d_amplitude = (fwhm / x_0) ** 2 / ((x / x_0 - x_0 / x) ** 2 + (fwhm /
        x_0) ** 2)
    d_x_0 = -2 * amplitude * d_amplitude * (1 / x_0 + d_amplitude * (x_0 **
        2 / fwhm ** 2) * ((-x / x_0 - 1 / x) * (x / x_0 - x_0 / x) - 2 *
        fwhm ** 2 / x_0 ** 3))
    d_fwhm = 2 * amplitude * d_amplitude / fwhm * (1 - d_amplitude)
    return [d_amplitude, d_x_0, d_fwhm]


def evaluate_total(output):
    """
    Evaluates the total of the different statistics.
    @example: if lines of code and percentage for languages are
              Language Lines Percentage
              "Python"   20     20
              "Java"     80     80
              This will return ['Total', 100, 100]
    """
    total_stats = ['Total']
    for stat_idx in range(1, len(output[0])):
        stat_total = 0
        for lang_stats in output:
            stat_total += lang_stats[stat_idx]
        total_stats.append(stat_total)
    return total_stats


def _isfloat(x):
    """
    returns True if x is a float,
    returns False otherwise
    """
    try:
        float(x)
    except:
        return False
    return True


def push_projection():
    """Add to the projection matrix stack.

    """
    pass


def fromUtf8(s):
    """Convert s from UTF-8 if necessary."""
    if isinstance(s, str):
        return s.decode('utf8')
    else:
        return str(s)


def setGlobalOptions(options):
    """
    Sets the global-options object. The global options
    can then be accessed by globalOptions().
    """
    global globalOptions_
    globalOptions_ = options


def get_url_by_format(config):
    """Get URL depending on the format."""
    if config.format == 'gff3':
        return config.sviewer_url
    return config.entrez_url


@classmethod
def restore_history(cls, ids, datetime):
    """Restore record ids from history at the date time"""
    cls._restore_history(ids, datetime)


def deploy_arm_template():
    """How to deploy an ARM template using Azure CLI."""
    print(
        """
***********************
ARM Template Deployment
***********************

Could this be helpful?  Let us know!
====================================

1. First Step
2. Second Step

And you're done!
"""
        )


@classmethod
def restore_padding(cls, token):
    """Restore padding based on token size.

        :param token: token to restore padding on
        :type token: six.text_type
        :returns: token with correct padding

        """
    mod_returned = len(token) % 4
    if mod_returned:
        missing_padding = 4 - mod_returned
        token += '=' * missing_padding
    return token


def add_cors_header(response):
    """ Adds a header allowing the response being used in scripts. """
    response.headers.add('Access-Control-Allow-Origin', '*')


@classmethod
def name_from_vge(cls, vge_type_name):
    """Get a DataType string from a vge data type string"""
    for name, data_type in cls.types.items():
        if data_type.vge_type == vge_type_name:
            return name
    raise ValueError('Unknown type: ' + vge_type_name)


def forwards(apps, schema_editor):
    """
    Copy the ClassicalWork and DancePiece data to use the new through models.
    """
    Event = apps.get_model('spectator_events', 'Event')
    ClassicalWorkSelection = apps.get_model('spectator_events',
        'ClassicalWorkSelection')
    DancePieceSelection = apps.get_model('spectator_events',
        'DancePieceSelection')
    for event in Event.objects.all():
        for work in event.classicalworks.all():
            selection = ClassicalWorkSelection(classical_work=work, event=event
                )
            selection.save()
        for piece in event.dancepieces.all():
            selection = DancePieceSelection(dance_piece=piece, event=event)
            selection.save()


@classmethod
def _reservedAttributes(cls):
    """
        Override in subclass to reserve a certain number of attributes that can't be used for
        chunks.
        """
    return 1


@staticmethod
def kind_to_resource_name(kind):
    """
        Converts kind to resource name. It is same logics
        as in k8s.io/k8s/pkg/api/meta/restmapper.go (func KindToResource)
        Example:
            Pod -> pods
            Policy - > policies
            BuildConfig - > buildconfigs

        Args:
            kind (str): Kind of the object

        Returns:
            Resource name (str) (kind in plural form)
        """
    singular = kind.lower()
    if singular.endswith(('s', 'x', 'z', 'ch', 'sh')):
        plural = singular + 'es'
    elif singular[-1] == 'y':
        plural = singular.rstrip('y') + 'ies'
    else:
        plural = singular + 's'
    return plural


def new_revision_rql(has_parent, has_precursor=False, set_all=False):
    """return rql to insert a revision entity

    substitutions used:
    * description, author, branch, repoeid (mandatory)
    * parent (if `has_parent` is True)
    * date, changeset (if `set_all` is True)
    """
    rql = (
        'INSERT Revision R: R description %(description)s, R author %(author)s, R branch %(branch)s, R from_repository X, R phase %(phase)s, R hidden %(hidden)s'
        )
    if set_all:
        rql += ', R changeset %(changeset)s'
        rql += ', R creation_date %(date)s'
    if has_parent:
        rql += ', R parent_revision PR'
    if has_precursor:
        rql += ', R obsoletes PREC'
    rql += ' WHERE X eid %(repoeid)s'
    if has_parent:
        rql += ', PR eid %(parent)s'
    if has_precursor:
        rql += ', PREC eid %(precursor)s'
    return rql


def declare_constant(name, value):
    """declare constant"""
    try:
        if value and value[0] not in ('"', "'"):
            int(value)
    except ValueError:
        value = repr(value)
    return '\n{0} = {1}'.format(name.upper(), value)


@staticmethod
def request_output_status(output_id):
    """Generate an output-port status request.

        :param    int    output_id:    Output id 0..3
        :return:    The PCK command (without address header) as text
        :rtype:    str
        """
    if output_id < 0 or output_id > 3:
        raise ValueError('Invalid output_id.')
    return 'SMA{:d}'.format(output_id + 1)


@classmethod
def supports_metadata(cls):
    """returns True if this audio type supports MetaData"""
    return True


def is_hidden(resource, route_doc=None):
    """
    Determine whether a Resource has been hidden from Swagger documentation
    i.e. by using Api.doc(False) decorator
    """
    if route_doc is False:
        return True
    else:
        return hasattr(resource, '__apidoc__') and resource.__apidoc__ is False


def peak_correction(peak_area, sf_machine):
    """Corrected intensity of peak fitting by scaling to the sensitivity
    factor of the machine.

    peak_area   : peak area [CPS*eV]
    sf_machine  : sensitivity factor of xps machine
    """
    return peak_area / sf_machine


def representative_in_range(quotient_class, valid_range):
    """
    Return the unique representative of @p quotient_class in @p valid_range.
    For example, the representative of @c (3 mod 7) in @c range(13, 19) is 17.

    @param     quotient_class  A QuotientClass over the Integers.
    @param     valid_range     The range() object describing the interval in
                               which to the returned representative must lie.

    @return    An integer @c x in @p valid_range with @c x % m == r, where
               @c m is the modulus, and @c r the remainder of @p quotient_class.

    @exception ValueError  either if there is no representative in
                           @p valid_range, or if there are multiple.
    """
    if len(valid_range) > quotient_class.modulus():
        raise ValueError('solution not unique')
    q, r = divmod(valid_range[0], quotient_class.modulus())
    shifted_range = range(r, r + len(valid_range))
    if quotient_class.remainder() in shifted_range:
        return q * quotient_class.modulus() + quotient_class.remainder()
    elif quotient_class.remainder() + quotient_class.modulus(
        ) in shifted_range:
        return (q + 1) * quotient_class.modulus() + quotient_class.remainder()
    else:
        raise ValueError('no solution')


@classmethod
def load_from_options(cls, **kwargs):
    """Create a plugin from the arguments retrieved from get_options.

        A client can override this function to do argument validation or to
        handle differences between the registered options and what is required
        to create the plugin.
        """
    return cls(**kwargs)


def fun_total_capacity(x, tot_cap):
    """Function defining the equality constraint on total capacity.

    :param x: State vector.
    :param tot_cap: Total capacity.
    :type x: :py:class:`numpy.array`
    :type tot_cap: float

    :returns: Value of left-hand side of constraint.
    :rtype: float
    """
    return tot_cap - x.sum()


def p_op_value(p):
    """ op_value : STRING
                 | STRING_ENCLOSED_DOUBLE_QUOTE
                 | IPADDR
                 | op_value COMMA op_value
    """
    p[0] = ''.join(p[1:])


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


def _check(return_val):
    """Checks the return code of the C calls"""
    if __debug__:
        if isinstance(return_val, int) and return_val == 1:
            return
        if isinstance(return_val, bool) and return_val == True:
            return
    if return_val == 1 or return_val == True:
        return
    raise Exception('EC exception')


def set_log_output(fd):
    """Sets log output to a open file-object."""
    global _log_output
    _log_output = fd


@classmethod
def create(cls, name, site, data, meta):
    """
        Create a new Content instance.

        Will extract the content type from the meta, and create the
        appropriate sub-class.
        """
    content_type = meta.get('content_type', cls.__name__)
    try:
        klass = cls.__registry__[content_type]
    except KeyError:
        raise ValueError(
            f'You attempted to create a page with type "{content_type}" but no class is registered to handle this content type'
            )
    return klass(name, site, data=data, meta=meta)


@classmethod
def get_task_id(cls):
    """
        获取当前任务的ID,在后台任务时使用
        :return:
        """
    from .backend_task.task_worker import TaskWorker
    return TaskWorker.get_task_id()