def translate(source, vocab, populate=None, keys=None, solver=None):
    """Translate *source* Semantic Pointer to vocabulary *vocab*.

    The translation of a Semantic Pointer uses some form of projection to
    convert the source Semantic Pointer to a Semantic Pointer of another
    vocabulary. By default the outer products of terms in the source and
    target vocabulary are used, but if *solver* is given, it is used to find
    a least squares solution for this projection.

    Parameters
    ----------
    source : object
        Source of Semantic Pointer.
    vocab : Vocabulary
        Target vocabulary.
    populate : bool, optional
        Whether the target vocabulary should be populated with missing keys.
        This is done by default, but with a warning. Set this explicitly to
        *True* or *False* to silence the warning or raise an error.
    keys : list, optional
        All keys to translate. If *None*, all keys in the source vocabulary
        will be translated.
    solver : nengo.Solver, optional
        If given, the solver will be used to solve the least squares problem to
        provide a better projection for the translation.
    """
    if hasattr(source, 'translate'):
        return source.translate(vocab, populate, keys, solver)
    else:
        raise TypeError("bad operand type for 'translate'")


def delimiter_func(string):
    """The delimiter function used in the image importer
    Used to just get the number of the image from the name of the image/mda file

    Parameters
    ==========
    string (str):
        the string the user wants to place the delimiter function on

    Returns
    =======
    a cropped string based on the delimiter function
    """
    return string.split('_')[-1][0:-4]


def discretize(value, n_dim, min_val, max_val):
    """
    discretize a value into a vector of n_dim dimension 1-hot representation
    with the value below min_val being [1, 0, 0, ..., 0]
    and the value above max_val being [0, 0, ..., 0, 1]
    Args:
        value: the value that needs to be discretized into 1-hot format
        n_dim: number of dimensions
        min_val: minimal value in the result
        man_val: maximum value in the result
    Returns:
        the discretized vector
    """
    assert n_dim > 0
    if n_dim == 1:
        return [1]
    delta = (max_val - min_val) / float(n_dim - 1)
    active_pos = int((value - min_val) / delta + 0.5)
    active_pos = min(n_dim - 1, active_pos)
    active_pos = max(0, active_pos)
    ret_array = [(0) for i in range(n_dim)]
    ret_array[active_pos] = 1.0
    return ret_array


@classmethod
def _register_trace(cls, trace):
    """ Resource subclasses will invoke this method to add a
        resource trace

        """
    cls._traces[trace.name] = trace


def strip(minlink, transaction):
    """Remove storage of items starting at a linkrev.

        This uses ``getstrippoint()`` to determine the first node to remove.
        Then it effectively truncates storage for all revisions after that.

        TODO this is highly revlog centric and should be abstracted into a
        higher-level deletion API.
        """


def assert_cmd_has_no_qmark(command: str, context: str='') ->None:
    """Throws Exception if the query contains a question marks."""
    if '?' not in command:
        return
    message = ''
    if context:
        message = ' ' + context
    message = (message +
        "Set commands must not contain question-marks. Sent command: '{0}'"
        .format(command.strip('\n')))
    raise Exception(message)


def arguments(function, extra_arguments=0):
    """Returns the name of all arguments a function takes"""
    if not hasattr(function, '__code__'):
        return ()
    return function.__code__.co_varnames[:function.__code__.co_argcount +
        extra_arguments]


def format_key_to_etcd(key):
    """Format a dot based key as a etcd key.

    Args:
        key (str): Path to the setting.

    Returns:
        str: Formatted key.
    """
    return '/' + key.replace('.', '/')


def _clean_markdown_cells(ntbk):
    """Clean up cell text of an nbformat NotebookNode."""
    for cell in ntbk.cells:
        if cell.cell_type == 'markdown':
            cell_lines = cell.source.split('\n')
            for ii, line in enumerate(cell_lines):
                if line.startswith('#'):
                    cell_lines[ii] = line.rstrip('#').rstrip()
            cell.source = '\n'.join(cell_lines)
    return ntbk


def create_point(fields, timestamp, decoder, version):
    """
    Create a decoded data point in JSON format

    :returns: a JSON formatted time series data point
    """
    point = {'time': timestamp, 'measurement': '', 'tags': {'satellite': '',
        'decoder': decoder, 'station': '', 'observer': '', 'source': '',
        'version': version}, 'fields': fields}
    return point


def rpartition(text, sep):
    """
    Splits ``text`` at the last occurrence of ``sep``, returning the result as 3-tuple.

    If the separator is not found, this function a 3-tuple containing two empty strings,
    followed by the string itself.

    :return: a 3-tuple containing the part before the separator, the separator itself, and the part after the separator.
    :rtype:  ``tuple`` of ``str``
    """
    assert isinstance(text, str), '%s is not a string' % text
    return text.rpartition(sep)


def convert_bytes(value, unit):
    """Convert bytes to something else"""
    if unit == 'Bps':
        return value
    if unit == 'bps':
        return value * 8
    multiple_unit = unit[0]
    data_unit = unit[1:]
    if data_unit == 'bps':
        value *= 8
    for single_unit in ['k', 'M', 'G', 'T']:
        value = value / 1000
        if single_unit == multiple_unit:
            return value
    raise Exception('Cannot parse %s' % unit)


def navigationRootUrl():
    """Get the url to the current navigation root
        """


def cycles_integrator_preset_add(name: str='', remove_active: bool=False):
    """Add an Integrator 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 asciilower(s):
    """convert a string to lowercase if ASCII

    Raises UnicodeDecodeError if non-ASCII characters are found."""
    s.decode('ascii')
    return s.lower()


def set_four_index_element(four_index_object, i, j, k, l, value):
    """Assign values to a four index object, account for 8-fold index symmetry.

    This function assumes physicists' notation

    Parameters
    ----------
    four_index_object : np.ndarray, shape=(nbasis, nbasis, nbasis, nbasis), dtype=float
        The four-index object
    i, j, k, l: int
        The indices to assign to.
    value : float
        The value of the matrix element to store.
    """
    four_index_object[i, j, k, l] = value
    four_index_object[j, i, l, k] = value
    four_index_object[k, j, i, l] = value
    four_index_object[i, l, k, j] = value
    four_index_object[k, l, i, j] = value
    four_index_object[l, k, j, i] = value
    four_index_object[j, k, l, i] = value
    four_index_object[l, i, j, k] = value


def is_amqplib_ioerror(e):
    """Returns True if e is an amqplib internal exception."""
    return type(e) is IOError and e.args == ('Socket error',)


def alignmentPositions(alignment):
    """
    Extracts start position and length from an alignment

    Arguments:
      alignment : tuples of (operation, length) for each alignment operation.

    Returns:
      dict : query (q) and reference (r) start (0-based) and length information with keys
             {q_start, q_length, r_start, r_length}.
    """
    result = {'q_start': 0, 'q_length': 0, 'r_start': 0, 'r_length': 0}
    if alignment[0][0] == 'S':
        result['q_start'] = alignment[0][1]
    if alignment[0][0] == 'N':
        result['r_start'] = alignment[0][1]
    elif alignment[0][0] == 'S' and alignment[1][0] == 'N':
        result['r_start'] = alignment[1][1]
    for x, i in alignment:
        if x in ('M', '=', 'X'):
            result['r_length'] += i
            result['q_length'] += i
        elif x == 'D':
            result['r_length'] += i
        elif x == 'I':
            result['q_length'] += i
    return result


def lin_norm(data):
    """
    Normalize data with linear algorithm.
    The formula applied to obtain the results is:

        zi = xi - min(x) / max(x) - min(x)

    where x=(x1,...,xn) and zi is now your with normalized data.
    Ensure that the resulting values are comprise between 0 and 1.
    return None if data is None, return empty :class:`pd.DataFrame` object if data is empty.

    :param data: the data to normalize, this 2D matrix must contains only coverage scores (no more metadata).
    :type data: a 2D :class:`pandas.DataFrame` object.
    :return: a normalize matrix, where  0 <= zi <=1 where z=(z1, ..., zn)
    :rtype: a 2D :class:`pandas.DataFrame` object or None if data is None.
    """
    if data is None or data.empty:
        return data
    vmin = data.min().min()
    vmax = data.max().max()
    data -= vmin
    data /= vmax - vmin
    return data


def sanitize(name: str):
    """ Normalize the given string by removing chars that are potentially problematic for the LP solver """
    return name.replace('-', '__')


def relabel_node(graph, node_id, new_id):
    """Relabel a node in the graph.

    Parameters
    ----------
    graph : regraph.Graph
    node_id : id of a node to relabel.
    new_id : hashable, new label of a node.
    """
    graph.relabel_node(node_id, new_id)


def fls(val: int, v6: bool) ->int:
    """Find last set - returns the index, counting from 0 (from the right) of the
    most significant set bit in `val`."""
    if val == 0:
        return 0
    max_power_of_2 = 7 if v6 else 5
    n = val | val >> 1
    for i in range(1, max_power_of_2 + 1):
        n |= n >> 2 ** i
    n += 1
    n >>= 1
    pos = 0
    while n & 1 == 0:
        n >>= 1
        pos += 1
    return pos


def consume(objects):
    """Stores the objects, which this adapter can display, yields not
        consumed objects"""


@classmethod
def add_parser(cls, subparser):
    """Create parser for command line."""
    parser = super().add_parser(subparser)
    parser.add_argument('-i', '--input', help=
        'File to upload (defaults to stdin)')
    parser.add_argument('--overwrite', action='store_true', help=
        'Overwrite existing translations (defaults to none)')
    parser.add_argument('--author-name', help=
        'Author name, to override currently authenticated user')
    parser.add_argument('--author-email', help=
        'Author email, to override currently authenticated user')
    parser.add_argument('--method', choices=('translate', 'approve',
        'suggest', 'fuzzy', 'replace'), default='translate')
    parser.add_argument('--fuzzy', choices=('', 'process', 'approve'),
        default='')
    return parser


def _show_msg(msg, show_other):
    """
    Determine if message should be shown.
    :param msg: message to be shown.
    :param show_other: whether messages from other clients should be shown.
    :return: whether the message should be shown.
    """
    return msg.from_here or show_other


def from_bool_to_int(boolean):
    """Convert a bool to a int representation

    :param boolean: bool to convert
    :type boolean: bool
    :return: if boolean 1 ,else 0
    :rtype: int
    """
    if boolean:
        return 1
    return 0


@classmethod
def header(cls):
    """Header for Enpass CSV file."""
    return cls.csv_header.replace('"', '').split(',')


def calc_flux_rad_ratio_from_light(light_oc, light_tr, light_ref=1.0):
    """Calculate ratio of the radiative fluxes of the smaller star to greater star
    from their light levels  during occultation and transit.
    Assumes L \\propto r^2, no limb darkening.

    Parameters
    ----------
    light_oc : float
        Light level during occultation (primary eclipse). Light level is the average
        of the flat region at the bottom of one of the eclipse minima. The event is
        a total eclipse of the star with the smaller radius.
    light_tr : float
        Light level during transit (secondary eclipse). Light level is the average
        of the rounded region at the bottom of one of the eclipse minima. The event is
        an annular eclipse of the star with the larger radius.
    light_ref : {1.0}, float, optional
        Reference for light levels outside of eclipse. Typically total system light is normalized to 1.0.

    Returns
    -------
    flux_rad_ratio : float
        Ratio of radiative fluxes of smaller star to greater star.
        flux_rad_ratio = flux_rad_s / flux_rad_g

    Notes
    -----
    flux_rad_ratio = flux_rad_s / flux_rad_g
                   = (light_ref - light_oc) / (light_ref - light_tr)
    From equation 7.10 in section 7.3 of [1]_

    References
    ----------
    .. [1] Carroll and Ostlie, 2007, An Introduction to Modern Astrophysics

    """
    flux_rad_ratio = (light_ref - light_oc) / (light_ref - light_tr)
    return flux_rad_ratio


def liget(l, idx, default=None):
    """Tries to get element of list by index, similar to dict.get(). If it fails it returns default"""
    try:
        return l[idx]
    except IndexError:
        return default


def as_2d(points):
    """
    Takes a 3D points and converts to a 2D representation by dropping the z coordinates.
    :param points:
    :return:
    """
    return points[:, :2]


def VCF_website(file, website_url):
    """
    This function add website url
    :param file: file object
    :param website_url: URL
    :type website_url:str
    :return: None
    """
    file.write('item3.URL;type=pref:' + website_url + '\n')
    file.write('END:VCARD')
    file.close()


def read_single_data(db: dict, record_id: int, data_name: str):
    """Return the contents of a data column specified by data_name for a given record_id
    """
    if data_name in db['db'][str(record_id)].keys():
        return db['db'][str(record_id)][data_name]
    else:
        return None


def upload_read(infile, table):
    """
    Reads a table from a MagIC upload (or downloaded) txt file, puts data in a
    list of dictionaries
    """
    delim = 'tab'
    hold, magic_data, magic_record, magic_keys = [], [], {}, []
    f = open(infile, 'r')
    line = f.readline()[:-1]
    file_type = line.split('\t')[1]
    if file_type == 'delimited':
        file_type = line.split('\t')[2]
    if delim == 'tab':
        line = f.readline()[:-1].split('\t')
    else:
        f.close()
        print('only tab delimitted files are supported now')
        return
    while file_type != table:
        while line[0][0:5] in f.readlines() != '>>>>>':
            pass
        line = f.readline()[:-1]
        file_type = line.split('\t')[1]
        if file_type == 'delimited':
            file_type = line.split('\t')[2]
        ine = f.readline()[:-1].split('\t')
    while line[0][0:5] in f.readlines() != '>>>>>':
        for key in line:
            magic_keys.append(key)
        for line in f.readlines():
            rec = line[:-1].split('\t')
            hold.append(rec)
        for rec in hold:
            magic_record = {}
            if len(magic_keys) != len(rec):
                print('Uneven record lengths detected: ', rec)
                input('Return to continue.... ')
            for k in range(len(magic_keys)):
                magic_record[magic_keys[k]] = rec[k]
            magic_data.append(magic_record)
    f.close()
    return magic_data


@classmethod
def iterconstants(cls):
    """
        Iteration over a L{Names} subclass results in all of the constants it
        contains.

        @return: an iterator the elements of which are the L{NamedConstant}
            instances defined in the body of this L{Names} subclass.
        """
    constants = cls._enumerants.values()
    return iter(sorted(constants, key=lambda descriptor: descriptor._index))


def calc_sigma(wfh, wfe, N_state, N_statec, model, Ntotal2d):
    """This function calculates `net' areal charge density
    n-type dopants lead to -ve charge representing electrons, and additionally
    +ve ionised donors."""
    sigma = model.dop * model.dx
    if Ntotal2d > 0:
        for j in range(0, model.subnumber_e, 1):
            sigma -= N_statec[j] * wfe[j] ** 2
    else:
        for i in range(0, model.subnumber_h, 1):
            sigma += N_state[i] * wfh[i] ** 2
    return sigma


def set_column_sequence(dataframe, seq):
    """
    Returns pandas DataFrame with the columns named in seq as first columns.

    :param dataframe: pandas DataFrame to be resorted according to seq.
    :param seq: array of column names.
    """
    cols = seq[:]
    for x in dataframe.columns:
        if x not in cols:
            cols.append(x)
    return dataframe[cols]


def delete_schedule(api, schedule_name):
    """
    Delete a schedule for a user.

    :type api: :class:`mortar.api.v2.api.API`
    :param api: API

    :type schedule_name: str
    :param schedule_name: Name of the schedule to delete.

    :raises: requests.exception.HTTPError: if a 40x or 50x error occurs
    """
    api.delete('schedules/%s' % schedule_name)


@classmethod
def from_matrix(cls, matrix):
    """Creates a ``Transformation`` from a 4x4 two-dimensional list of numbers.

        Parameters
        ----------
        matrix : :obj:`list` of :obj:`list` of `float`
            The 4x4 transformation matrix.

        Returns
        -------
        Transformation
            A transformation object.

        """
    T = cls()
    for i in range(4):
        for j in range(4):
            T.matrix[i][j] = float(matrix[i][j])
    return T


def unflattern(iterator, keys, container=None):
    """Build a structure info from a iterator, using some keys that
    acts as indexes of the structure.

    The value is taken from item itself.
    """
    container = container or dict()
    for item in iterator:
        parent, child = None, container
        for key in keys:
            if isinstance(item, (list, tuple)):
                item = list(item)
                key = item.pop(key)
            elif isinstance(item, dict):
                item = dict(item)
                key = item.pop(key)
            else:
                key = getattr(item, key)
            parent, child = child, child.setdefault(key, dict())
        parent[key] = item
    return container


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

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

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


def parse_mailcap_nametemplate(tmplate='%s'):
    """this returns a prefix and suffix to be used
    in the tempfile module for a given mailcap nametemplate string"""
    nt_list = tmplate.split('%s')
    template_prefix = ''
    template_suffix = ''
    if len(nt_list) == 2:
        template_suffix = nt_list[1]
        template_prefix = nt_list[0]
    else:
        template_suffix = tmplate
    return template_prefix, template_suffix


def _set_play_to_work(params, name: str, index: int, value: float):
    """Adjust the Parameters.play_to_work parameter"""
    if index is not None:
        raise IndexError('You cannot index the play_to_work parameter')
    params.play_to_work = value


def _effective_crossings(fluxdata, nint, end_step):
    """Analyse flux data and obtain effective crossings.

    Parameters
    ----------
    fluxdata : list of tuples of ints
        The list contains the data obtained from a ``md-flux``
        simulation.
    nint : int
        The number of interfaces used.
    end_step : int
        This is the last step done in the simulation.

    Returns
    -------
    eff_cross : list of lists
        `eff_cross[i]` is the effective crossings times for
        interface `i`.
    ncross : list of ints
        `ncross[i]` is the number of crossings for interface `i`.
    neffcross : list of ints
        `neffcross[i]` is the number of effective crossings for
        interface `i`.
    time_in_state : dict
        The time spent in the different states which are labeled with
        the keys 'A', 'B', 'OA', 'OB'. 'O' is taken to mean the
        'overall' state.

    Note
    ----
    We do here `intf - 1`. This is just to be compatible with the old
    FORTRAN code where the interfaces are numbered 1, 2, 3 rather than
    0, 1, 2. If this is to be changed in the future the `-1` can just
    be removed. Such a change will also require changes to the
    formatter for flux data.

    """
    overallstate_a = not (fluxdata[0][1] == 2 and fluxdata[0][2] < 0)
    firstcross = [True] * nint
    ncross = [0] * nint
    neffcross = [0] * nint
    eff_cross = [[] for _ in range(nint)]
    end = {'A': 0, 'B': 0, 'OA': 0, 'OB': 0}
    start = {'A': 0, 'B': 0, 'OA': 0, 'OB': 0}
    time_in_state = {'A': 0, 'B': 0, 'OA': 0, 'OB': 0}
    time, intf, sign = None, None, None
    for time, intf, sign in fluxdata:
        if sign > 0:
            if intf - 1 == 0:
                end['A'] = time
                time_in_state['A'] += end['A'] - start['A']
            elif intf - 1 == 2:
                start['B'] = time
                if overallstate_a:
                    end['OA'] = time
                    start['OB'] = time
                    time_in_state['OA'] += end['OA'] - start['OA']
                    overallstate_a = False
            ncross[intf - 1] += 1
            if firstcross[intf - 1]:
                firstcross[intf - 1] = False
                neffcross[intf - 1] += 1
                eff_cross[intf - 1].append((time - time_in_state['OB'], time))
        elif sign < 0:
            if intf - 1 == 0:
                firstcross = [True] * nint
                start['A'] = time
                if not overallstate_a:
                    end['OB'] = time
                    start['OA'] = time
                    time_in_state['OB'] += end['OB'] - start['OB']
                    overallstate_a = not overallstate_a
            elif intf - 1 == 2:
                end['B'] = time
                time_in_state['B'] += end['B'] - start['B']
    state = 'OA' if overallstate_a else 'OB'
    time_in_state[state] += end_step - start[state]
    if intf - 1 == 0 and sign < 0:
        time_in_state['A'] += end_step - start['A']
    elif intf - 1 == 2 and sign > 0:
        time_in_state['B'] += end_step - start['B']
    return eff_cross, ncross, neffcross, time_in_state


def hex2rgb(hexstring, digits=2):
    """
    Converts a hexstring color to a rgb tuple.
    Example: #ff0000 -> (1.0, 0.0, 0.0)
    digits is an integer number telling how many characters should be
    interpreted for each component in the hexstring.
    """
    if isinstance(hexstring, (tuple, list)):
        return hexstring
    top = float(int(digits * 'f', 16))
    r = int(hexstring[1:digits + 1], 16)
    g = int(hexstring[digits + 1:digits * 2 + 1], 16)
    b = int(hexstring[digits * 2 + 1:digits * 3 + 1], 16)
    return r / top, g / top, b / top


def _simplify(value):
    """
	Return a string whose value can be used as an intializer for an attribute
	value. (If the value is an :class:`int` strip the quotes)
	"""
    try:
        value = int(value)
    except ValueError:
        if '"' in value:
            value = repr(value)
        else:
            value = f'"{repr(value)[1:-1]}"'
    return value


def getTitle():
    """Return a title identifying the criterion.
        """


def _merge_parts(list_de_tuple_parts_id):
    """ Merge two consecutives strings with the same tag """
    if len(list_de_tuple_parts_id) <= 1:
        return list_de_tuple_parts_id
    i = 0
    j = 1
    sentences, tags = zip(*list_de_tuple_parts_id)
    tags = list(tags)
    sentences = list(sentences)
    while j < len(list_de_tuple_parts_id):
        if tags[i] == tags[j]:
            sentences[i] = ' '.join((sentences[i], sentences[j]))
            j += 1
        else:
            i += 1
            tags[i] = tags[j]
            sentences[i] = sentences[j]
            j += 1
    list_de_tuples_merged = list(zip(sentences[:i + 1], tags[:i + 1]))
    return list_de_tuples_merged


def user_chat(info):
    """
        Process 'user sent message to chat' event.

        Input:
        `info`  # A tuple with information about user's callsign and body of
                # the message.
        """


@staticmethod
def _select_choice(codon, selection):
    """
        This function, based upon the codon, makes a choice from the list.
        The determination is based upon the module of the codon to the length
        of the list of choices.  For example, if the codon is 10 and the list
        is 7 choices long, then the selection would be from selection[3].  This
        ensures that for every codon for every selection there is some choice.

        """
    if isinstance(selection, list):
        return selection[codon % len(selection)]
    else:
        msg = 'selection. %s, must be a list' % selection
        raise ValueError(msg)


def AddSubheader(L, N, color, num1, num2, font_family, text, renderer):
    """
    (list, int, str, str, str, str, mistune.Markdown) -> int

    :param L: List with report strings
    :param N: Number of empty lines following header
    :param color: Color of the text
    :param num1: Header number
    :param num2: Sub-header number
    :param font_family: Comma-separated text fonts
    :param text: Text of the header
    :param renderer: markdown renderer

    Add header to list. Modify list in place. And return the sub-header number
    """
    L.append(renderer(
        '
{2}.{3} {4}
'
        .format(color, font_family, num1, num2, text)))
    L.append(renderer('

' * N))
    return num2


def block_level_page_name(sibling_before, sibling_after):
    """Return the next page name when siblings don't have the same names."""
    before_page = sibling_before.page_values()[1]
    after_page = sibling_after.page_values()[0]
    if before_page != after_page:
        return after_page


def contour(z, x=None, y=None, filled=None, xlim=None, ylim=None, xinvert=
    False, yinvert=False, xlog=False, ylog=False, title=None, xlabel=None,
    ylabel=None, lab_loc=0, ax=None, grid=None, plot_kw={}, **kwargs):
    """Level contour plotting function.

	This is a wrapper for pyplot.contour() and pyplot.contourf().

	Parameters
	----------
	z : array-like
		The height values to draw the contours.
	x : array-like, optional
		Position of data points in the x axis.
	y : array-like, optional
		Position of data points in the y axis.
	filled: boolean, optional
		If True, draws filled contours. If not given defaults to the value defined in splotch.Params.
	xlim : tuple-like, optional
		Defines the limits of the x-axis, it must contain two elements (lower and higer limits).
	ylim : tuple-like, optional
		Defines the limits of the y-axis, it must contain two elements (lower and higer limits).
	xinvert : bool, optional
		If True, inverts the x-axis.
	yinvert : bool, optional
		If True, inverts the y-axis.
	xlog : bool, optional
		If True, the scale of the x-axis is logarithmic. If not given defaults to the value defined in splotch.Params.
	ylog : bool, optional
		If True, the scale of the x-axis is logarithmic. If not given defaults to the value defined in splotch.Params.
	title : str, optional
		Sets the title of the plot
	xlabel : str, optional
		Sets the label of the x-axis.
	ylabel : str, optional
		Sets the label of the y-axis.
	lab_loc : int, optional
		Defines the position of the legend
	ax : pyplot.Axes, optional
		Use the given axes to make the plot, defaults to the current axes.
	grid : boolean, optional
		If not given defaults to the value defined in splotch.Params.
	output : boolean, optional
		If True, returns the edges and values of the underlying histogram plus the levels of the contours.
	plot_kw : dict, optional
		Passes the given dictionary as a kwarg to the plotting function. Valid kwargs are QuadContourSet properties.
	**kwargs: QuadContourSet properties, optional
		kwargs are used to specify matplotlib specific properties such as cmap, linewidths, hatches, etc.
		The list of available properties can be found here:
		https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.contour.html

	Returns
	-------
	bin_edges_x : array
		The bin edges for the x axis.
	bin_edges_y : array
		The bin edges for the y axis.
	n : array
		The values of the underlying histogram.
	l : array
		The levels for the contours.
	"""
    from numpy import shape, linspace
    from matplotlib.pyplot import contour, contourf, legend
    from .base_func import axes_handler, dict_splicer, plot_finalizer
    if ax is not None:
        old_axes = axes_handler(ax)
    if filled is None:
        from .defaults import Params
        filled = Params.cont_filled
    if x is None:
        x = linspace(0, 1, z.shape[0])
    if y is None:
        y = linspace(0, 1, z.shape[1])
    plot_par = plot_kw.copy()
    plot_par.update(kwargs)
    plotf = {(False): contour, (True): contourf}
    plotf[filled](x, y, z, **plot_par)
    plot_finalizer(xlog, ylog, xlim, ylim, title, xlabel, ylabel, xinvert,
        yinvert, grid)
    if ax is not None:
        old_axes = axes_handler(old_axes)


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


def _effective_crossings(fluxdata, nint, end_step):
    """Analyse flux data and obtain effective crossings.

    Parameters
    ----------
    fluxdata : list of tuples of ints
        The contents of this array is the data obtained from a
        ``md-flux`` simulation.
    nint : int
        The number of interfaces used.
    end_step : int
        This is the last step done in the simulation.

    Returns
    -------
    eff_cross : list of lists
        `eff_cross[i]` is the effective crossings times for
        interface `i`.
    ncross : list of ints
        `ncross[i]` is the number of crossings for interface `i`.
    neffcross : list of ints
        `neffcross[i]` is the number of effective crossings for
        interface `i`.
    time_in_state : dict
        The time spent in the different states which are labelled with
        the keys 'A', 'B', 'OA', 'OB'. 'O' is taken to mean the
        'overall' state.

    Note
    ----
    We do here `intf - 1`. This is just to be compatible with the old
    Fortran code where the interfaces are numbered 1, 2, 3 rather than
    0, 1, 2. If this is to be changed in the future the `-1` can just
    be removed. Such a change will also require changes to the writer
    for flux data!
    """
    overallstate_a = not (fluxdata[0][1] == 2 and fluxdata[0][2] < 0)
    firstcross = [True] * nint
    ncross = [0] * nint
    neffcross = [0] * nint
    eff_cross = [[] for _ in range(nint)]
    end = {'A': 0, 'B': 0, 'OA': 0, 'OB': 0}
    start = {'A': 0, 'B': 0, 'OA': 0, 'OB': 0}
    time_in_state = {'A': 0, 'B': 0, 'OA': 0, 'OB': 0}
    time, intf, sign = None, None, None
    for time, intf, sign in fluxdata:
        if sign > 0:
            if intf - 1 == 0:
                end['A'] = time
                time_in_state['A'] += end['A'] - start['A']
            elif intf - 1 == 2:
                start['B'] = time
                if overallstate_a:
                    end['OA'] = time
                    start['OB'] = time
                    time_in_state['OA'] += end['OA'] - start['OA']
                    overallstate_a = False
            ncross[intf - 1] += 1
            if firstcross[intf - 1]:
                firstcross[intf - 1] = False
                neffcross[intf - 1] += 1
                eff_cross[intf - 1].append((time - time_in_state['OB'], time))
        elif sign < 0:
            if intf - 1 == 0:
                firstcross = [True] * nint
                start['A'] = time
                if not overallstate_a:
                    end['OB'] = time
                    start['OA'] = time
                    time_in_state['OB'] += end['OB'] - start['OB']
                    overallstate_a = not overallstate_a
            elif intf - 1 == 2:
                end['B'] = time
                time_in_state['B'] += end['B'] - start['B']
    state = 'OA' if overallstate_a else 'OB'
    time_in_state[state] += end_step - start[state]
    if intf - 1 == 0 and sign < 0:
        time_in_state['A'] += end_step - start['A']
    elif intf - 1 == 2 and sign > 0:
        time_in_state['B'] += end_step - start['B']
    return eff_cross, ncross, neffcross, time_in_state


def transform(v):
    """
    Translate environment variables to ones corresponding to keys in the
    configuration.  In particular, env variables may be made with
    "PERI_"+key_name: fftw-threads = PERI_FFTW_THREADS. Each env var
    is later checked to see if it has to do with PERI
    """
    return v.lower().replace('_', '-').replace('peri-', '')


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 _iter_frames(initialFrame):
    """NO-YIELD VERSION: Iterates through all the frames starting at the specified frame (which will be the first returned item)"""
    frames = []
    while initialFrame is not None:
        frames.append(initialFrame)
        initialFrame = initialFrame.f_back
    return frames


def __new__(mcs, name, bases, cls_dict):
    """Return a new class with predefined comparison operators"""
    for method_name in ('__lt__', '__le__', '__gt__', '__ge__', '__eq__',
        '__ne__'):
        if method_name not in cls_dict:
            cls_dict[method_name] = mcs._make_operator(method_name)
    return type.__new__(mcs, name, bases, cls_dict)


def evaluator_parent_inspection(element, parent):
    """
    Recursively check if the evaluator class has the specified parent
    :param element: the element to check
    :param parent: the expected parent
    :return: the check result
    """
    return hasattr(element, 'get_parent_evaluator_classes'
        ) and element.get_parent_evaluator_classes(parent)


def convert_anchors(ori1, dest1, ori2, dest2):
    """
    Given a signal that we want to shift and stretch on the x axis, this affine
    operation can be defined by picking 2 points of the signal (ori1 and ori2,
    called here "anchors"), and mapping them to other 2 points (dest1 and
    dest2). For the given anchors, this function returns the corresponding
    stretching ratio and shifting amount (after stretching) needed to match the
    given anchors. This is given by solving the formula::

      ``[dest1, dest2] = shift + stretch * [ori1, ori2]``

    :param number ori1: any real-valued number. Same for ori2, dest1, dest2.
    :returns: a tuple (stretch, shift) with 2 real-valued numbers.
    """
    o1, d1, o2, d2 = float(ori1), float(dest1), float(ori2), float(dest2)
    stretch = (d1 - d2) / (o1 - o2)
    shift = d1 - stretch * o1
    return stretch, shift


@classmethod
def getPathToArchive(cls):
    """
        Get the path segment of the archive, default '/'.

        In many cases, it's '/archive' or '/fanfiction'
        """
    return ''


def values(min=None, max=None, excludemin=False, excludemax=False):
    """Return an :class:`BTrees.Interfaces.IReadSequence` containing the values in the collection.

        The type of the :class:`~BTrees.Interfaces.IReadSequence` is not specified. It could be a list
        or a tuple or some other type.

        All arguments are optional, and may be specified as keyword
        arguments, or by position.

        If a min is specified, then output is constrained to values whose
        keys are greater than or equal to the given min, and, if excludemin
        is specified and true, is further constrained to values whose keys
        are strictly greater than min.  A min value of None is ignored.  If
        min is None or not specified, and excludemin is true, the value
        corresponding to the smallest key is excluded.

        If a max is specified, then output is constrained to values whose
        keys are less than or equal to the given max, and, if excludemax is
        specified and true, is further constrained to values whose keys are
        strictly less than max.  A max value of None is ignored.  If max is
        None or not specified, and excludemax is true, the value
        corresponding to the largest key is excluded.
        """


def _version_too_old(version, known_good):
    """Return True iff a version is smaller than a tuple of integers.

    This method will return True only if the version string can
    confidently be said to be smaller than ``known_good``. If
    the string cannot be parsed as dot-separated-integers, ``None``
    (which is false) will be returned.

    The comparison is performed part by part, the first non-equal
    one wins.

    >>> _version_too_old('0.4.3', (0,4,3))
    False
    >>> _version_too_old('0.4.2', (0,4,3))
    True
    >>> _version_too_old('0.5.devel', (0,4,3))
    False
    >>> _version_too_old('0.4.devel', (0,4,3))
    """
    for part, expected in zip(version.split('.'), known_good):
        try:
            p = int(part)
        except ValueError:
            return None
        if p < expected:
            return True
        if p > expected:
            break
    return False


def set_abort_status(status):
    """Terminate MPI execution environment at Python exit.

    Terminate MPI execution environment at Python exit by calling
    ``MPI.COMM_WORLD.Abort(status)``. This function should be called
    within an ``except`` block. Afterwards, exceptions should be
    re-raised.
    """
    import sys
    status = status if isinstance(status, int) else 0 if status is None else 1
    pkg = __package__ or __name__.rpartition('.')[0]
    mpi = sys.modules.get(pkg + '.MPI')
    if mpi is not None and status:
        mpi._set_abort_status(status)
    return sys.exc_info()


def is_fp_closed(obj):
    """
    Checks whether a given file-like object is closed.

    :param obj:
        The file-like object to check.
    """
    try:
        return obj.isclosed()
    except AttributeError:
        pass
    try:
        return obj.closed
    except AttributeError:
        pass
    try:
        return obj.fp is None
    except AttributeError:
        pass
    raise ValueError('Unable to determine whether fp is closed.')


@classmethod
def _subclass(cls, is_group):
    """Factory method returning :class:`_TopologyAttrContainer` subclasses.

        Parameters
        ----------
        is_group : bool
            The :attr:`_is_group` of the returned class will be set to
            `is_group`. This is used to distinguish between Groups
            (:class:`AtomGroup` etc.) and Components (:class:`Atom` etc.) in
            internal methods when considering actions such as addition of
            objects or adding
            :class:`TopologyAttributes<MDAnalysis.core.topologyattrs.TopologyAttr>`
            to them.

        Returns
        -------
        type
            A subclass of :class:`_TopologyAttrContainer`, with the same name.
        """
    newcls = type(cls.__name__, (cls,), {'_is_group': bool(is_group)})
    if is_group:
        newcls._SETATTR_WHITELIST = {'positions', 'velocities', 'forces',
            'dimensions', 'atoms', 'residue', 'residues', 'segment', 'segments'
            }
    else:
        newcls._SETATTR_WHITELIST = {'position', 'velocity', 'force',
            'dimensions', 'atoms', 'residue', 'residues', 'segment'}
    return newcls


def select(wait_to_deselect_others: bool=False, mouse_x: int=0, mouse_y:
    int=0, extend: bool=False, camera: bool=False):
    """Select time marker(s)

    :param wait_to_deselect_others: Wait to Deselect Others
    :type wait_to_deselect_others: bool
    :param mouse_x: Mouse X
    :type mouse_x: int
    :param mouse_y: Mouse Y
    :type mouse_y: int
    :param extend: Extend, Extend the selection
    :type extend: bool
    :param camera: Camera, Select the camera
    :type camera: bool
    """
    pass


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


@staticmethod
def rmul(*args):
    """
        Return product of Permutations [a, b, c, ...] as the Permutation whose
        ith value is a(b(c(i))).

        a, b, c, ... can be Permutation objects or tuples.

        Examples
        ========

        >>> from sympy.combinatorics.permutations import _af_rmul, Permutation
        >>> Permutation.print_cyclic = False

        >>> a, b = [1, 0, 2], [0, 2, 1]
        >>> a = Permutation(a); b = Permutation(b)
        >>> list(Permutation.rmul(a, b))
        [1, 2, 0]
        >>> [a(b(i)) for i in range(3)]
        [1, 2, 0]

        This handles the operands in reverse order compared to the ``*`` operator:

        >>> a = Permutation(a); b = Permutation(b)
        >>> list(a*b)
        [2, 0, 1]
        >>> [b(a(i)) for i in range(3)]
        [2, 0, 1]

        Notes
        =====

        All items in the sequence will be parsed by Permutation as
        necessary as long as the first item is a Permutation:

        >>> Permutation.rmul(a, [0, 2, 1]) == Permutation.rmul(a, b)
        True

        The reverse order of arguments will raise a TypeError.

        """
    rv = args[0]
    for i in range(1, len(args)):
        rv = args[i] * rv
    return rv


def count_lines(ipath):
    """Quickly count lines in a file.

    Args:
        ipath (str): path to input file.

    Returns:
        int: number of lines
    """
    rc = 0
    with open(ipath, 'r') as IH:
        for line in IH:
            rc += 1
    return rc


def positionlines(numbers, digits, gapposchar='.'):
    """For a given iterable `numbers` of integers and a given number of `digits`,
    return a list of `digits` strings (lines) that,
    if printed in reverse order below each other,
    constitute the vertically written `numbers` (mod 10**digits).
    """
    lines = [[] for _ in range(digits)]
    if digits <= 0:
        return lines
    for i in numbers:
        if i < 0:
            for l in lines:
                l.append(gapposchar)
        elif i == 0:
            lines[0].append('0')
            for k in range(1, digits):
                lines[k].append(' ')
        else:
            for k in range(digits):
                c = str(i % 10) if i != 0 else ' '
                lines[k].append(c)
                i = i // 10
    for k in range(digits):
        lines[k] = ''.join(lines[k])
    return lines


def ZopeTime(*args):
    """Utility function to return current date/time"""


def get_uncompressed_pub_key(pub_key_raw):
    """Represent public key in full/uncompressed format"""
    assert len(pub_key_raw) == 64
    full_pub_key = b'\x04' + pub_key_raw
    assert len(full_pub_key) == 65
    return full_pub_key


def check_compatibility(seq1, seq2):
    """Function that takes as input two DNA sequence and checks whether their alphabets have at least one element
    in common. This due to an old bug in edlib"""
    for base in seq1:
        for base2 in seq2:
            if base == base2:
                return True
    return False


def _mixed_join(iterable, sentinel):
    """concatenate any string type in an intelligent way."""
    iterator = iter(iterable)
    first_item = next(iterator, sentinel)
    if isinstance(first_item, bytes):
        return first_item + b''.join(iterator)
    return first_item + u''.join(iterator)


def lint_response_objects(spec, resolver):
    """
    Must: Always Return JSON Objects As Top-Level Data Structures To Support Extensibility

    https://zalando.github.io/restful-api-guidelines/compatibility/Compatibility.html#must-always-return-json-objects-as-toplevel-data-structures-to-support-extensibility
    """
    for path_name, methods_available in spec.get('paths', {}).items():
        for method_name, method_def in methods_available.items():
            if isinstance(method_def, dict):
                for status_code, response_def in method_def.get('responses', {}
                    ).items():
                    schema_type = response_def.get('schema', {}).get('type')
                    if schema_type and schema_type != 'object':
                        yield 'paths/"{}"/{}/responses/{}'.format(path_name,
                            method_name, status_code)


def is_draft(post):
    """returns True/False based on `published` metadata in post"""
    if post is not None and ('published' in post.meta and post.meta[
        'published'] is False or 'status' in post.meta and post.meta[
        'status'].lower() == 'draft' or 'published' not in post.meta):
        return post


@classmethod
def max(cls, a, b):
    """比较两个版本(1.1.1)的大小，需要按.分割后比较各个部分的大小
        :param a 对比的第一个字符串
        :param b 对比的第二个字符串
        """
    ret = cls.cmp(a, b)
    if ret >= 0:
        return a
    else:
        return b


@staticmethod
def get_preference_static(request, prefname):
    """
        Get a preference, or None
        """
    full_name = 'exordium__%s' % prefname
    if request.user.is_authenticated:
        return request.user.preferences[full_name]
    elif full_name in request.session:
        return request.session[full_name]
    else:
        return None


def midpoint(pt1, pt2):
    """Computes the midpoint between two points"""
    x = pt2[0] + int((pt1[0] - pt2[0]) / 2)
    y = pt2[1] + int((pt1[1] - pt2[1]) / 2)
    return x, y


def chars_to_ranges(s):
    """
    Return a list of character codes consisting of pairs
    [code1a, code1b, code2a, code2b,...] which cover all
    the characters in |s|.
    """
    char_list = list(s)
    char_list.sort()
    i = 0
    n = len(char_list)
    result = []
    while i < n:
        code1 = ord(char_list[i])
        code2 = code1 + 1
        i += 1
        while i < n and code2 >= ord(char_list[i]):
            code2 += 1
            i += 1
        result.append(code1)
        result.append(code2)
    return result


def search(text, quotable=False, scorable=True):
    """Search all CMIS content that contains the given text.
        """


def countX(lst, x):
    """An internal function counting the number of time an element is present in a list"""
    return lst.count(x)


@classmethod
def insnstr(cls, s, x=None, y=None, n=None, attr=None):
    """
        Insert a string at cursor or specified position, at most n characters.
        Cursor is not moved and characters to the right are shifted right.
        If n is zero, all characters are inserted.

        :param s: the string
        :param x: optional x value
        :param y: optional y value
        :param n: max characters to insert (0 is all)
        :param attr: optional attributes
        """
    x, y = cls._fix_xy(x, y)
    attr = cls._fix_attr(attr)
    n = n if n is not None else cls.WIDTH
    if attr is None:
        return cls.WINDOW.insnstr(y, x, s, n)
    else:
        return cls.WINDOW.insnstr(y, x, s, n, attr)


@staticmethod
def user_parse(data):
    """Parse information from the provider."""
    _user = data.get('query', {}).get('results', {}).get('profile', {})
    yield 'id', _user.get('guid')
    yield 'username', _user.get('username')
    yield 'link', _user.get('profileUrl')
    emails = _user.get('emails')
    if isinstance(emails, list):
        for email in emails:
            if 'primary' in list(email.keys()):
                yield 'email', email.get('handle')
    elif isinstance(emails, dict):
        yield 'email', emails.get('handle')
    yield 'picture', _user.get('image', {}).get('imageUrl')
    city, country = map(lambda s: s.strip(), _user.get('location', ',').
        split(','))
    yield 'city', city
    yield 'country', country


@classmethod
def from_existing_session(cls, session: object, options: str=None
    ) ->'RsCmwWlanSig':
    """Creates a new RsCmwBluetoothSig object with the entered 'session' reused.

		:param session: can be an another driver or a direct pyvisa session.
		:param options: string tokens alternating the driver settings."""
    return cls(None, False, False, options, session)


@classmethod
def can_preview_object(cls, entry):
    """ Override whether the node can be previewed. """
    return hasattr(entry, 'get_absolute_url') and entry.is_published


@staticmethod
def __check_string_tag_ignore(match_result, tag_index, string_ignore_chars):
    """
        检查匹配到的字符串结束标签在忽略字符中
        向前、向后找与标签有重叠冲突的匹配结果，看是否在忽略字符中

        @param {[type]} match_result - <description>
        @param {[type]} tag_index - <description>
        @param {[type]} string_ignore_chars - <description>

        @returns {bool} - True-在忽略字符中，False-不在忽略字符中

        """
    _max_char_len = 0
    for _item in string_ignore_chars:
        if len(_item) > _max_char_len:
            _max_char_len = len(_item)
    if _max_char_len < 2:
        return False
    _match_info = match_result[tag_index]
    _maxlen = len(match_result)
    _current_index = tag_index - 1
    while _current_index >= 0:
        _cmp_info = match_result[_current_index]
        if _cmp_info[2] <= _match_info[2] - _max_char_len:
            break
        if _cmp_info[2] <= _match_info[2] < _cmp_info[3]:
            if _cmp_info[0] in string_ignore_chars:
                return True
        _current_index = _current_index - 1
        continue
    _current_index = tag_index + 1
    while _current_index < _maxlen:
        _cmp_info = match_result[_current_index]
        if _cmp_info[2] > _match_info[2]:
            break
        if _cmp_info[2] <= _match_info[2]:
            if _cmp_info[0] in string_ignore_chars:
                return True
        _current_index = _current_index + 1
        continue
    return False


@staticmethod
def split_text(text, part_length, signature, continue_text=
    """

--- continued below ---""", split_char='\n'):
    """
        Split a text into several parts. Attach signature to every message and an info regarding the split to every
        message except the last.
        :param text: text which should be splitted
        :param part_length: maximum amount of characters per part
        :param signature: signature which should be present on every part
        :param continue_text: info regarding the split, present on every part except the last
        :param split_char: character on which the split should be determined on
        :return: list of parts
        """
    extra_length = len(signature) + len(continue_text)
    parts = []
    while True:
        if len(text) <= 0:
            return parts
        content_parts = text.split(split_char)
        stitched_content = ''
        for part in content_parts:
            if len(stitched_content) + len(part + split_char
                ) + extra_length <= part_length:
                stitched_content += part + split_char
            else:
                break
        if text[len(stitched_content):] == '':
            parts.append(stitched_content + signature)
        else:
            parts.append(stitched_content + continue_text + signature)
        text = text[len(stitched_content):]


def uniqify_phenotypes(lines):
    """Produce a new resource with phenotypes and descriptions

        Args:
            lines (Iterator): The lines of the file

        Returns:
            hpo_terms(generator(dict)): The hpoterms
    """
    hpo_terms = {}
    for line in lines:
        if not line.startswith('#'):
            line = line.rstrip().split('\t')
            hpo_id = line[0]
            description = line[1]
            hpo_terms[hpo_id] = description
    return hpo_terms


def _gene2n_transcripts(data):
    """
    Return a dictionary from gene id to number of transcripts in the gene.
    """
    return data.groupby('GeneID').apply(lambda df: len(set(df.
        TranscriptIDCluster))).to_dict()


def optionalFlagParse(raw: str) ->bool:
    """
	Parses the allowed values for the optional JSON and TIMESTAMP
	configuration flags, and returns their value as a boolean.
	"""
    try:
        return bool(int(raw))
    except ValueError:
        try:
            return {'FALSE': False, 'TRUE': True}[raw]
        except KeyError:
            raise ValueError('Invalid value: %s' % raw)


@classmethod
def load_pkcs1(cls, keyfile, format='PEM'):
    """Loads a key in PKCS#1 DER or PEM format.

        :param keyfile: contents of a DER- or PEM-encoded file that contains
            the key.
        :type keyfile: bytes
        :param format: the format of the file to load; 'PEM' or 'DER'
        :type format: str

        :return: the loaded key
        :rtype: AbstractKey
        """
    methods = {'PEM': cls._load_pkcs1_pem, 'DER': cls._load_pkcs1_der}
    method = cls._assert_format_exists(format, methods)
    return method(keyfile)


def leading_space(line):
    """Returns a string representing the leading whitespace for the specified
    string."""
    return line[:len(line) - len(line.lstrip())]


def isAllowedToEdit(user):
    """
        This method returns true if the given user is allowed to edit the
        contents of the tile based on which group is he member of.
        If no user is provided, it will check on the authenticated member.
        """


def expose_action(func):
    """This decorator makes a method into an action."""
    func.__daemonocle_exposed__ = True
    return func


def dict_to_sequence(d):
    """Returns an internal sequence dictionary update."""
    if hasattr(d, 'items'):
        d = d.items()
    return d


@classmethod
def from_device(cls, device, parent=None):
    """Create a TyphosMethodButton from a device"""
    instance = cls(parent=parent)
    instance.add_device(device)
    return instance


def character_tokenizer(sequence):
    """ Splits sequence into a list of characters. """
    if sequence:
        return [*sequence]


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

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

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


def revs(start=0, stop=None):
    """Iterate over revision numbers for this file, with control."""


def _shell_escape(string):
    """
    Escape double quotes, backticks and dollar signs in given ``string``.

    For example::

        >>> _shell_escape('abc$')
        'abc\\\\$'
        >>> _shell_escape('"')
        '\\\\"'
    """
    for char in ('"', '$', '`'):
        string = string.replace(char, '\\%s' % char)
    return string


def getAllImages():
    """
    Function generating a script to extract all image tags of a web page.

    @return script to extract image tags
    @rtype str
    """
    source = """
(function() {
    var out = [];
    var imgs = document.getElementsByTagName('img');
    for (var i = 0; i < imgs.length; ++i) {
        var e = imgs[i];
        out.push({
            src: e.src,
            alt: e.alt
        });
    }
    return out;
})()"""
    return source


def view_zoom_out(location: float=(0.0, 0.0)):
    """Zoom out the image (centered around 2D cursor)

    :param location: Location, Cursor location in screen coordinates
    :type location: float
    """
    pass


def clean_prefix(x: str, prefix: str) ->str:
    """Remove a prefix and all options from the command x."""
    if not x.startswith(prefix):
        return x
    x = x[len(prefix):]
    i = 0
    last_was_minus = False
    for i, char in enumerate(x):
        if last_was_minus:
            if char == ' ':
                last_was_minus = False
        if char == '-':
            last_was_minus = True
        if char not in ['-', ' '] and not last_was_minus:
            break
    x = x[i:]
    return x


@staticmethod
def classes(attrs):
    """Get tag's classes from its attribute dict."""
    return attrs.get('class', '').split()


def split_number_and_unit(s):
    """Parse a string that consists of a integer number and an optional unit.
    @param s a non-empty string that starts with an int and is followed by some letters
    @return a triple of the number (as int) and the unit
    """
    if not s:
        raise ValueError('empty value')
    s = s.strip()
    pos = len(s)
    while pos and not s[pos - 1].isdigit():
        pos -= 1
    number = int(s[:pos])
    unit = s[pos:].strip()
    return number, unit


def get_yes_no_from_user(message):
    """return the Boolean value of the users response the a yes/no question"""
    while True:
        try:
            yes_no = bool('y' in input(message).lower())
        except ValueError:
            print("Sorry, I didn't understand that\n")
            continue
        else:
            break
    return yes_no


def is_container():
    """Return boolean: container or none"""


def combine_request_approved(access_requests):
    """Combine pending and approved requests for the same user.

       Emergency Access Service returns both requests and approved access.
       If a request is already approved we don't want to show the request, so
       we merge the requests by user."""
    current_access = {}
    for request in access_requests:
        req = current_access.get(request['user'], request)
        if not req.get('approved', False):
            req['approved'] = request.get('approved', False)
            req['expiry_time'] = request['expiry_time']
        if req.get('reason', '') == '':
            req['reason'] = request['reason']
        current_access[request['user']] = req
    return current_access


def db_field_to_ratio(db):
    """
    Convert a given ratio from a decibel value for field quantities to the underlying quantity.
    The result is returned as a ratio to the 0 dB value.
    """
    return 10 ** (db / 20.0)


@staticmethod
def diffWithOverflowCheck(new, old):
    """
        do a difference with overflow check and repair
        the counter is unsigned 32 or 64 bit
        """
    if new >= old:
        return new - old
    else:
        maxv = (1 << 31) * 2
        if old >= maxv:
            maxv = (1 << 63) * 2
        return new - old + maxv


@staticmethod
def addon_defaults_list(session=None):
    """
        Return a list of default add-ons.

        The return value must be a list with meta description following the
        `PyPI JSON api`_ specification. At the minimum 'info.name' and
        'info.version' must be supplied. e.g.

            `[{'info': {'name': 'Super Pkg', 'version': '4.2'}}]

        .. _`PyPI JSON api`:
            https://warehouse.readthedocs.io/api-reference/json/
        """
    return []


@classmethod
def from_args(cls, args):
    """Builds a pipeline instance from the given arguments.

        Parameters
        ----------
        args : Namespace
            Parsed arguments from argparser.

        Returns
        -------
        Pipeline
            Instantiated pipeline instance.

        """
    return cls(**cls._extract_args(args))


def to_numpy(x):
    """
    Moves a tensor to :mod:`numpy`.

    :param x:
        a :class:`torch.Tensor`.
    :return:
        a :class:`numpy.ndarray`.
    """
    return x.cpu().detach().data.numpy()


def format_timestamp(dt):
    """
    Format the given timestamp.

    :param datetime.datetime dt: A datetime.datetime object to be formatted.
    """
    return dt.strftime('%Y-%m-%dT%H:%M:%S.999-05:00')


def get_dict_element_header(title=None, k=None, v=None):
    """
    File creation function - Get data for output file
    :param title: Element title
    :param k: Key value
    :param v: Value associated to the key
    :return: Dictionary with the [title], the key and the value
    """
    if title:
        return {'title': title, 'key': k, 'value': v}
    else:
        return {'key': k, 'value': v}


@classmethod
def request_payload(cls, id_, method, params=None):
    """JSON v2 request payload.  Params is optional."""
    payload = {'jsonrpc': '2.0', 'method': method, 'id': id_}
    if params:
        payload['params'] = params
    return payload


def standard_python_slice(len_idx, arg):
    """ Figuring out the missing parameters of slice"""
    start = arg.start
    stop = arg.stop
    step = arg.step
    if step is None:
        step = 1
    if step == 0:
        raise Exception('Step cannot be zero.')
    if start is None:
        start = 0 if step > 0 else len_idx - 1
    else:
        if start < 0:
            start += len_idx
        if start < 0:
            start = 0 if step > 0 else -1
        if start >= len_idx:
            start = len_idx if step > 0 else len_idx - 1
    if stop is None:
        stop = len_idx if step > 0 else -1
    else:
        if stop < 0:
            stop += len_idx
        if stop < 0:
            stop = 0 if step > 0 else -1
        if stop >= len_idx:
            stop = len_idx if step > 0 else len_idx - 1
    if step < 0 and stop >= start or step > 0 and start >= stop:
        slice_length = 0
    elif step < 0:
        slice_length = (stop - start + 1) // step + 1
    else:
        slice_length = (stop - start - 1) // step + 1
    return start, stop, step, slice_length


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

    The ".dev0" means dirty.

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


def drop():
    """
        Unconditionally drop (close) the database connection.
        """


def SetVersion(Version):
    """
	Activate mail sending according to version.
	"""
    if Version.upper().startswith('RD') or Version.lower().startswith('test'):
        SendMail = True
    else:
        SendMail = False
    return


def PmfProbEqual(pmf1, pmf2):
    """Probability that a value from pmf1 equals a value from pmf2.

    Args:
        pmf1: Pmf object
        pmf2: Pmf object

    Returns:
        float probability
    """
    total = 0.0
    for v1, p1 in pmf1.Items():
        for v2, p2 in pmf2.Items():
            if v1 == v2:
                total += p1 * p2
    return total


def ternary_search(f, lo, hi, gap=1e-10):
    """Ternary maximum search for a bitonic function

    :param f: boolean bitonic function (increasing then decreasing, not necessarily strictly)
    :param int lo:
    :param int hi: with hi >= lo
    :param float gap:
    :returns: value x in [lo,hi] maximizing f(x),
             x is computed up to some precision
    :complexity: `O(log((hi-lo)/gap))`
    """
    while hi - lo > gap:
        step = (hi - lo) / 3.0
        if f(lo + step) < f(lo + 2 * step):
            lo += step
        else:
            hi -= step
    return lo


@staticmethod
def list_source_and_target_plates(picklist):
    """Return two lists: plates with resp. source wells and target wells.

        In the final animation, source plates will be on the left and target
        plates on the right.
        """
    source_plates = []
    target_plates = []
    seen_plates = set()
    for _transfer in picklist.transfers_list:
        source_plate = _transfer.source_well.plate
        target_plate = _transfer.destination_well.plate
        if source_plate not in seen_plates:
            source_plates.append(source_plate)
        if target_plate not in seen_plates:
            target_plates.append(target_plate)
        seen_plates.add(source_plate)
        seen_plates.add(target_plate)
    return source_plates, target_plates


def payment_delete(payment):
    """This is called just before a payment is deleted

        :param payment: the payment which is going to be deleted
        """


@classmethod
def RegisterCredentials(cls, credentials):
    """Registers a path specification credentials.

    Args:
      credentials (Credentials): credentials.

    Raises:
      KeyError: if credentials object is already set for the corresponding
          type indicator.
    """
    if credentials.type_indicator in cls._credentials:
        raise KeyError(
            'Credentials object already set for type indicator: {0:s}.'.
            format(credentials.type_indicator))
    cls._credentials[credentials.type_indicator] = credentials


def render_pep440_bare(pieces):
    """TAG[.DISTANCE[.dev0]] .

    The ".dev0" means dirty.

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


def prompt(string):
    """Returns string formatted as prompt.

  Escape sequences used for colors, in combination with readline, break input()
  Since tab completion is more useful than the bold prompt, the bold prompt is nixed.
  Thus this funciton presently does nothing.
  """
    return string


def phi1_from_phi_a_phi_s(phi_a, phi_s):
    """Returns the angle between the x-component axis and the in-plane
    spin for the primary mass from phi_s and phi_a.
    """
    return (phi_s + phi_a) / 2.0


@staticmethod
def call_callback_functions(functions, message):
    """Call callback functions."""
    for func in functions:
        func(message)


@classmethod
def from_columns(cls, columns, column_names=None, wrapped=True):
    """
        Build a new object of the type corresponding to the wrapper from the supplied `columns` (a list of columns; only length-1 lists is supported).

        `column_names` parameter is ignored.
        If ``wrapped==True``, return a new wrapper contating the column; otherwise, just return the column.
        """
    if len(columns) != 1:
        raise ValueError(
            'Array1DWrapper only supports single columns, got {} columns'.
            format(len(columns)))
    return cls.from_array(columns[0])


def SHORTER(fragment):
    """Sort shorter passages first."""
    return len(fragment)


@staticmethod
def get_values(data):
    """Return median of gauss distributed layer
        calculated from expected values."""
    return data


def load_samples(sample_file_paths):
    """Read in processed sample files, returning flat list."""
    samples = []
    for sample_file_path in sample_file_paths:
        with open(sample_file_path, 'r') as sample_file:
            for sample in sample_file:
                sample = sample.strip()
                samples.append(sample)
    return samples


def lastmodified_sort(d1, d2):
    """ sort dictionaries in descending order based on last mod time """
    m1 = d1.get('_last_modified', 0)
    m2 = d2.get('_last_modified', 0)
    if m1 == m2:
        return 0
    if m1 > m2:
        return -1
    return 1


def metar_to_iso8601(metardate):
    """Convert a metar date to an ISO8601 date."""
    if metardate is not None:
        date, hour = metardate.split()[:2]
        year, month, day = date.split('.')
        return '%s-%s-%s %s:%s:00Z' % (year, month, day, hour[:2], hour[2:4])


@classmethod
def upload_files(cls, files, **kwargs):
    """Upload files to remote machines, so that they are accessible by import or load.
        """
    cls.REMOTE_MANAGER.upload_files(files, **kwargs)


def is_class_private_name(name):
    """ Determine if a name is a class private name. """
    return name.startswith('__') and not name.endswith('__')


@classmethod
def loose_minority_constraint(cls, variables):
    """Clauses encoding a "at most half" constraint

        Parameters
        ----------
        variables : list of variables
           variables in the constraint

        Returns
        -------
            a list of clauses
        """
    threshold = int(len(variables) / 2)
    return cls.less_or_equal_constraint(variables, threshold)


@classmethod
def is_decorated_with(this, fn, decorator):
    """Checks if a given function decorated with the given decorator

		Usage example:
		::
			from regd import DecoratorRegisrty

			# defining decorator function
			def my_decorator( fn) :
				def wrapper( *args, **kwargs) :
					print( "%s called" %fn.__name__)
					return fn( *args, **kwargs)
				return wrapper

			# registering decorator function with DecoratorRegistry
			my_decorator = DecoratorRegistry.decorator( my_decorator)

			# example class
			class MyClass :
				@my_decorator
				def my_method( self) :
					if (DecoratorRegistry.is_decorated_with( self.my_method, my_decorator)) :
						print( "my_method is decorated with my_decorator" %())
					else :
						print( "my_method is not decorated with my_decorator")

			inst = MyClass()
			inst.my_method()

		:param fn: function to check
		:param decorator: decorator function to check with
		:rtype: bool
		"""
    return decorator in this.get_decorators(fn)


def _get_rbe3_um(i, unused_j, idata, unused_fdata):
    """helper for ``read_rbe3s_from_idata_fdata``"""
    gmi = []
    cmi = []
    if idata[i] == -2:
        i += 1
    if idata[i] != -3:
        while idata[i] != -3:
            gm = idata[i]
            cm = idata[i + 1]
            gmi.append(gm)
            cmi.append(cm)
            i += 2
    if idata[i] == -3:
        i += 1
    return i, gmi, cmi


def comma_ize(strings, lastComma=True):
    """ Make a single string with input strings separated by commas.

        Set `lastComma=False` if there should be no ending comma."""
    string = ''
    for s in strings:
        string += str(f'{s}, ')
    if not lastComma:
        ret = string[0:-2]
    else:
        ret = string
    return ret


def get_job_details(jobId=None):
    """
    Returns information about a job. Only used for custom actions.
    See also: AWS API Documentation

    :example: response = client.get_job_details(
        jobId='string'
    )

    :type jobId: string
    :param jobId: [REQUIRED]
            The unique system-generated ID for the job.

    :rtype: dict
    :return: {
        'jobDetails': {
            'id': 'string',
            'data': {
                'actionTypeId': {
                    'category': 'Source'|'Build'|'Deploy'|'Test'|'Invoke'|'Approval',
                    'owner': 'AWS'|'ThirdParty'|'Custom',
                    'provider': 'string',
                    'version': 'string'
                },
                'actionConfiguration': {
                    'configuration': {
                        'string': 'string'
                    }
                },
                'pipelineContext': {
                    'pipelineName': 'string',
                    'stage': {
                        'name': 'string'
                    },
                    'action': {
                        'name': 'string'
                    }
                },
                'inputArtifacts': [
                    {
                        'name': 'string',
                        'revision': 'string',
                        'location': {
                            'type': 'S3',
                            's3Location': {
                                'bucketName': 'string',
                                'objectKey': 'string'
                            }
                        }
                    },
                ],
                'outputArtifacts': [
                    {
                        'name': 'string',
                        'revision': 'string',
                        'location': {
                            'type': 'S3',
                            's3Location': {
                                'bucketName': 'string',
                                'objectKey': 'string'
                            }
                        }
                    },
                ],
                'artifactCredentials': {
                    'accessKeyId': 'string',
                    'secretAccessKey': 'string',
                    'sessionToken': 'string'
                },
                'continuationToken': 'string',
                'encryptionKey': {
                    'id': 'string',
                    'type': 'KMS'
                }
            },
            'accountId': 'string'
        }
    }

    """
    pass


def faces_select_linked_flat(sharpness: float=0.0174533):
    """Select linked faces by angle

    :param sharpness: Sharpness
    :type sharpness: float
    """
    pass


@staticmethod
def get_callback_pattern(expected_params, actual_params):
    """
        Assembles a dictionary whith the parameters schema defined for this route
        :param expected_params dict parameters schema defined for this route
        :param actual_params dict actual url parameters
        :rtype: dict
        """
    pattern = dict()
    key = 0
    for exp_param in expected_params:
        if exp_param[0] == '{' and exp_param[-1:] == '}':
            pattern[exp_param[1:-1]] = actual_params[key]
        key = key + 1
    return pattern


def check_args(parsed_args):
    """
    Function to check for inherent contradictions within parsed arguments.
    For example, batch_size < num_gpus
    Intended to raise errors prior to backend initialisation.

    :param parsed_args: parser.parse_args()
    :return: parsed_args
    """
    return parsed_args


def _gather_channels(x, indexes, **kwargs):
    """Slice tensor along channels axis by given indexes"""
    backend = kwargs['backend']
    if backend.image_data_format() == 'channels_last':
        x = backend.permute_dimensions(x, (3, 0, 1, 2))
        x = backend.gather(x, indexes)
        x = backend.permute_dimensions(x, (1, 2, 3, 0))
    else:
        x = backend.permute_dimensions(x, (1, 0, 2, 3))
        x = backend.gather(x, indexes)
        x = backend.permute_dimensions(x, (1, 0, 2, 3))
    return x


def url_open(url: str=''):
    """Open a website in the web-browser

    :param url: URL, URL to open
    :type url: str
    """
    pass


@classmethod
def meta_info(cls):
    """Returns meta info for this job class.
        For example:
            {
                'job_class_string': 'myscheduler.jobs.myjob.MyJob',
                'arguments': [
                    {'type': 'string', 'description': 'name of this channel'},
                    {'type': 'string', 'description': 'what this channel does'},
                    {'type': 'int', 'description': 'created year'}
                ],
                'example_arguments': '["music channel", "it's an awesome channel", 1997]',
                'notes': 'need to specify environment variable API_KEY first'
            }
        The arguments property should be consistent with the run() method.
        This info will be used in web ui for explaining what kind of arguments is needed for a job.
        You should override this function if you want to make your scheduler web ui informative :)
        :return: meta info for this job class.
        :rtype: dict
        """
    return {'job_class_string': '%s.%s' % (cls.__module__, cls.__name__),
        'arguments': [], 'example_arguments': '', 'notes': ''}


def max(input, dim):
    """Reduce max the input tensor along the given dim.

    Parameters
    ----------
    input : Tensor
        The input tensor.
    dim : int
        The reduce dim.

    Returns
    -------
    Tensor
        A framework-specific tensor.
    """
    pass


def column_exists(df, col):
    """Check the column name exists in the DataFrame.

    Args:
        df (:obj:`DataFrame`): Pandas DataFrame.
        col (str): Column name.

    Returns:
        bool: True if exists, False if not exists.

    """
    if col and col not in df.columns:
        print('The specify column `{0!s}` not found in the input file'.
            format(col))
        return False
    else:
        return True


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


def delete(obj_id, store):
    """Delete an ORM Interface Object"""


@staticmethod
def build_latent_variables():
    """ Builds additional latent variables for this family in a probabilistic model

        Returns
        ----------
        - A list of lists (each sub-list contains latent variable information)
        """
    lvs_to_build = []
    return lvs_to_build


def same_side_cross(v1, v2):
    """Checks if one line crosses both crossings from the same side"""
    if abs(v1[0] - v2[0]) == 1:
        return v1[0].top == v2[0].top
    elif abs(v1[1] - v2[0]) == 1:
        return v1[1].top == v2[0].top
    elif abs(v1[1] - v2[1]) == 1:
        return v1[1].top == v2[1].top
    elif abs(v1[0] - v2[1]):
        return v1[0].top == v2[1].top
    else:
        return False


@classmethod
def from_hdf(cls, fp, template_hash, root=None, load_to_memory=True,
    load_now=False):
    """Load a compressed waveform from the given hdf file handler.

        The waveform is retrieved from:
        `fp['[{root}/]compressed_waveforms/{template_hash}/{param}']`,
        where `param` is the `sample_points`, `amplitude`, and `phase`.

        Parameters
        ----------
        fp : h5py.File
            An open hdf file to write the compressed waveform to.
        template_hash : {hash, int, str}
            The id of the waveform.
        root : {None, str}
            Retrieve the `compressed_waveforms` group from the given string.
            If `None`, `compressed_waveforms` will be assumed to be in the
            top level.
        load_to_memory : {True, bool}
            Set the `load_to_memory` attribute to the given value in the
            returned instance.
        load_now : {False, bool}
            Immediately load the `sample_points`/`amplitude`/`phase` to memory.

        Returns
        -------
        CompressedWaveform
            An instance of this class with parameters loaded from the hdf file.
        """
    if root is None:
        root = ''
    else:
        root = '%s/' % root
    group = '%scompressed_waveforms/%s' % (root, str(template_hash))
    fp_group = fp[group]
    sample_points = fp_group['sample_points']
    amp = fp_group['amplitude']
    phase = fp_group['phase']
    if load_now:
        sample_points = sample_points[:]
        amp = amp[:]
        phase = phase[:]
    return cls(sample_points, amp, phase, interpolation=fp_group.attrs[
        'interpolation'], tolerance=fp_group.attrs['tolerance'], mismatch=
        fp_group.attrs['mismatch'], precision=fp_group.attrs['precision'],
        load_to_memory=load_to_memory)


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

    The ".dev0" means dirty.

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


def get_E(data, keys):
    """
    Retrive the E from a dataset
    """
    try:
        Ei = keys.index('Ekine')
    except:
        try:
            Ei = keys.index('E')
        except:
            raise RuntimeError(
                "Error, cannot find key 'Ekine' nor 'E'. Keys are: ", keys)
    E = data[:, (Ei)]
    return E, Ei


def t_2(t_nom, t_cor):
    """ Characteristic wall thicknesses (Table 5-6)
    t_2 used where failure is likely to occur in connection with an
    extreme load effect at a location with average thickness:
    - Buckle """
    return t_nom - t_cor


def getEmail():
    """Returns email of the order's customer.
        """


@classmethod
def is_arrival(cls, session, trip_id, stop_id):
    """
        :return True if it looks like this Trip / Stop pair is an arrival only
        NOTE: this routine might be EXPENSIVE since it is
        Further, this routine isn't well thought out...not sure block.is_arrival() works
        """
    _is_arrival = False
    from gtfsdb import Block
    blocks = Block.blocks_by_trip_stop(session, trip_id, stop_id)
    if blocks:
        for b in blocks:
            if b.is_arrival():
                _is_arrival = True
                break
    return _is_arrival


@classmethod
def remove_line_with(cls, lines, what):
    """
        returns all lines that do not contain what
        :param lines:
        :param what:
        :return:
        """
    result = []
    for line in lines:
        if what not in line:
            result = result + [line]
    return result


def random_vector_2D(vector, sd):
    """Form random orthonormal basis including vector, rotate vector by random
    amount sd in both normal directions."""
    import random
    o0 = vector.ortho()
    o1 = vector.cross(o0)
    return vector.rotate(o0, random.gauss(0, sd)).rotate(o1, random.gauss(0,
        sd))


def replace_labels(axes, cols, labels):
    """
    Sets the the labels of the graph in a proper format. For example removes 'mag' from the old labels

    :param axes: The axes object of the subplot

    :param cols: The names of the cols
    :type cols: list
    :param labels: The new labels
    :type labels: list, dict
    :return:
    """
    if type(labels) == list:
        axes.set_xlabel(labels[0])
        axes.set_ylabel(labels[1])
    elif type(labels) == dict:
        axes.set_xlabel(labels[cols[0]])
        axes.set_ylabel(labels[cols[1]])
    else:
        axes.set_xlabel(cols[0].replace('mag', ''))
        axes.set_ylabel(cols[1].replace('mag', ''))


def google_list_style(style):
    """finds out whether this is an ordered or unordered list"""
    if 'list-style-type' in style:
        list_style = style['list-style-type']
        if list_style in ['disc', 'circle', 'square', 'none']:
            return 'ul'
    return 'ol'


@staticmethod
def list_to_string(recipient):
    """
        Format the recipient for the MIMEMultipart() email type.
        If the recipient is a list, then it returns the list as a
        comma separated string.
        example: input=['you@here.com', 'her@there.com']
                 output='you@there.com, her@there.com'
        """
    if recipient:
        if isinstance(recipient, list):
            return ', '.join(recipient)
        return recipient


@classmethod
def status(cls, options=None):
    """
        Get status of host

        Usage::

            hammer host status [OPTIONS]

        Options::

            --id ID                       resource id
            --name NAME                   resource name
            -h, --help                    print help
        """
    cls.command_sub = 'status'
    result = cls.execute(cls._construct_command(options))
    return result


def hide_tracks_clear():
    """Clear hide selected tracks

    """
    pass


def get_hex(input_list):
    """
        Convert a list of bytes into hex string
    """
    if input_list is None:
        return ''
    o = ''
    for i in input_list:
        o += hex(i) + ' '
    return o[:-1]


def set_pdb_trace(pm=False):
    """Start the Python debugger when robotframework is running.

    This makes sure that pdb can use stdin/stdout even though
    robotframework has redirected I/O.
    """
    import sys
    import pdb
    for attr in ('stdin', 'stdout', 'stderr'):
        setattr(sys, attr, getattr(sys, '__%s__' % attr))
    if pm:
        pdb.post_mortem()
    else:
        pdb.set_trace()


def enable_filter_traceback(enable):
    """Enable/disable replacing asynq boilerplate lines in stacktraces.

    These lines are repeated many times in stacktraces of codebases using asynq.
    By default we replace them so it's easier to read the stacktrace, but you can enable
    if you're debugging an issue where it's useful to know the exact lines.

    """
    global _should_filter_traceback
    _should_filter_traceback = enable


def prepareFixed(query, ftypes, fixed):
    """Called by :meth:`.FileTreeManager.update`. Prepares a dictionary
    which contains all possible values for each fixed variable, and for
    each file type.

    :arg query:  :class:`.FileTreeQuery` object

    :arg ftypes: List of file types to be displayed

    :arg fixed:  List of fixed variables

    :returns:    A dict of ``{ ftype : { var : [value] } }`` mappings
                 which, for each file type, contains a dictionary of
                 all fixed variables and their possible values.
    """
    allvars = query.variables()
    _fixed = {}
    for ftype in ftypes:
        ftvars = query.variables(ftype)
        _fixed[ftype] = {}
        for var in fixed:
            if var in ftvars:
                _fixed[ftype][var] = allvars[var]
    fixed = _fixed
    return fixed


def determine_state(value, warning='', critical=''):
    """Based on `value`, calculate if it is greater or equal either `critical`
    or `warning` and return the corresponding state as an integer of either
    2 (CRITICAL), 1 (WARNING) or 0 (OK)."""
    if isinstance(critical, int) and value >= critical:
        return 2
    if isinstance(warning, int) and value >= warning:
        return 1
    return 0


def aps09_f(x, n):
    """Upside down quartic with parametrizable height"""
    return (1 + (1 - n) ** 4) * x - (1 - n * x) ** 4


def rev_enumerate(sequence):
    """Simple reversed enumerate."""
    n = len(sequence) - 1
    for element in reversed(sequence):
        yield n, element
        n -= 1


@staticmethod
def __no_bin(image, *args, **kwargs):
    """
        Does absolutely nothing to the image.  Exists so that we can have
        a bin function to call whether we actually rebin the image or not.

        Parameters
        ----------
        image : ndarray
            Image
        args:
            Argument list
        kwargs:
            Keyword argument list

        Returns
        -------
        image : ndarray
            The input image
        """
    return image


def remaining_data_length(node=None, parent=None, attr_index=None, rawdata=
    None, new_value=None, *args, **kwargs):
    """
    Size getter for the amount of data left in the rawdata
    starting at kwargs['offset'] + kwargs['root_offset']

    If not provided, offset and root_offset default to 0.
    """
    if new_value is not None:
        return
    if rawdata is not None:
        return len(rawdata) - kwargs.get('offset', 0) + kwargs.get(
            'root_offset', 0)
    elif parent is not None:
        remainder = parent[attr_index]
        try:
            return len(remainder)
        except Exception:
            pass
    return 0


@classmethod
def normalize_name(cls, name):
    """
        Replace some characters in command names.
        """
    return name.lower().replace('_', '-').replace(' ', '-')


@classmethod
def dot(cls, value):
    """
        Dot notation, `such.as.this`
        """
    return cls.separator(value=cls.normalize(value), separator='.')


@staticmethod
def _prepend_required(help_text, required):
    """
        Returns the passed help text prepended with "Optional. " or "Mandatory. ",
        based on the value of the passed 'required' param. If the passed help text
        is 'None' or blank, then returns the help text as is.

        :param help_text: Text to perhaps prepend
        :param required:  True if the option is required, else False - the
        option is not required to be provided on the command line

        :return: The value of 'help_text', potentially prepended as described.
        """
    if not help_text or len(help_text.strip()) == 0:
        return help_text
    else:
        return ('Mandatory. ' if required else 'Optional. ') + help_text


def nth_combination(iterable, r, index):
    """Equivalent to ``list(combinations(iterable, r))[index]``.

    The subsequences of *iterable* that are of length *r* can be ordered
    lexicographically. :func:`nth_combination` computes the subsequence at
    sort position *index* directly, without computing the previous
    subsequences.

    """
    pool = tuple(iterable)
    n = len(pool)
    if r < 0 or r > n:
        raise ValueError
    c = 1
    k = min(r, n - r)
    for i in range(1, k + 1):
        c = c * (n - k + i) // i
    if index < 0:
        index += c
    if index < 0 or index >= c:
        raise IndexError
    result = []
    while r:
        c, n, r = c * r // n, n - 1, r - 1
        while index >= c:
            index -= c
            c, n = c * (n - r) // n, n - 1
        result.append(pool[-1 - n])
    return tuple(result)


def replace_all(text, d):
    """Allows you to replace multiple strings. It uses the key of the given dictionary d to match a string in the text
    and the associated value as replacement. E.g. d = {"hi": "bye", "no": "yes"} will replace hi with bye and no with
    yes."""
    for i, j in d.items():
        text = text.replace(i, j)
    return text


@classmethod
def attempt_convert_uuid_hex_to_bytes(cls, value):
    """Attempt to convert value to bytes or return value.

        :param value: value to attempt to convert to bytes
        :returns: tuple containing boolean indicating whether user_id was
                  stored as bytes and uuid value as bytes or the original value

        """
    try:
        return True, cls.convert_uuid_hex_to_bytes(value)
    except (ValueError, TypeError):
        return False, value


def revcomp(dna):
    """reverse complement DNA sequences"""
    tab = str.maketrans('ACGTNX*-', 'TGCANX*-')
    return dna.upper().translate(tab)[::-1]


def sequence_minus(seq1, seq2):
    """Calculate difference of two sequences.

    Result contains the elements from first sequence that are not
    present in second sequence, in original order. Works even
    if sequence elements are not hashable.
    """
    result = list(seq1)
    for item in seq2:
        try:
            result.remove(item)
        except ValueError:
            pass
    return result


@classmethod
def create(cls, node=None, nickname=None, **kwargs):
    """Create a subnets record in API and corresponding Subnet instance.

        Args:
            node (BaseNode): the node from which the subnet belongs
            nickname (str): nickname of subnet

        Returns:
            Subnet: a new Subnet instance
        """
    payload = cls.payload_for_create(nickname, **kwargs)
    response = node.user.client.subnets.create(node.user.id, node.id, payload)
    return cls.from_response(node, response)


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 addValueToPoints(valuestring, points):
    """Adds the collected character string to the last coordinate
    in the points list."""
    if not valuestring:
        return
    value = float(valuestring)
    if not points or len(points[-1]) == 2:
        points.append([])
    points[-1].append(value)


def _fragment(div, eps):
    """Create a list of grids."""
    grids = []
    for lat in range(div):
        for log in range(div):
            init = [1.0 / div * lat, 1.0 / div * log]
            end = [1.0 / div * (lat + 1) + 2 * eps, 1.0 / div * (log + 1) +
                2 * eps]
            end2 = [1.0 / div * (lat + 1), 1.0 / div * (log + 1)]
            grids.append([init, end, end2])
    return grids


def di(data):
    """
    Delete imaginary from data

    Parameters
    ----------
    data : ndarray
        Array of NMR data.

    Returns
    -------
    ndata : ndarray
        Array of NMR data without imaginaries.

    """
    return data.real


def _is_x_first_dim(dim_order):
    """Determine whether x is the first dimension based on the value of dim_order."""
    if dim_order is None:
        dim_order = 'yx'
    return dim_order == 'xy'


def golf():
    """
    Full factorial experiments to maximize a golfer's driving distance.

    A full factorial experiment with four factors run by a golf enthusiast. The
    objective of the experiments was for the golfer to maximize her driving distance
    at a specific tee off location on her local golf course. The golfer considered
    the following factors:

    H = Tee height (cm)
    N = Holes: number of golf balls played for prior to experimental tee shot
    C = Club type
    T = Time of day (on the 24 hour clock)

    The data are in standard order, however the actual experiments were run in
    random order.

    Coded values for H, N, C and T should be used in the linear regression
    model analysis, with -1 representing the low value and +1 the high value.

    Dimensions
    ----------
    A data frame containing 16 observations of 4 variables (H, N, C, T) and a
    column y, as a response variable.

    Source
    ------
    A MOOC on Design of Experiments: ``Experimentation for Improvement'',
    https://learnche.org

    Example
    -------
    """
    pass


def kwargs_to_string(kwargs):
    """
    Given a set of kwargs, turns them into a string which can then be passed to a command.
    :param kwargs: kwargs from a function call.
    :return: outstr: A string, which is '' if no kwargs were given, and the kwargs in string format otherwise.
    """
    outstr = ''
    for arg in kwargs:
        outstr += ' -{} {}'.format(arg, kwargs[arg])
    return outstr


def bech32_polymod(values):
    """Internal function that computes the Bech32 checksum."""
    generator = [996825010, 642813549, 513874426, 1027748829, 705979059]
    chk = 1
    for value in values:
        top = chk >> 25
        chk = (chk & 33554431) << 5 ^ value
        for i in range(5):
            chk ^= generator[i] if top >> i & 1 else 0
    return chk


def _to_int(byte_string):
    """ convert a string of bytes(in least significant byte order) to int """
    return int(byte_string[::-1].encode('hex'), 16)


def mysql_datetime(dt):
    """Datetime formatted to be digestible by MySQL"""
    return dt.strftime('%Y-%m-%d %H:%M:%S')


def load_PySide_QtCore(finder, module):
    """PySide.QtCore dynamically loads the stdlib atexit module."""
    finder.IncludeModule('atexit')


@classmethod
def _parse_value(cls, stream_rdr, offset, value_count, value_offset):
    """
        Return the value of this field parsed from *stream_rdr* at *offset*.
        Intended to be overridden by subclasses.
        """
    return 'UNIMPLEMENTED FIELD TYPE'


def clear():
    """
        removes all pending items, and returns a list of mapping objects
        """


def html(filename='index.html'):
    """
    Returns a simple HTML5 template.
    """
    with open(filename, 'w') as f:
        f.write(
            """<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>

</body>
</html>"""
            )


def Identity(v):
    """ Identity function.

    Special `identity` function which matches everything.
    Is primarily used for the `Extra` marker, as well as all other markers specified as classes.
    """
    return v


def getColorRange(x):
    """ Determines the range of colors, centered at zero, for normalizing cmap """
    vmax = x.max()
    vmin = x.min()
    if vmax < 0 and vmin < 0:
        direction = 'negative'
    elif vmax > 0 and vmin > 0:
        direction = 'positive'
    else:
        direction = 'both'
    if direction == 'both':
        vmax = max([vmax, abs(vmin)])
        vmin = -1 * vmax
        return vmax, vmin
    else:
        return vmax, vmin


def to_bash_variable(param: str) ->str:
    """
        Convert a command variable in a bash variable
    """
    return param.upper().replace('-', '_')


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

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

    """
    pass


def is_emulator(cls):
    """Emulator needs to be configured."""
    return cls.device_name in ('emulator', 'emulator-jb')


def run():
    """ Entry-point script for execution"""


def getStatusChangeTime():
    """
        Retrieve the time of the last status change for this file.

        @return: a number of seconds from the epoch.
        @rtype: L{float}
        """


def get_glove_vocab(filename):
    """Load vocab from file

    Args:
        filename: path to the glove vectors

    Returns:
        vocab: set() of strings
    """
    print('Building vocab...')
    vocab = set()
    with open(filename) as f:
        for line in f:
            word = line.strip().split(' ')[0]
            vocab.add(word)
    print('- done. {} tokens'.format(len(vocab)))
    return vocab


def setPrefix(prefix):
    """Set the `prefix` used for names of input elements

        Element names should begin with the given `prefix`,
        followed by a dot.
        """