def default_user_validator(request, username, password):
    """
    Validate the username/password. This is c2cgeoportal's
    default user validator.
    Return none if we are anonymous, the string to remember otherwise.
    """
    from c2cgeoportal.models import DBSession, User
    user = DBSession.query(User).filter_by(username=username).first()
    return username if user and user.validate_password(password) else None


def write(packet, addr=None):
    """
        Write packet to given address.

        @param addr: a tuple of (ip, port). For connected transports must
                     be the address the transport is connected to, or None.
                     In non-connected mode this is mandatory.

        @raise twisted.internet.error.MessageLengthError: C{packet} was too
        long.
        """


def init_thread(i, r, d):
    """
    to initialise multithreaded worker
    """
    global indexes_count, reindexed_count, deleted_count
    indexes_count = i
    reindexed_count = r
    deleted_count = d


@staticmethod
def compute(mechanism, subsystem, purviews, cause_purviews, effect_purviews):
    """Compute a |Concept| for a mechanism, in this |Subsystem| with the
        provided purviews.
        """
    concept = subsystem.concept(mechanism, purviews=purviews,
        cause_purviews=cause_purviews, effect_purviews=effect_purviews)
    concept.subsystem = None
    return concept


def _update_context(context, postdata):
    """
    Updates the default selections with user's selections.
    """
    listCheck = lambda el: el[0] if type(el) == list else el
    widget_id = listCheck(postdata.get('widget_id'))
    context.target_table = listCheck(postdata.get('target_table%s' % widget_id)
        )
    context.target_att = listCheck(postdata.get('target_att%s' % widget_id))
    context.tables = postdata.get('tables%s' % widget_id, [])
    if context.target_table not in context.tables:
        raise Exception(
            'The selected target table "%s" is not among the selected tables.'
             % context.target_table)
    for table in context.cols.keys():
        if table not in context.tables:
            del context.cols[table]
    for pair in context.connected.keys():
        if pair[0] in context.tables and pair[1] in context.tables:
            continue
        del context.connected[pair]
    for table in context.tables:
        context.cols[table] = postdata.get('%s_columns%s' % (table,
            widget_id), [])
        if (table == context.target_table and context.target_att not in
            context.cols[table]):
            raise Exception(
                'The selected target attribute ("%s") is not among the columns selected for the target table ("%s").'
                 % (context.target_att, context.target_table))
    if context.in_memory:
        context.orng_tables = None
        context.orng_tables = context.read_into_orange()


def broadcast_minimum(lhs=None, rhs=None, out=None, name=None, **kwargs):
    """Returns element-wise minimum of the input arrays with broadcasting.

    This function compares two input arrays and returns a new array having the element-wise minima.

    Example::

       x = [[ 1.,  1.,  1.],
            [ 1.,  1.,  1.]]

       y = [[ 0.],
            [ 1.]]

       broadcast_maximum(x, y) = [[ 0.,  0.,  0.],
                                  [ 1.,  1.,  1.]]

    Defined in src/operator/tensor/elemwise_binary_broadcast_op_extended.cc:L117

    Parameters
    ----------
    lhs : NDArray
        First input to the function
    rhs : NDArray
        Second input to the function

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

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


def rgb_to_hsl(r, g, b):
    """
    Converts an RGB color value to HSL.
    :param r: The red color value
    :param g: The green color value
    :param b: The blue color value
    :return: The HSL representation
    """
    r = float(r) / 255.0
    g = float(g) / 255.0
    b = float(b) / 255.0
    max_value = max(r, g, b)
    min_value = min(r, g, b)
    h = None
    s = None
    l = (max_value + min_value) / 2
    d = max_value - min_value
    if d == 0:
        h = 0
        s = 0
    else:
        s = d / (1 - abs(2 * l - 1))
        if r == max_value:
            h = 60 * ((g - b) % 6)
            if b > g:
                h += 360
        if g == max_value:
            h = 60 * ((b - r) / d + 2)
        if b == max_value:
            h = 60 * ((r - g) / d + 4)
    return round(h, 2), round(s, 2), round(l, 2)


def snap_selected_to_cursor(use_offset: bool=True):
    """Snap selected item(s) to the 3D cursor

    :param use_offset: Offset, If the selection should be snapped as a whole or by each object center
    :type use_offset: bool
    """
    pass


def void_function(*arg, **kw):
    """A function that accepts any number of parameters and does nothing"""
    pass


def is_quantity(val):
    """Is ``val`` a quantity (int, float, datetime, etc) (not str, bool)?

    Relies on presence of __sub__.
    """
    return hasattr(val, '__sub__')


def _singlethread_iteration(selection_iterator, scoring_fn):
    """Handles a single pass of the abstract variable importance algorithm,
    assuming a single worker thread

    :param selection_iterator: an iterator which yields triples
        ``(variable, training_data, scoring_data)``. Typically a
        :class:`PermutationImportance.selection_strategies.SelectionStrategy`
    :param scoring_fn: a function to be used for scoring. Should be of the form
        ``(training_data, scoring_data) -> float``
    :returns: a dict of ``{var: score}``
    """
    result = dict()
    for var, training_data, scoring_data in selection_iterator:
        score = scoring_fn(training_data, scoring_data)
        result[var] = score
    return result


def div_sqrt_dim(data=None, name=None, attr=None, out=None, **kwargs):
    """Rescale the input by the square root of the channel dimension.

       out = data / sqrt(data.shape[-1])

    Defined in src/operator/contrib/transformer.cc:L833

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

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

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


def apply_slice(img, crop_slice):
    """Apply cropping slice to trailing image dimensions"""
    if img.ndim < 2:
        raise ValueError(
            'Expecting at least 2 dimensions in image (shape of given array = {})'
            .format(img.shape))
    slices = [slice(None, None) for _ in range(img.ndim - 2)] + crop_slice
    return img[slices]


def get_any_key(x):
    """ Returns a key from a dictionary.

		# Arguments:

		x: dict. The dictionary to pull a key from.

		# Return value

		If x is empty, returns None; otherwise, this returns a key from the
		dictionary.
	"""
    if x:
        for k in x:
            return k
    else:
        return None


def _check_type(value, expected_type):
    """! @brief Perform type checking on the provided value

    This is a helper that will raise ``TypeError`` if the provided value is
    not an instance of the provided type.  This method should be used sparingly
    but can be good for preventing problems earlier when you want to restrict
    duck typing to make the types of fields more obvious.

    If the value passed the type check it will be returned from the call.
    """
    if not isinstance(value, expected_type):
        raise TypeError(
            'Value {value!r} has unexpected type {actual_type!r}, expected {expected_type!r}'
            .format(value=value, expected_type=expected_type, actual_type=
            type(value)))
    return value


def _get_bug_attr(bug, attr):
    """Default longdescs/flags case to [] since they may not be present."""
    if attr in ('longdescs', 'flags'):
        return getattr(bug, attr, [])
    return getattr(bug, attr)


def parent_clear():
    """Clear the mask’s parenting

    """
    pass


def escape_attribute(value, encoding):
    """Escape an attribute value using the given encoding."""
    if '&' in value:
        value = value.replace('&', '&')
    if '<' in value:
        value = value.replace('<', '<')
    if '"' in value:
        value = value.replace('"', '"')
    return value.encode(encoding, 'xmlcharrefreplace')


@staticmethod
def _idgen_sources(group_id, subject_number):
    """
        Identifiers generator
        :param gid: group ID
        :param subn: subject ID
        :return: str
        """
    idarr = []
    if group_id != '':
        idarr.append('GRP-{}'.format(group_id))
    if subject_number != '':
        idarr.append('SBJ-{}'.format(subject_number))
    return '.'.join(idarr).replace(' ', '_')


def button_select_released(controller):
    """
    Callback function that is triggered, when the select button was released

    :param controller:              the controller that triggered the action
    :type controller:               steuer.Controller
    """
    print('ACTION:' + str(controller.number) + ':' + controller.name +
        ':Button Select released')


def string_to_num(s: str):
    """Converts a string to an int/float

    Returns ``None`` if it can't be converted

    >>> string_to_num('5')
    5
    >>> string_to_num('5.2')
    5.2
    >>> string_to_num(10)
    10
    >>> string_to_num(10.1)
    10.1
    >>> string_to_num('this is not a string') is None
    True
    """
    if isinstance(s, (int, float)):
        return s
    if s.isdigit():
        return int(s)
    try:
        return float(s)
    except ValueError:
        return None


def cut(value):
    """Cut values in graphics primitives (not displayed otherwise in SVG)"""
    border = 10 ** 8
    if value < -border:
        value = -border
    elif value > border:
        value = border
    return value


def get_title(doc):
    """Get title of doc"""
    if not doc:
        return ''
    lines = doc.strip('\n').split('\n', maxsplit=1)
    title = lines[0].strip()
    if len(title) > 30:
        title = title[:30] + '...'
    return title


def is_iterable(obj):
    """
    Test if the given object is iterable

    :param obj: an object
    :return: True if obj is iterable, False otherwise
    """
    try:
        _ = iter(obj)
        return True
    except TypeError:
        return False


def _read(fname):
    """ Read data from file """
    with open(fname, 'r', newline='\r\n') as frobj:
        return frobj.read()


def keyframe_clear_v3d():
    """Remove all keyframe animation for selected objects

    """
    pass


def block_splitter(data, block_size):
    """
    Creates a generator by slicing ``data`` into chunks of ``block_size``.

    >>> data = range(10)
    >>> list(block_splitter(data, 2))
    [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9]]

    If ``data`` cannot be evenly divided by ``block_size``, the last block will
    simply be the remainder of the data. Example:

    >>> data = range(10)
    >>> list(block_splitter(data, 3))
    [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]

    If the ``block_size`` is greater than the total length of ``data``, a
    single block will be generated:

    >>> data = range(3)
    >>> list(block_splitter(data, 4))
    [[0, 1, 2]]

    :param data:
        Any iterable. If ``data`` is a generator, it will be exhausted,
        obviously.
    :param int block_site:
        Desired (maximum) block size.
    """
    buf = []
    for i, datum in enumerate(data):
        buf.append(datum)
        if len(buf) == block_size:
            yield buf
            buf = []
    if buf:
        yield buf


def get_meta(df):
    """
    Return the metadata from a single dataframe
    :param df: cudf.dataframe
    :return: Row data from the first row of the dataframe
    """
    ret = df.iloc[:0]
    return ret


def can_access(user):
    """define who can access"""
    return user.is_authenticated and user.is_staff


def basename(path):
    """Use for Windows compatibility.

    """
    pass


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

        :param SsoRemoveLoginUrlDetails val:
        :rtype: EventDetails
        """
    return cls('sso_remove_login_url_details', val)


def update(d):
    """
        Merge dictionary d into ourselves.
        """


def get_layout_characteristics(n2lo):
    """
    Checks the layout values for all the elements and finds the coordinates of the top left corner,
    the width and the height or the area containing the graph and the height of the minimal element.
    :param n2lo: node layout as a dictionary    {node_id: ((x, y), (w, h)) if node is not ubiquitous
                                                else node_id : {r_ids: ((x, y), (w, h)) for r_ids of
                                                reactions using each duplicated metabolite}}
    :return: h_min, (x_min, y_min), (w, h): the height of the minimal element, the coordinates of the top left corner,
                                            the width and the height or the area containing the graph.
    """
    x_min, y_min, x_max, y_max, h_min = None, None, None, None, None
    for v in n2lo.values():
        if not isinstance(v, dict):
            v = {'': v}
        for (x, y), (w, h) in v.values():
            if x_min is None or x - w / 2 < x_min:
                x_min = x - w / 2
            if x_max is None or x + w / 2 > x_max:
                x_max = x + w / 2
            if y_min is None or y - h / 2 < y_min:
                y_min = y - h / 2
            if y_max is None or y + h / 2 > y_max:
                y_max = y + h / 2
            if h_min is None or h < h_min:
                h_min = h
    w, h = x_max - x_min, y_max - y_min
    return h_min, (x_min, y_min), (w, h)


def select_circle(x: int=0, y: int=0, radius: int=1, gesture_mode: int=0):
    """Select curve points using circle selection

    :param x: X
    :type x: int
    :param y: Y
    :type y: int
    :param radius: Radius
    :type radius: int
    :param gesture_mode: Gesture Mode
    :type gesture_mode: int
    """
    pass


def register_translation(language, content):
    """
        register an existing content as translation
        for context
        """


def profile(ob):
    """
    Comment out this function to be able to use the line_profiler module. e.g. call:
    kernprof -l scripts/deploy_summariser.py --loglevel=10
    python -m line_profiler deploy_summariser.py.lprof > deploy_summariser.py.summary
    :param ob: object
    :return: object
    """
    return ob


def get_messages(request):
    """
    Return the message storage on the request if it exists, otherwise return
    an empty list.
    """
    return getattr(request, '_messages', [])


def repr_timespan(start, end) ->str:
    """return a string representing the timespan.

    Returns:
        a string like #h#m

    """
    duration = end - start
    hours = duration.seconds // 3600
    minutes = (duration.seconds - hours * 3600) // 60
    hours += duration.days * 24
    return '{}:{:02}'.format(hours, minutes)


def _pesummary_metafile_command_line_options(parser):
    """Add command line options which are specific for reading and
    manipulating pesummary metafiles

    Parameters
    ----------
    parser: object
        OptionParser instance
    """
    pesummary_group = parser.add_argument_group(
        """Options specific for reading and manipulating pesummary metafiles
-----------------------------------------------------------------"""
        )
    pesummary_group.add_argument('--compare_results', dest=
        'compare_results', nargs='+', default=None, help=
        'labels for events stored in the posterior_samples.json that you wish to compare'
        )
    pesummary_group.add_argument('--save_to_json', action='store_true',
        default=False, help='save the meta file in json format')
    return pesummary_group


def error_status(e):
    """Return the HTTP status code associated with an exception"""
    codes = {'ZoomError': 400, 'ValueError': 400, 'RuntimeError': 500,
        'UnicodeDecodeError': 500}
    name = e.__class__.__name__
    if name not in codes.keys():
        return 500
    return codes[name]


def close():
    """
        Close connection
        """


def vertex_group_mirror(mirror_weights: bool=True, flip_group_names: bool=
    True, all_groups: bool=False, use_topology: bool=False):
    """Mirror vertex group, flip weights and/or names, editing only selected vertices, flipping when both sides are selected otherwise copy from unselected

    :param mirror_weights: Mirror Weights, Mirror weights
    :type mirror_weights: bool
    :param flip_group_names: Flip Group Names, Flip vertex group names
    :type flip_group_names: bool
    :param all_groups: All Groups, Mirror all vertex groups weights
    :type all_groups: bool
    :param use_topology: Topology Mirror, Use topology based mirroring (for when both sides of mesh have matching, unique topology)
    :type use_topology: bool
    """
    pass


def is_mutating(status):
    """Determines if the statement is mutating based on the status."""
    if not status:
        return False
    mutating = set(['insert', 'update', 'delete'])
    return status.split(None, 1)[0].lower() in mutating


def _call_gabwin(g, a, M, L):
    """ Internal use only """
    from ltfatpy.gabor.gabwin import gabwin
    return gabwin(g, a, M, L)


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

    @param argv list of commandline parameters (list of strings)
    @return reference to the main widget (QWidget)
    """
    from PluginManager.PluginInstallDialog import PluginInstallWindow
    return PluginInstallWindow(argv[1:])


def roi_array_to_dict(a):
    """Convert the `ROIs` structured arrays to :py:class:`dict`

    Parameters
    ----------
    a : numpy.ndarray
        Structured array containing ROI data

    Returns
    -------
    list of dict
        One dict per ROI. Keys are "top_left", "bottom_right", and "bin",
        values are tuples whose first element is the x axis value and the
        second element is the y axis value.
    """
    l = []
    a = a[['startx', 'starty', 'endx', 'endy', 'groupx', 'groupy']]
    for sx, sy, ex, ey, gx, gy in a:
        d = {'top_left': [int(sx), int(sy)], 'bottom_right': [int(ex), int(
            ey)], 'bin': [int(gx), int(gy)]}
        l.append(d)
    return l


@staticmethod
def format_time(seconds):
    """
        Converts seconds into seconds, minutes:seconds, or
        hours:minutes.seconds as appropriate.
        """
    try:
        minutes, seconds = divmod(float(seconds), 60)
        hours, minutes = divmod(minutes, 60)
        return_value = int(hours), int(minutes), float(seconds)
        if hours:
            return '{0:d}:{1:0>2d}:{2:0>6.3f}'.format(*return_value)
        elif minutes:
            return '{1:d}:{2:0>6.3f}'.format(*return_value)
        else:
            return '{2:.3f}'.format(*return_value)
    except (TypeError, ValueError):
        return ''


def psi_K_Br_OH_PK74(T, P):
    """c-a-a': potassium bromide hydroxide [PK74]."""
    psi = -0.014
    valid = T == 298.15
    return psi, valid


def data_source_types():
    """Returns a list of the supported data source types"""
    return ['FlatfileDataset', 'XpathDataset', 'MatrixDataset',
        'SpreadsheetDataset', 'RDBMSDataset', 'FilesDataset']


def pretty_size_print(num_bytes):
    """
    Output number of bytes in a human readable format

    keywords
    --------
    num_bytes: int
        number of bytes to convert

    returns
    -------
    output: str
        string representation of the size with appropriate unit scale
    """
    if num_bytes is None:
        return
    KiB = 1024
    MiB = KiB * KiB
    GiB = KiB * MiB
    TiB = KiB * GiB
    PiB = KiB * TiB
    EiB = KiB * PiB
    ZiB = KiB * EiB
    YiB = KiB * ZiB
    if num_bytes > YiB:
        output = '%.3g YB' % (num_bytes / YiB)
    elif num_bytes > ZiB:
        output = '%.3g ZB' % (num_bytes / ZiB)
    elif num_bytes > EiB:
        output = '%.3g EB' % (num_bytes / EiB)
    elif num_bytes > PiB:
        output = '%.3g PB' % (num_bytes / PiB)
    elif num_bytes > TiB:
        output = '%.3g TB' % (num_bytes / TiB)
    elif num_bytes > GiB:
        output = '%.3g GB' % (num_bytes / GiB)
    elif num_bytes > MiB:
        output = '%.3g MB' % (num_bytes / MiB)
    elif num_bytes > KiB:
        output = '%.3g KB' % (num_bytes / KiB)
    else:
        output = '%.3g Bytes' % num_bytes
    return output


def write_config(directory='.', ed_solver=1, num_val_orbs=2, num_core_orbs=
    2, neval=1, nvector=1, ncv=1, idump=True, num_gs=1, maxiter=500,
    linsys_max=1000, min_ndim=1000, nkryl=500, eigval_tol=1e-08, linsys_tol
    =1e-10, omega_in=0.0, gamma_in=0.1):
    """
    Write control parameters in config.in file for ed_fsolver.
    """
    if idump:
        dump_vector = '.true.'
    else:
        dump_vector = '.false.'
    config = ['&control', 'ed_solver=' + str(ed_solver), 'num_val_orbs=' +
        str(num_val_orbs), 'num_core_orbs=' + str(num_core_orbs), 'neval=' +
        str(neval), 'nvector=' + str(nvector), 'ncv=' + str(ncv), 'idump=' +
        str(dump_vector), 'num_gs=' + str(num_gs), 'maxiter=' + str(maxiter
        ), 'linsys_max=' + str(linsys_max), 'min_ndim=' + str(min_ndim),
        'nkryl=' + str(nkryl), 'eigval_tol=' + str(eigval_tol),
        'linsys_tol=' + str(linsys_tol), 'omega_in=' + str(omega_in),
        'gamma_in=' + str(gamma_in), '&end']
    f = open(directory + '/config.in', 'w')
    for item in config:
        f.write(item + '\n')
    f.close()


@classmethod
def _get_value_from_string(cls, string):
    """
        Receives a left stripped string, identifies the heading value, decodes it,
        and returns a tuple (key, rest of the string)

        :param unicode string: substring of connection string
        :returns: rest of string left stripped and without any leading ';'
        :rtype: unicode
        :raises: ValueError

        """
    first = string[0]
    if first not in cls._quotes:
        value, _, string = string.partition(';')
        return value.rstrip(), string
    start = 1
    while True:
        pos = string.find(first, start)
        if pos == -1:
            raise ValueError('Token delimiter not found: "%s"' % first)
        if string[pos] == string[pos + 1]:
            start = pos + 2
            continue
        value, rest = string[:pos + 1], string[pos + 1:]
        return cls._decode_value(value.rstrip()), rest.lstrip(' ;')


@classmethod
def register_errorhandler(cls, app):
    """Register the standard error handler for this exception on this App.

        This will set :meth:`errorhandler_callback` as an error handler for
        this exception. This means all exceptions that inherit from this class
        will be caught by that error handler.

        This method does nothing other than registration and the actual
        implementation of the callback is found in
        :meth:`errorhandler_callback`. If you want a custom exception derived
        from this exception to run a custom callback, please override
        :meth:`errorhandler_callback`, and continue to use this function to
        register.

        Example usage:

        .. code:: python

            from fleaker import AppException

            def create_app():
                app = fleaker.App(__name__)

                # this will register the standard callback
                AppException.register_errorhandler(app)

                class MyException(AppException):
                    ""\"Has a custom handler callback.""\"

                    @classmethod
                    def errorhandler_callback(cls, exc):
                        ""\"Custom error handler that greets the user.""\"
                        return 'Hi'

                # now whenever MyException or it's sub-classes are thrown, the
                # user will get `Hi` back
                MyException.register_errorhandler(app)

        Args:
            app (flask.Flask):
                The Flask application to register the standard handler callback
                to.

        Returns:
            fleaker.exceptions.FleakerBaseException:
                Returns the same class this was called on, to provide a fluent
                interface (e.g., register error handlers on multiple apps in
                one method chain).
        """
    app.errorhandler(cls)(cls.errorhandler_callback)
    return app


def first_element(storage, loc):
    """Returns the first element of two"""
    return storage


def get_styles():
    """Returns a dict containing all configured styles.

        :returns: Current custom styles on the context.
        :rtype: dict
        """


def exists(segments):
    """
        Return True if segments points to an existing path.
        """


@classmethod
def _add_operation_bundling_arg_group(cls, parser):
    """Add argument group to parser for operation bundling."""
    bundling_group = parser.add_argument_group('bundling',
        'Bundle multiple operations for execution, e.g., to submit them all together to a cluster job, or execute them in parallel within an execution script.'
        )
    bundling_group.add_argument('-b', '--bundle', type=int, nargs='?',
        const=0, default=1, dest='bundle_size', help=
        'Bundle multiple operations for execution in a single scheduler job. When this option is provided without argument,  all pending operations are aggregated into one bundle.'
        )
    bundling_group.add_argument('-p', '--parallel', action='store_true',
        help='Execute all operations within a single bundle in parallel.')


def segemehl_parse(fusion, out):
    """
    Parse fusion junctions from segemehl aligner
    """
    print('Start parsing fusion junctions from segemehl...')
    total = 0
    with open(fusion, 'r') as junc_f, open(out, 'w') as outf:
        for i, line in enumerate(junc_f):
            chrom, start, end, info = line.split()[:4]
            if not info.endswith('C:P'):
                continue
            reads = info.split(':')[1]
            start = str(int(start) - 1)
            outf.write('\t'.join([chrom, start, end,
                'FUSIONJUNC_%d/%s\t+\n' % (i, reads)]))
            total += int(reads)
    print('Converted %d fusion reads!' % total)


def run_with_stack_context(context, func):
    """Run a coroutine ``func`` in the given `StackContext`.

    It is not safe to have a ``yield`` statement within a ``with StackContext``
    block, so it is difficult to use stack context with `.gen.coroutine`.
    This helper function runs the function in the correct context while
    keeping the ``yield`` and ``with`` statements syntactically separate.

    Example::

        @gen.coroutine
        def incorrect():
            with StackContext(ctx):
                # ERROR: this will raise StackContextInconsistentError
                yield other_coroutine()

        @gen.coroutine
        def correct():
            yield run_with_stack_context(StackContext(ctx), other_coroutine)

    .. versionadded:: 3.1
    """
    with context:
        return func()


def embed_standard_shell(namespace=None, banner='', history_filename=None):
    """Start a standard python shell"""
    import code
    try:
        import readline
    except ImportError:
        pass
    else:
        import rlcompleter
        readline.parse_and_bind('tab:complete')
    code.interact(banner=banner, local=namespace)


@classmethod
def get(cls):
    """Returns an instance of the communicator"""
    raise NotImplementedError('get is not implemented')


def select_border(gesture_mode: int=0, xmin: int=0, xmax: int=0, ymin: int=
    0, ymax: int=0, extend: bool=True, axis_range: bool=False,
    include_handles: bool=False):
    """Select all keyframes within the specified region

    :param gesture_mode: Gesture Mode
    :type gesture_mode: int
    :param xmin: X Min
    :type xmin: int
    :param xmax: X Max
    :type xmax: int
    :param ymin: Y Min
    :type ymin: int
    :param ymax: Y Max
    :type ymax: int
    :param extend: Extend, Extend selection instead of deselecting everything first
    :type extend: bool
    :param axis_range: Axis Range
    :type axis_range: bool
    :param include_handles: Include Handles, Are handles tested individually against the selection criteria
    :type include_handles: bool
    """
    pass


@classmethod
def auth(cls, username, raw_password):
    """验证用户登录。如果登录成功，返回用户"""
    obj = cls.query.filter_by(username=username).first()
    if obj and obj.check_password(raw_password):
        return obj
    else:
        return None


def yield_batch(iterable, batch_size, num_tensors=1):
    """Generator that yields batches of a DataFrame iterator.

  Args:
    :iterable: Spark partition iterator.
    :batch_size: number of items to retrieve per invocation.
    :num_tensors: number of tensors (columns) expected in each item.

  Returns:
    An array of ``num_tensors`` arrays, each of length `batch_size`
  """
    tensors = [[] for i in range(num_tensors)]
    for item in iterable:
        if item is None:
            break
        for i in range(num_tensors):
            tmp = str(item[i]) if type(item[i]) is bytearray else item[i]
            tensors[i].append(tmp)
        if len(tensors[0]) >= batch_size:
            yield tensors
            tensors = [[] for i in range(num_tensors)]
    if len(tensors[0]) > 0:
        yield tensors


@staticmethod
def _termial_function(n: int) ->int:
    """Compute termial function, with red hats off to Donald Knuth.

        Termial function is:

          \\sum_{k=0}^n k

        Let's use arithmetic progression to get termial of n.
        """
    if n < 0:
        raise ValueError('Termial function used with negative number')
    return int((1 + n) * (n / 2))


def list_group_policies(GroupName=None, Marker=None, MaxItems=None):
    """
    Lists the names of the inline policies that are embedded in the specified IAM group.
    An IAM group can also have managed policies attached to it. To list the managed policies that are attached to a group, use  ListAttachedGroupPolicies . For more information about policies, see Managed Policies and Inline Policies in the IAM User Guide .
    You can paginate the results using the MaxItems and Marker parameters. If there are no inline policies embedded with the specified group, the action returns an empty list.
    See also: AWS API Documentation

    Examples
    The following command lists the names of in-line policies that are embedded in the IAM group named Admins.
    Expected Output:

    :example: response = client.list_group_policies(
        GroupName='string',
        Marker='string',
        MaxItems=123
    )

    :type GroupName: string
    :param GroupName: [REQUIRED]
            The name of the group to list policies for.
            This parameter allows (per its regex pattern ) a string of characters consisting of upper and lowercase alphanumeric characters with no spaces. You can also include any of the following characters: =,.@-

    :type Marker: string
    :param Marker: Use this parameter only when paginating results and only after you receive a response indicating that the results are truncated. Set it to the value of the Marker element in the response that you received to indicate where the next call should start.

    :type MaxItems: integer
    :param MaxItems: (Optional) Use this only when paginating results to indicate the maximum number of items you want in the response. If additional items exist beyond the maximum you specify, the IsTruncated response element is true .
            If you do not include this parameter, it defaults to 100. Note that IAM might return fewer results, even when there are more results available. In that case, the IsTruncated response element returns true and Marker contains a value to include in the subsequent call that tells the service where to continue from.

    :rtype: dict
    :return: {
        'PolicyNames': [
            'string',
        ],
        'IsTruncated': True|False,
        'Marker': 'string'
    }

    :returns:
    (string) --

    """
    pass


def determine_datatype(path):
    """
    Determine if plaintext, tokens or parsed XML
    """
    import os
    from collections import Counter
    exts = []
    if not os.path.isdir(path) and not os.path.isfile(path):
        raise ValueError("Corpus path '%s' doesn't exist." % path)
    singlefile = False
    if os.path.isfile(path):
        singlefile = True
        if '.' in path:
            exts = [os.path.splitext(path)[1]]
        else:
            exts = ['.txt']
    else:
        for root, dirs, fs in os.walk(path):
            for f in fs:
                if '.' in f:
                    ext = os.path.splitext(f)[1]
                    exts.append(ext)
    counted = Counter(exts)
    counted.pop('', None)
    try:
        mc = counted.most_common(1)[0][0]
    except IndexError:
        mc = '.txt'
    lookup = {'.txt': 'plaintext', '.conll': 'conll', '.conllu': 'conll'}
    return lookup.get(mc, 'plaintext'), singlefile


@staticmethod
def _parse_instance_info(node):
    """Gets the instance specific Node deployment info.

        This method validates whether the 'instance_info' property of the
        supplied node contains the required or optional information properly
        for this driver to deploy images to the node.

        :param node: a target node of the deployment
        :returns:  the instance_info values of the node.
        :raises: InvalidParameterValue, if any of the parameters have invalid
            value.
        """
    deploy_info = node.instance_info.copy()
    return deploy_info


@classmethod
def wrap(cls, instance):
    """Wrap an object instance.

        The wrapped object does not need to derive from :class:`dbusx.Object`.
        Wrapping an object allows you to expose an existing object hierarchy on
        D-BUS without changing it to inherit from :class:`dbusx.Object`.
        """
    self = cls()
    self.wrapped = instance
    return self


def getSubDict(name, dict_, sep=u'_'):
    """get a sub dictionary from a serialised dictionary

    look for keys starting with name, and create a dict with it
    eg.: if "key" is looked for, {'html': 1, 'key_toto': 2, 'key_titi': 3} will return:
        {None: 1, toto: 2, titi: 3}
    @param name(unicode): name of the key
    @param dict_(dict): dictionary with the serialised list
    @param sep(unicode): separator used between name and subkey
    @return iter: iterate through the deserialised items
    """
    for k, v in dict_.iteritems():
        if k.startswith(name):
            if k == name:
                yield None, v
            elif k[len(name)] != sep:
                continue
            else:
                yield k[len(name) + 1:], v


def Rights():
    """ Return the DCMI Rights element (resource copyright).

        o Return a string describing the intellectual property status, if
          any, of the resource.

        o Permission:  View
        """


def interpret_signal(signal):
    """signal interpretation
    returning numbers:
        1: to the next image
        -1: previous image
        2: exit
        None: remain and do nothing
    returning sequence:
        add_page, model_inference, quit
    """
    if signal == 1:
        return 1, False
    elif signal == 2:
        return None, True
    elif signal == -1:
        return -1, False
    else:
        return 0, False


@staticmethod
def right_child(i):
    """
        Given index i, compute the index of i's right child.

        @param i: The index of the node from which the right child index should be calculated.
        @type: C{int}
        @return: The right index of the node i.
        @rtype: C{int}
        """
    return 2 * i + 2


def getTOFgammaDeriv(dsp):
    """get derivatives of TOF peak profile gamma wrt X, Y & Z

    :param float dsp: d-spacing of peak

    :returns: list getTOFgammaDeriv: d(gam)/dX & d(gam)/dY

    """
    return dsp, dsp ** 2, 1.0


def empty_formatter(view, value):
    """
        Return empty string for `None` value

        :param value:
            Value to check
    """
    return ''


def pin(clear: bool=False):
    """Set/clear selected UV vertices as anchored between multiple unwrap operations

    :param clear: Clear, Clear pinning for the selection instead of setting it
    :type clear: bool
    """
    pass


def _build_up_implementation(cls):
    """
            Implementation of type creation. To be overridden in derived metaclasses.
        """


def get():
    """Get a dictionary with tile data for this tile. The dictionary is
        disconnected from the underlying storage.
        """


def expand_tokens(tokens, equal=False):
    """Given a list of tokens, return a generator of the chunks of
    text for the data in the tokens.
    """
    for token in tokens:
        for pre in token.pre_tags:
            yield pre
        if not equal or not token.hide_when_equal:
            if token.trailing_whitespace:
                yield token.html() + token.trailing_whitespace
            else:
                yield token.html()
        for post in token.post_tags:
            yield post


def _utf8_str(s):
    """Convert unicode to utf-8."""
    if isinstance(s, str):
        return s.encode('utf-8')
    else:
        return str(s)


@classmethod
def _deriveLogin(cls, email, firstName, lastName, userName=None):
    """
        Attempt to automatically create a login name from existing user
        information from OAuth2 providers. Attempts to generate it from the
        username on the provider, the email address, or first and last name. If
        not possible, returns None and it is left to the caller to generate
        their own login for the user or choose to fail.

        :param email: The email address.
        :type email: str
        """
    for login in cls._generateLogins(email, firstName, lastName, userName):
        login = login.lower()
        if cls._testLogin(login):
            return login
    raise Exception('Could not generate a unique login name for %s (%s %s)' %
        (email, firstName, lastName))


def update_view(url):
    """This action will update the current container view with provided url.

    See 'XBMC.Container.Update()' at
    http://wiki.xbmc.org/index.php?title=List_of_built-in_functions.
    """
    return 'XBMC.Container.Update(%s)' % url


def edge_rotate(edge: 'bmesh.types.BMEdge', ccw: bool=False
    ) ->'bmesh.types.BMEdge':
    """Rotate the edge and return the newly created edge. If rotating the edge fails, None will be returned.

    :param edge: The edge to rotate.
    :type edge: 'bmesh.types.BMEdge'
    :param ccw: When True the edge will be rotated counter clockwise.
    :type ccw: bool
    :return:  The newly rotated edge.
    """
    pass


@staticmethod
def _from_string(msg: str='', del_spaces: bool=False, delimiter: str='\n'):
    """
        Takes a manual string input from the user, and then splits it using a comma delimiter into a list of values.         Called when an FeatureSet instance is created without input,         or when FeatureSet.enrich_randomization is called without input.

        :param msg: a promprt to be printed to the user
        :param del_spaces: if True, will delete all spaces in each delimited value.
        :param delimiter: the delimiter used to separate the values. Default is '
'
        :return:
        A list of the comma-seperated values the user inserted.
        """
    string = input(msg)
    split = string.split(sep=delimiter)
    if del_spaces:
        for i in range(len(split)):
            split[i] = split[i].replace(' ', '')
    if split[-1] == '':
        split = split[:-1]
    return split


@classmethod
def transcribe_value(cls, value, **kw):
    """ For simple `PacketField`s, return a bytes transcription of a
        value suitable for the `.value` attribute.

        For example, the `BSUInt` subclass stores a `int` as its
        `.value` and exposes its serialisation method, suitable for
        any `int`, as `transcribe_value`.
    """
    return cls(value, **kw).transcribe()


@classmethod
def fromkeys(cls, iterable, value=None):
    """OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S
        and values equal to v (which defaults to None).

        """
    d = cls()
    for key in iterable:
        d[key] = value
    return d


def get_app_label(attrs):
    """
    Returns an app_label from attrs
    """
    app_label = None
    try:
        from django.apps import apps
    except ImportError:
        meta = attrs.get('Meta')
        if meta:
            app_label = getattr(meta, 'app_label', None)
        if not app_label:
            app_label = attrs['__module__'].split('.')[-2]
    else:
        app_config = apps.get_containing_app_config(attrs['__module__'])
        if app_config:
            app_label = app_config.label
    return app_label


def create2D(rowCount, colCount, value=None):
    """
    Create and return a 2D array having rowCount rows and colCount
    columns, with each element initialized to value.
    """
    a = [None] * rowCount
    for row in range(rowCount):
        a[row] = [value] * colCount
    return a


def gzipped(content):
    """
    test if content is gzipped by magic num.
    first two bytes of gzip stream should be 0x1F and 0x8B,
    the third byte represent for compress algorithm, always 8(deflate) now
    """
    if content is not None and len(content) > 10 and ord(content[0:1]
        ) == 31 and ord(content[1:2]) == 139 and ord(content[2:3]) == 8:
        return True
    return False


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

        :param TeamFolderMetadata val:
        :rtype: TeamFolderArchiveJobStatus
        """
    return cls('complete', val)


def is_simulator_backend(backend):
    """
    Return True if backend is a simulator.

    Args:
        backend (BaseBackend): backend instance
    Returns:
        bool: True is a simulator
    """
    return backend.configuration().simulator


@staticmethod
def search_get_document_id(key):
    """
        Returns an index document id from a key. Defaults to just using the key's urlsafe string.

        :param key: ndb.Key instance
        :return: String for document index
        """
    return key.urlsafe()


def parsing_play_end(response, tips=False):
    """
    功能：解析停止播放命令的回应内容：
    输入：
    response：停止播放命令执行后机器人的回应内容。
    返回：
    action_name:机器人当前执行的动作表名称
    """
    if response == b'':
        return response
    cmd_len = response[2]
    cmd_type = response[3]
    if cmd_type != 49:
        print('解析类型错误，请检查回应内容，当前命令类型为%d' % cmd_type)
        return 0
    action_name = bytes.decode(response[4:cmd_len - 1], encoding='gbk')
    if tips:
        print('动作“%s”已执行完毕！' % action_name)
    return action_name


def convert_run_to_newstyle(run):
    """
    Converts a saved run result to include the parameters.

    Parameters
    ----------
    run : :py:meth:`~batchpy.run.Run` object or child class
        The run to convert the result from.

    """
    res = run.load()
    if res is not None:
        run._save(res)


def import_lmfit(funcname='XU'):
    """
    lazy import function for lmfit
    """
    try:
        import lmfit
        return lmfit
    except ImportError:
        raise ImportError(
            '%s: Fitting of models needs the lmfit package (https://pypi.python.org/pypi/lmfit)'
             % funcname)


def pypi_url(varmap):
    """Return the PyPI URL for program ``name`` from the setup vars.
    """
    return 'http://pypi.org/project/{}'.format(varmap['name'])


@staticmethod
def _separate_target_reqs(req):
    """Separates parameters into target and non-target ones.

        target_* parameters are rekeyed by removing the prefix.

        :param req: Request dict containing the parameters for Keystone
        authentication.
        :return: list of [non-target, target] request parameters
        """
    r = {}
    target_r = {}
    target_prefix = 'target_'
    for key in req:
        if key.startswith(target_prefix):
            target_r[key[len(target_prefix):]] = req[key]
        else:
            r[key] = req[key]
    return [r, target_r]


def one_obj_or_list(seq):
    """If there is one object in list - return object, otherwise return list"""
    if len(seq) == 1:
        return seq[0]
    return seq


def value_for_dsd_ref(kind, args, kwargs):
    """Maybe replace a string 'value_for' in *kwargs* with a DSD reference."""
    try:
        dsd = kwargs.pop('dsd')
        descriptor = getattr(dsd, kind + 's')
        kwargs['value_for'] = descriptor.get(kwargs['value_for'])
    except KeyError:
        pass
    return args, kwargs


@classmethod
def construct_search(cls, request, view, search_backend):
    """Construct search.

        :param request:
        :param view:
        :param search_backend:
        :return:
        """
    raise NotImplementedError(
        'You should implement `construct_search` method in your {} class'.
        format(cls.__name__))


def create_buckets(lower_bound, upper_bound, bins):
    """
    Create a dictionary with bins
    :param lower_bound: low range
    :param upper_bound: high range
    :param bins: number of buckets
    :return:
    """
    range_value = (upper_bound - lower_bound) / bins
    low = lower_bound
    buckets = []
    if bins == 1:
        buckets.append({'lower': low, 'upper': low + 1, 'bucket': 0})
    else:
        for i in range(0, bins):
            high = low + range_value
            buckets.append({'lower': low, 'upper': high, 'bucket': i})
            low = high
        buckets[bins - 1]['upper'] = upper_bound
    return buckets


def set_uuid_for(node, override=False, recursiv=False):
    """Set ``uuid`` for node. If ``override`` is True, override existing
        ``uuid`` attributes, if ``recursiv`` is True, set new ``uuid`` on
        children as well.
        """


def enqueue_output(out, queue):
    """
    Send output to a queue.

    Parameters
    -----------
    out
        Readable output object.
    queue : :class:`queue.Queue`
        Queue to send ouptut to.
    """
    for line in iter(out.readline, b''):
        queue.put(line)
    out.close()


def find_break_point(line, max_index, key_list):
    """ find the most appropriate break point for a fortran line """
    for key in key_list:
        idx = line.rfind(key, 0, max_index)
        if idx > 0:
            return idx + len(key)
    raise Exception(
        "Error in find_break_point. No suitable break point found for line '" +
        line[:max_index] + "' and keys '" + str(key_list) + "'")


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

        :param MemberSetProfilePhotoType val:
        :rtype: EventType
        """
    return cls('member_set_profile_photo', val)


def duration_str(s):
    """
    s: number of seconds
    Return a human-readable string.
    Example: 100 => "1m40s", 10000 => "2h46m"
    """
    if s is None:
        return None
    m = int(s // 60)
    if m == 0:
        return '%.1fs' % s
    s -= m * 60
    h = int(m // 60)
    if h == 0:
        return '%dm%ds' % (m, s)
    m -= h * 60
    d = int(h // 24)
    if d == 0:
        return '%dh%dm' % (h, m)
    h -= d * 24
    y = int(d // 365)
    if y == 0:
        return '%dd%dh' % (d, h)
    d -= y * 365
    return '%dy%dd' % (y, d)


def declare_array(a, bv1, bv2):
    """
    Declares an SMT2 array represented as a map
    from a bit vector to another bit vector.
    :param a: array name
    :param bv1: SMT2 bit vector
    :param bv2: SMT2 bit vector
    """
    return '(declare-fun {} () (Array {} {}))'.format(a, bv1, bv2)


def interpolate_tuple(startcolor, goalcolor, steps):
    """
    Take two RGB color sets and mix them over a specified number of steps.  Return the list
    """
    R = startcolor[0]
    G = startcolor[1]
    B = startcolor[2]
    targetR = goalcolor[0]
    targetG = goalcolor[1]
    targetB = goalcolor[2]
    DiffR = targetR - R
    DiffG = targetG - G
    DiffB = targetB - B
    buffer = []
    for i in range(0, steps + 1):
        iR = R + DiffR * i // steps
        iG = G + DiffG * i // steps
        iB = B + DiffB * i // steps
        hR = str.replace(hex(iR), '0x', '')
        hG = str.replace(hex(iG), '0x', '')
        hB = str.replace(hex(iB), '0x', '')
        if len(hR) == 1:
            hR = '0' + hR
        if len(hB) == 1:
            hB = '0' + hB
        if len(hG) == 1:
            hG = '0' + hG
        color = str.upper('#' + hR + hG + hB)
        buffer.append(color)
    return buffer


def is_any(type_strings, struct):
    """
    Return true if all types are valid, and there are no type constraints.
    """
    ALL_PROPERTY_NAMES = {'exclusiveMaximum', 'format', 'minItems',
        'pattern', 'required', 'multipleOf', 'maximum', 'minimum',
        'maxItems', 'minLength', 'uniqueItems', 'additionalItems',
        'maxLength', 'items', 'exclusiveMinimum', 'properties',
        'additionalProperties', 'minProperties', 'maxProperties',
        'patternProperties'}
    return len(type_strings) == 6 and not set(struct.keys()
        ) & ALL_PROPERTY_NAMES


@classmethod
def clear_instance_cache(cls):
    """
        Clear/Reset the instance cache.
        """
    cls.__instance_cache = {}


def learning_rate_linearly_decayed(initial_rate, final_rate=0,
    max_iterations=20):
    """ A generator function that, starting from `initial_rate`, decays the
    learning rate linearly. After `max_iterations` it always yields final_rate.

    It can be passed as ``learning_rate`` argument to :py:meth:`.SGD.train` .

    Formally, it computes :math:`\\epsilon_k = (1 - \\alpha)\\epsilon_0+
    \\alpha \\epsilon_\\tau`, where :math:`k` is the iteration number,
    :math:`\\tau` is ``max_iterations``, :math:`\\epsilon_0` is
    ``initial_rate``, :math:`\\epsilon_\\tau` is ``final_rate``, and
    :math:`\\alpha=\\frac{k}{\\tau}`.

    :param initial_rate: the rate at the first iteration.
    :param final_rate: the rate to return after the maximum number of
        iterations.
    :param max_iterations: the maximum number of iterations.
    """
    for i in range(max_iterations):
        alpha = i / max_iterations
        rate = (1.0 - alpha) * initial_rate + alpha * final_rate
        yield rate
    while True:
        yield final_rate


def scale_size(scalar: float=1.0):
    """Change brush size by a scalar

    :param scalar: Scalar, Factor to scale brush size by
    :type scalar: float
    """
    pass


def _len_list(obj):
    """Length of list (estimate).
    """
    n = len(obj)
    if n > 8:
        n += 6 + (n >> 3)
    elif n:
        n += 4
    return n


def after_initialize(harn):
    """
        Perform a custom initialization step (not usually needed)
        """
    pass


def _assert_valid_axis(ndims, axis):
    """Assert the condition `-ndims < axis <= ndims` if `axis` is not `None`."""
    if axis and (axis < -ndims or axis >= ndims):
        raise ValueError('axis = %d not in [%d, %d)' % (axis, -ndims, ndims))


def psi_K_Cl_HSO4_HMW84(T, P):
    """c-a-a': potassium chloride bisulfate [HMW84]."""
    psi = 0.0
    valid = T == 298.15
    return psi, valid


@staticmethod
def _get_source_and_target_channels(channel_one, channel_two,
    rebalance_direction):
    """
        Determines what the sending and receiving channel ids are.

        :param channel_one: first channel
        :type channel_one: int

        :param channel_two: second channel
        :type channel_two: int

        :param rebalance_direction: positive, if receiving, negative if sending
        :type rebalance_direction: float

        :return: sending and receiving channel
        :rtype: (int, int)
        """
    if rebalance_direction < 0:
        source = channel_one
        target = channel_two
    else:
        source = channel_two
        target = channel_one
    return source, target


def add_custom_pattern(mpl_hatch, pattern_name, pattern_definition=None):
    """
        The patterns of tikzpgf are quite simple, and cannot be customized but for the
        color. A solution is to expose a function like this one to allow the user to
        populate _MP_HATCH2PGF_PATTERN with custom (hatch, pattern) pairs. mpl does no
        validation of the hatch string, it just ignores it if it does not recognize it,
        so it is possible to have <any> string be a mpl_hatch.

        If the pattern definition is passed, it could be added at the start of the code
        in a similar fashion to
        > data["custom colors"] = {}
        in get_tikz_code(). tikzplotlib pattern definitions would mend the bad
        correspondence between the mpl hatches and tikz patterns, with custom patterns
        for the mpl hatches 'o' and 'O'

        Want some opinions on this before I implement it..

        From https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.patches.Patch.html:
        > Letters can be combined, in which case all the specified hatchings are done.
        > If same letter repeats, it increases the density of hatching of that pattern.
        To achieve something like this, custom patterns must be created
        https://tex.stackexchange.com/questions/29359/pgfplots-how-to-fill-the-area-
        under-a-curve-with-oblique-lines-hatching-as-a/29367#29367
    """


def empty_line(line):
    """Empty lines are ignored by Solr."""
    if len(line.strip()) == 0:
        return True


@classmethod
def find(cls, value):
    """Get level based on given value, returns None if level not found."""
    return getattr(cls, (value or '').upper(), None)


def bench5(x):
    """A benchmark function for test purposes.

        f(x) = float(x[0]) ** 2 + x[1] ** 2

    where x is a string. It has a single minima with f(x) = 0 at x[0] = "0"
    and x[1] = "0"
    This benchmark is used for checking support of mixed spaces.
    """
    return float(x[0]) ** 2 + x[1] ** 2


def isWminus(pid):
    """Determine if the PID is that of a W-"""
    return pid == -24


def _parse_color_value(value):
    """Converts a Gdk color object to a hex-formatted string (e.g. #FFFFFF)"""
    return '#%02x%02x%02x' % (int(value.red * 255), int(value.green * 255),
        int(value.blue * 255))


@classmethod
def getServers(cls):
    """
        This method must be implemented by subclasses.
        """
    raise NotImplementedError('This method must be implemented by a subclass.')


def match_movie_length():
    """Set image’s user’s length to the one of this video

    """
    pass


@classmethod
def unpack_scalar(cls, dataset, data):
    """
        Given a dataset object and data in the appropriate format for
        the interface, return a simple scalar.
        """
    if len(data) != 1:
        return data
    key = list(data.keys())[0]
    if len(data[key]) == 1 and key in dataset.vdims:
        return data[key][0]


def get_protected_attributes_dict(names, attributes):
    """Returns dictionary of protected attributes.

    The dictionary has the form: {"s1": [...], "s2": [...], ... }
    Key "sI" is the sensitive feature name, and [...] the 1D array holding the
    sensitive feature.

    Args:
        names (list(str)): names of the attributes in attributes.
        attributes (np.ndarray): 2D array of the sensitive features.

    Returns:
        (dict): {"s1": [attributes[:, 1]], "s2":[attributes[:, 2]], ... }
    """
    protected_attributes_dict = {}
    for i in range(len(names)):
        name = names[i]
        data = attributes[:, (i)]
        protected_attributes_dict[name] = data
    return protected_attributes_dict


def drange(start, stop, step=1):
    """
    Creates lists containing arithmetic progressions of any number type (int,
    float, ...)
    """
    r = start
    while r < stop:
        yield r
        r += step


@staticmethod
def _convert_number_bmk(axis_value, _):
    """Converts the values on axes to Billions, Millions or Thousands"""
    if axis_value >= 1000000000.0:
        return '{:1.1f}B'.format(axis_value * 1e-09)
    if axis_value >= 1000000.0:
        return '{:1.1f}M'.format(axis_value * 1e-06)
    if axis_value >= 1000.0:
        return '{:1.1f}K'.format(axis_value * 0.001)
    if axis_value >= 1 or axis_value == 0:
        return '{:1.0f}'.format(axis_value)
    return axis_value


def update_projects():
    """Called when projects may have changed, to refresh the available
        projects"""


def trim_long_text(text, max_lines):
    """
    Trim a potentially long multi-line message at the given number of lines.
    :param text: the input text
    :param max_lines: maximum number of lines
    :return: the trimmed message
    """
    max_lines = max(max_lines, 3)
    lines = text.splitlines()
    if len(lines) <= max_lines:
        return text
    lines_to_keep_at_each_end = int((max_lines - 1) / 2)
    num_lines_skipped = len(lines) - lines_to_keep_at_each_end * 2
    if num_lines_skipped <= 0:
        return text
    return '\n'.join(lines[:lines_to_keep_at_each_end] + [
        '({} lines skipped)'.format(num_lines_skipped)] + lines[-
        lines_to_keep_at_each_end:])


def select_parent():
    """Select bones that are parents of the currently selected bones

    """
    pass


def is_resource(thing):
    """
    Checks if a given object or type adheres to the closable concept
    :type thing: object or type
    :rtype: bool
    """
    return hasattr(thing, 'close') and hasattr(thing.close, '__call__')


def ensure_unique_obs_ids_in_wide_data(obs_id_col, wide_data):
    """
    Ensures that there is one observation per row in wide_data. Raises a
    helpful ValueError if otherwise.

    Parameters
    ----------
    obs_id_col : str.
        Denotes the column in `wide_data` that contains the observation ID
        values for each row.
    wide_data : pandas dataframe.
        Contains one row for each observation. Should contain the specified
        `obs_id_col` column.

    Returns
    -------
    None.
    """
    if len(wide_data[obs_id_col].unique()) != wide_data.shape[0]:
        msg = 'The values in wide_data[obs_id_col] are not unique, '
        msg_2 = 'but they need to be.'
        raise ValueError(msg + msg_2)
    return None


def __delitem__(name):
    """Call __delitem__ on context.
        """


def loseConnection():
    """
        Close my connection, after writing all pending data.

        Note that if there is a registered producer on a transport it
        will not be closed until the producer has been unregistered.
        """


def sgd(w, dw, config=None):
    """
    Performs vanilla stochastic gradient descent.

    config format:
    - learning_rate: Scalar learning rate.
    """
    if config is None:
        config = {}
    config.setdefault('learning_rate', 0.01)
    w -= config['learning_rate'] * dw
    return w, config


@staticmethod
def add_to_path(path, phase_point, left, right):
    """
        Add a phase point and perform some checks.

        This method is intended to be used by the propagate methods.

        Parameters
        ----------
        path : object like :py:class:`.PathBase`
            The path to add to.
        phase_point : object like py:class:`.System`
            The phase point to add to the path.
        left : float
            The left interface.
        right : float
            The right interface.

        """
    status = 'Running propagate...'
    success = False
    stop = False
    add = path.append(phase_point)
    if not add:
        if path.length >= path.maxlen:
            status = 'Max. path length exceeded'
        else:
            status = 'Could not add for unknown reason'
        success = False
        stop = True
    if path.phasepoints[-1].order[0] < left:
        status = 'Crossed left interface!'
        success = True
        stop = True
    elif path.phasepoints[-1].order[0] > right:
        status = 'Crossed right interface!'
        success = True
        stop = True
    if path.length == path.maxlen:
        status = 'Max. path length exceeded!'
        success = False
        stop = True
    return status, success, stop, add


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


@conf
def find_ldc2(conf):
    """
	Finds the program *ldc2* and set the variable *D*
	"""
    conf.find_program(['ldc2'], var='D')
    out = conf.cmd_and_log(conf.env.D + ['-version'])
    if out.find('based on DMD v2.') == -1:
        conf.fatal('detected compiler is not ldc2')


def p_language_mapping(t):
    """language_mapping : NUMBER COLON language"""
    t[0] = t[1], t[3]


def __clear_commands():
    """
    Clears all previously defined commands.

    Mostly for testing, but you could also use it to break everything in a
    really difficult to debug way.
    """
    _command_list = {}


@staticmethod
def vector_from_array(a):
    """Make a Matlab-compatible vector from a (Numpy) array.

        Parameters
        ----------
        a : ndarray
            The input array.

        Returns
        -------
        System.Array
            The vector.

        Examples
        --------
        >>>

        """
    raise NotImplementedError


def to_base(n, b):
    """
    Will convert any interger from base 10 to base b
    @arg n  The number to convert
    @arg b  The base to convert n to
    @ret    Coeff from expansion base b
            -- a_i from n = Sum (a_i) b^i
    """
    if n == 0:
        return [0]
    ret = []
    while n:
        ret.insert(0, n % b)
        n /= b
    return ret


def _c_string_literal(s):
    """
    Convert a python string into a literal suitable for inclusion into C code
    """
    s = s.replace('\\', '\\\\')
    s = s.replace('"', '\\"')
    s = s.replace('\n', '\\n')
    return '"{}"'.format(s)


def TiO2(mw_atmos, mh=1):
    """Defines properties for TiO2 as condensible"""
    if mh != 1:
        raise Exception(
            'Alert: No M/H Dependence in TiO2 Routine. Consult your local theorist to determine next steps.'
            )
    gas_mw = 80
    gas_mmr = 1.69e-07 * (gas_mw / mw_atmos)
    rho_p = 4.25
    return gas_mw, gas_mmr, rho_p


def _is_pesummary_hdf5_file(path, check_function):
    """Determine if the results file is a pesummary hdf5 file

    Parameters
    ----------
    path: str
        path to the results file
    check_function: func
        function used to check the result file
    """
    import h5py
    f = h5py.File(path, 'r')
    outcome = check_function(f)
    f.close()
    return outcome


def toUnicode(value):
    """Returns the given argument as a unicode object.

    @param value: A UTF-8 encoded string or a unicode (coercable) object
    @type message: str or unicode

    @returns: Unicode object representing the input value.
    """
    if isinstance(value, bytes):
        return value.decode('utf-8')
    return str(value)


def screener(molecules, ensemble, sort_order):
    """
    Uses the virtual screening scores for the receptors, or queries, specified in ensemble to sort the molecules in
    molecules in the direction specified by sort_order.
    :param molecules: a list of molecule objects (/classification/molecules.Molecules())
    :param ensemble: a tuple with receptors, or a query, that specifies a ensemble
    :param sort_order: 'asc' or 'dsc'. 'asc' sorts in ascending order (binding energy estimates) 'dsc' sorts in
    descending order (similarity scores, or binding probabilities)
    :return:
    """
    modified_molecules = []
    for index in range(len(molecules)):
        modified_molecules.append(molecules[index])
        scores = []
        for query in ensemble:
            scores.append((molecules[index].GetProp(query), query))
        if sort_order == 'dsc':
            scores.sort(key=lambda x: float(x[0]), reverse=True)
        elif sort_order == 'asc':
            scores.sort(key=lambda x: float(x[0]))
        modified_molecules[index].SetProp('best_score', format(scores[0][0]))
        modified_molecules[index].SetProp('best_query', format(scores[0][1]))
    active = []
    decoy = []
    non_random = []
    for mol in modified_molecules:
        if float(mol.GetProp('best_score')) == 10000.0:
            if mol.GetProp('status') == 1:
                active.append(mol)
            else:
                decoy.append(mol)
        else:
            non_random.append(mol)
    if sort_order == 'dsc':
        non_random.sort(key=lambda mol: float(mol.GetProp('best_score')),
            reverse=True)
    elif sort_order == 'asc':
        non_random.sort(key=lambda mol: float(mol.GetProp('best_score')))
    rand = []
    decoy_length = len(decoy)
    active_length = len(active)
    if decoy_length > active_length:
        for a, d in zip(active, decoy[0:active_length]):
            rand.append(a)
            rand.append(d)
        for d in decoy[active_length:decoy_length]:
            rand.append(d)
    elif decoy_length < active_length:
        for a, d in zip(active[0:decoy_length], decoy):
            rand.append(a)
            rand.append(d)
        for a in active[decoy_length:active_length]:
            rand.append(a)
    elif decoy_length == active_length:
        for a, d in zip(active, decoy):
            rand.append(a)
            rand.append(d)
    modified_molecules = non_random + rand
    return modified_molecules


def make_social_link(network, txt):
    """from a name like `username` return http://social.com/username"""
    if txt.startswith(('http://', 'https://', 'www.')):
        return txt
    if '/' in txt:
        return f'http://{txt}'
    return f'{network}/{txt}'


@staticmethod
def build_index(index, *args, **kwargs):
    """ Create the index. Child classes should generate index from the arguments given """
    _ = args, kwargs
    return index


def strings_differ(string1, string2, compare_digest=compare_digest):
    """Check whether two strings differ while avoiding timing attacks.

    This function returns True if the given strings differ and False
    if they are equal.  It's careful not to leak information about *where*
    they differ as a result of its running time, which can be very important
    to avoid certain timing-related crypto attacks:

        http://seb.dbzteam.org/crypto/python-oauth-timing-hmac.pdf

    .. versionchanged:: 1.5
       Support :func:`hmac.compare_digest` if it is available (Python 2.7.7+
       and Python 3.3+).

    """
    len_eq = len(string1) == len(string2)
    if len_eq:
        invalid_bits = 0
        left = string1
    else:
        invalid_bits = 1
        left = string2
    right = string2
    if compare_digest is not None:
        invalid_bits += not compare_digest(left, right)
    else:
        for a, b in zip(left, right):
            invalid_bits += a != b
    return invalid_bits != 0


@staticmethod
def parameters_list(num_particles, omega, phi_g):
    """
        Create a list with MOL parameters in the correct order.

        :param num_particles: Number of particles for the MOL swarm.
        :param omega: The omega parameter (aka. inertia weight) for the MOL.
        :param phi_g: The phi_g parameter (aka. social weight) for the MOL.
        :return: List with MOL parameters.
        """
    return [num_particles, omega, phi_g]


@staticmethod
def strip_indent(docstr):
    """Remove common leading indentation from docstring.

        Determine indentation level of line with least amount of leading
        whitespace (of the lines with non-whitespace characters). Dedent
        all docstring lines by that amount.

        :returns: normalized docstring
        :rtype: str

        """
    if '\n' in docstr:
        lines = docstr.split('\n')
        indents = []
        for line in lines[1:]:
            unindented_line = line.lstrip()
            if unindented_line:
                indents.append(len(line) - len(unindented_line))
        if indents:
            indent = min(indents)
        else:
            indent = 0
        lines[1:] = [line[indent:] for line in lines[1:]]
        docstr = '\n'.join(lines)
    return docstr


def _status_ok(record):
    """Check the record status field (position 3), if 0
    the file md5sum match the installation metadata.
    """
    if record[3] == 0:
        return True
    else:
        return False


@classmethod
def publish(cls, options, timeout=1500):
    """Publishes a new version of content-view."""
    cls.command_sub = 'publish'
    return cls.execute(cls._construct_command(options), ignore_stderr=True,
        timeout=timeout)


def submit(args):
    """
    makecli submit              : Submit your tool to pypi.python.org
    """
    text = """Please edit your own ~/.pypirc, and then run this command below:
  python setup.py sdist register upload
"""
    print(text)


def connectIDE():
    """Connect the debug server to the IDE

        May throw a IDEConnectionError.

        """


def diff(xds_inp_a, xds_inp_b):
    """Compare the parameters in a, b; write out the differences"""
    all_keys = list(sorted(set(xds_inp_a).union(xds_inp_b)))
    for key in all_keys:
        a = xds_inp_a.get(key, '')
        b = xds_inp_b.get(key, '')
        if a == b:
            continue
        print('%s:\n\t%s\n\t%s' % (key, a, b))


@classmethod
def execute(cls, session_id, data, state_name):
    """
        Execute the wizard state.

        session_id is a Session id
        data is a dictionary with the session data to update
        state_name is the name of state to execute

        Returns a dictionary with:
            - ``actions``: a list of Action to execute
            - ``view``: a dictionary with:
                - ``fields_view``: a fields/view definition
                - ``defaults``: a dictionary with default values
                - ``buttons``: a list of buttons
        """
    cls.check_access()
    wizard = cls(session_id)
    for key, values in data.items():
        record = getattr(wizard, key)
        for field, value in values.items():
            if field == 'id':
                continue
            setattr(record, field, value)
    return wizard._execute(state_name)


def N_(string):
    """No-op translation marker, inlined here to avoid importing from
    `trac.util`.
    """
    return string


def call_if_attribute(obj, attr, *args, **kwargs):
    """
    Call object method, if it exists.

    Arguments:
        obj (object): The object.
        attr (str): The name of the object method.
        *args (optional): Arguments for method.
        **kwargs (optional): Keyword arguments for method.

    Returns:
        Return value of calling method, or None if object does not have method.
    """
    op = getattr(obj, attr, None)
    if callable(op):
        return op(*args, **kwargs)


def external_pressure(h_l, rho_water, g=9.81) ->'p_e':
    """Water pressure, external to pipe.
    """
    return abs(h_l) * rho_water * g


@staticmethod
def _getGeneralizedTime(timeComponent):
    """Return time from Time component in YYYYMMDDHHMMSSZ format"""
    name = ''
    try:
        name = timeComponent.getName()
    except AttributeError:
        pass
    if name == 'generalTime':
        return timeComponent.getComponent()._value
    else:
        try:
            timeValue = timeComponent.getComponent()._value.decode('ascii')
        except AttributeError:
            timeValue = str(timeComponent[1][0])
        shortyear = int(timeValue[:2])
        rv = (shortyear >= 50 and '19' or '20') + timeValue
        return rv


def split_url_and_query(url):
    """Split the query from the url"""
    try:
        index = url.index('?')
    except ValueError:
        return url, ''
    query = url[index + 1:]
    url = url[:index]
    return url, query


def extract_want_line_capabilities(text):
    """Extract a capabilities list from a want line, if present.

    Note that want lines have capabilities separated from the rest of the line
    by a space instead of a null byte. Thus want lines have the form:

        want obj-id cap1 cap2 ...

    :param text: Want line to extract from
    :return: Tuple with text with capabilities removed and list of capabilities
    """
    split_text = text.rstrip().split(' ')
    if len(split_text) < 3:
        return text, []
    return ' '.join(split_text[:2]), split_text[2:]


def full_type_name(value):
    """
    The full class name of a type or instance.
    """
    if not isinstance(value, type):
        value = value.__class__
    module = str(value.__module__)
    name = str(value.__name__)
    return name if module == '__builtin__' else '{0}.{1}'.format(module, name)


def extract_hydrogens_from_instructions(instruction):
    """
    If the core or the fragment atom contains a "-" means that the user is selecting an specific H to be bonded with
    the heavy atom. For this reason, this detects if this option has been selected by the user and extract the PDB-atom-name
    of each element.
    :param instruction: list that follow this structure: [fragment_pdb_file, pdb_atom_name_of_the_core
    (and H if required), pdb_atom_name_of_the_fragment (and H if required)]
    :return: if the "-" is found in the pdb_atom_name_of_the_core or pdb_atom_name_of_the_fragment it returns a list with
    PDB-atom-names split following this order: heavy_atom_core, hydrogen_core, heavy_atom_fragment, hydrogen_fragment.
    Otherwise it returns False.
    """
    if '-' in instruction[1] or '-' in instruction[2]:
        try:
            heavy_core = instruction[1].split('-')[0]
            hydrogen_core = instruction[1].split('-')[1]
            heavy_fragment = instruction[2].split('-')[0]
            hydrogen_fragment = instruction[2].split('-')[1]
            return heavy_core, hydrogen_core, heavy_fragment, hydrogen_fragment
        except IndexError:
            raise IndexError(
                'To use steriochemistry the hydrogen from the core AND fragmet must be specified via controlfile'
                )
    else:
        return False


@classmethod
def _read(cls, line, sep='_'):
    """ Read a line and construct new object. """
    sline = line.strip().split(sep)
    mz = float(sline[3].lstrip('m/z'))
    retention = float(sline[4].lstrip('RT')) * 60
    return cls(mz, retention, line.strip())


def createMemberArea(member_id=''):
    """ Return a member area for the given member, creating if necessary.

        o If member area creation is disabled, return None.

        o 'member_id', if passed, is the ID of the member whose folder is
          to be created;  if not passed, default to the authenticated member.

        o Permission:  Public # ????
        """


def unicode_is_ascii(u_string):
    """Determine if unicode string only contains ASCII characters.

    :param str u_string: unicode string to check. Must be unicode
        and not Python 2 `str`.
    :rtype: bool
    """
    assert isinstance(u_string, str)
    try:
        u_string.encode('ascii')
        return True
    except UnicodeEncodeError:
        return False


def compute_ppi_corrected_res_array(res_array, ppi_list_rel_density):
    """Return ppi density normalized sizes of the real resolutions."""
    eff_res_array = []
    for i in range(len(res_array)):
        effw = round(res_array[i][0] / ppi_list_rel_density[i])
        effh = round(res_array[i][1] / ppi_list_rel_density[i])
        eff_res_array.append((effw, effh))
    return eff_res_array


def readData(inp, output_dict, input_dict):
    """
    This function read data from input wire and output
    :param inp: input name
    :param output_dict: output dictionary
    :param input_dict: input dictionary
    :return: input value
    """
    if inp in output_dict.keys():
        tempLogic = output_dict[inp]
    else:
        tempLogic = input_dict[inp]
    return tempLogic


def collection_hide_inside():
    """Hide all the objects and collections inside the collection

    """
    pass


def list_geo_locations(StartContinentCode=None, StartCountryCode=None,
    StartSubdivisionCode=None, MaxItems=None):
    """
    Retrieves a list of supported geo locations.
    Countries are listed first, and continents are listed last. If Amazon Route 53 supports subdivisions for a country (for example, states or provinces), the subdivisions for that country are listed in alphabetical order immediately after the corresponding country.
    See also: AWS API Documentation

    :example: response = client.list_geo_locations(
        StartContinentCode='string',
        StartCountryCode='string',
        StartSubdivisionCode='string',
        MaxItems='string'
    )

    :type StartContinentCode: string
    :param StartContinentCode: The code for the continent with which you want to start listing locations that Amazon Route 53 supports for geolocation. If Amazon Route 53 has already returned a page or more of results, if IsTruncated is true, and if NextContinentCode from the previous response has a value, enter that value in StartContinentCode to return the next page of results.
            Include StartContinentCode only if you want to list continents. Don't include StartContinentCode when you're listing countries or countries with their subdivisions.

    :type StartCountryCode: string
    :param StartCountryCode: The code for the country with which you want to start listing locations that Amazon Route 53 supports for geolocation. If Amazon Route 53 has already returned a page or more of results, if IsTruncated is true , and if NextCountryCode from the previous response has a value, enter that value in StartCountryCode to return the next page of results.
            Amazon Route 53 uses the two-letter country codes that are specified in ISO standard 3166-1 alpha-2 .

    :type StartSubdivisionCode: string
    :param StartSubdivisionCode: The code for the subdivision (for example, state or province) with which you want to start listing locations that Amazon Route 53 supports for geolocation. If Amazon Route 53 has already returned a page or more of results, if IsTruncated is true , and if NextSubdivisionCode from the previous response has a value, enter that value in StartSubdivisionCode to return the next page of results.
            To list subdivisions of a country, you must include both StartCountryCode and StartSubdivisionCode .

    :type MaxItems: string
    :param MaxItems: (Optional) The maximum number of geolocations to be included in the response body for this request. If more than MaxItems geolocations remain to be listed, then the value of the IsTruncated element in the response is true .

    :rtype: dict
    :return: {
        'GeoLocationDetailsList': [
            {
                'ContinentCode': 'string',
                'ContinentName': 'string',
                'CountryCode': 'string',
                'CountryName': 'string',
                'SubdivisionCode': 'string',
                'SubdivisionName': 'string'
            },
        ],
        'IsTruncated': True|False,
        'NextContinentCode': 'string',
        'NextCountryCode': 'string',
        'NextSubdivisionCode': 'string',
        'MaxItems': 'string'
    }

    """
    pass


@classmethod
def get_timeline_storage_options(cls):
    """
        Returns the options for the timeline storage
        """
    options = {}
    options['serializer_class'] = cls.timeline_serializer
    options['activity_class'] = cls.activity_class
    return options


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


@classmethod
def followee_count(cls, follower_id):
    """Return the number of objects followed by the follower."""
    return cls._get_followees(follower_id).count()


def global_pct_sim(segments):
    """
    Calculated as in global_pct_id(), but with the percent similarity field
    """
    match_length = 0
    similar_residues = 0
    for segment in segments:
        segment_length = abs(segment['contig_start'] - segment['contig_end']
            ) + 1
        match_length += segment_length
        matched_residues = segment_length * (segment['pct_sim'] / 100)
        similar_residues += matched_residues
    return similar_residues / match_length * 100


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

    .. math::
       square(x) = x^2

    Example::

       square([2, 3, 4]) = [4, 9, 16]

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

       - square(default) = default
       - square(row_sparse) = row_sparse
       - square(csr) = csr

    Defined in src/operator/tensor/elemwise_unary_op_pow.cc:L118

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

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

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


@classmethod
def vol_type(cls):
    """The type of volume supported by this type."""
    return 'fileio'


@classmethod
def alter_field(cls, field, label, ftype):
    """ Update an existing field

        :param field: instance of the Field model to update
        :param label: label of the field
        :param ftype: type of the AnyBlok Field
        """
    field.update(label=label, ftype=ftype)


@staticmethod
def decode(text):
    """Decode the text by the cipher

        If there are multiple ways to decode the text, return all of them

        :param text: The cipher-text
        :type text: str

        :returns: List of the plain-texts (or plain-text) after decode
        :rtype: list

        :raise NotImplementedError: If the decode function not set in the decoder
        """
    raise NotImplementedError


def gear_box_torques_in(min_engine_on_speed, gear_box_torques_out,
    gear_box_speeds_in, gear_box_speeds_out, par, clutch):
    """
    Calculates torque required according to the temperature profile [N*m].

    :param min_engine_on_speed:
        Minimum engine speed to consider the engine to be on [RPM].
    :type min_engine_on_speed: float

    :param gear_box_torques_out:
        Torque gear_box vector [N*m].
    :type gear_box_torques_out: numpy.array

    :param gear_box_speeds_in:
        Engine speed vector [RPM].
    :type gear_box_speeds_in: numpy.array

    :param gear_box_speeds_out:
        Wheel speed vector [RPM].
    :type gear_box_speeds_out: numpy.array

    :param gear_box_efficiency_parameters_cold_hot:
        Parameters of gear box efficiency model:

            - `gbp00`,
            - `gbp10`,
            - `gbp01`
    :type gear_box_efficiency_parameters_cold_hot: dict

    :return:
        Torque required vector [N*m].
    :rtype: numpy.array
    """
    tgb, es, ws = gear_box_torques_out, gear_box_speeds_in, gear_box_speeds_out
    if gear_box_speeds_in != 0:
        ratio = gear_box_speeds_out / gear_box_speeds_in
    else:
        ratio = 0
    if tgb >= 0:
        if es == 0 or ws == 0 or clutch == 1:
            res = 0
        else:
            res = (tgb * ratio - par['gbp10'] * es - par['gbp00']) / par[
                'gbp01']
    else:
        res = -(-tgb * ratio * par['gbp01'] + par['gbp10'] * ws + par['gbp00'])
    return res


@classmethod
def clear_expired(cls):
    """
        Remove expired sessions from the session store.

        If this operation isn't possible on a given backend, it should raise
        NotImplementedError. If it isn't necessary, because the backend has
        a built-in expiration mechanism, it should be a no-op.
        """
    raise NotImplementedError


def represent_mapping(tag, dumper, mapping):
    """Represent a mapping in yaml.

    :param tag: the yaml tag to use
    :param dumper: the dumper to use
    :type dumper: :class:`yaml.dumper.Dumper`
    :param mapping: the mapping to represent
    :return: the representation
    """
    return dumper.represent_mapping(tag, mapping)


def format_arg_value(arg_val):
    """ Return a string representing a (name, value) pair.

  >>> format_arg_value(('x', (1, 2, 3)))
  'x=(1, 2, 3)'
  """
    arg, val = arg_val
    return '%s=%r' % (arg, val)


def cursor_set(x: int=0, y: int=0):
    """Set cursor position

    :param x: X
    :type x: int
    :param y: Y
    :type y: int
    """
    pass


def debug(mode=True):
    """ Change the debug level.
    There is only one debug level supported at the moment."""
    global DEBUG
    DEBUG = bool(mode)


def _find_corresponding_multicol_key(key, keys_multicol):
    """Find the corresponding multicolumn key."""
    for mk in keys_multicol:
        if key.startswith(mk) and 'of' in key:
            return mk
    return None


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_ff(atomic_number, radiation, q=None):
    """Returns the form factor for a given atomic number, radiation and q
    values

    :param atomic_number: atomic number
    :type atomic_number: int
    :param radiation: type of radiation ('xray' or 'neutron')
    :type radiation: str
    :param q: value or values of q for which to get form factors
    :type q: float, list, :class:`numpy.ndarray`
    :return: form factors for given q
    :rtype: float, :class:`numpy.ndarray`

    :Examples:

    >>> get_ff(8, 'neutron')
    5.805

    >>> get_ff(8, 'xray', q=2.0)
    6.31826029176493

    >>> get_ff(8, 'xray', q=[0.0, 3.5, 7.0])
    array([ 7.999706  ,  4.38417867,  2.08928068])
    """
    import periodictable
    if radiation == 'neutron':
        return periodictable.elements[atomic_number].neutron.b_c
    elif radiation == 'xray':
        return periodictable.elements[atomic_number].xray.f0(q)
    else:
        raise ValueError('Unknown radition: ' + radiation)


@classmethod
def parse(cls, name, data_size, reader, parsers):
    """given a 4 byte name, data_size int, BitstreamReader
        and dict of {"atom":handler} sub-parsers,
        returns an atom of this class"""
    (version, track_in_poster, track_in_preview, track_in_movie, track_enabled
        ) = reader.parse('8u 20p 1u 1u 1u 1u')
    if version == 0:
        atom_format = '32u 32u 32u 4P 32u 8P 16u 16u 16u 2P'
    else:
        atom_format = '64U 64U 32u 4P 64U 8P 16u 16u 16u 2P'
    (created_utc_date, modified_utc_date, track_id, duration, video_layer,
        qt_alternate, volume) = reader.parse(atom_format)
    geometry_matrices = reader.parse('9* 32u')
    video_width, video_height = reader.parse('32u 32u')
    return cls(version=version, track_in_poster=track_in_poster,
        track_in_preview=track_in_preview, track_in_movie=track_in_movie,
        track_enabled=track_enabled, created_utc_date=created_utc_date,
        modified_utc_date=modified_utc_date, track_id=track_id, duration=
        duration, video_layer=video_layer, qt_alternate=qt_alternate,
        volume=volume, geometry_matrices=geometry_matrices, video_width=
        video_width, video_height=video_height)


def export_resources(interfaces: list, resources: dict) ->None:
    """
    Method to export the resources using the *output* interfaces.

    :param interfaces: The list of initialized output interfaces.
    :param resources: The resources provided by the input interfaces.
    """
    for interface in interfaces:
        interface.export_resources(resources)


def transform_tensor_sphericalPolar_2_lon_lat_rad(tensor):
    """Function transforming the components of a tensor from a spherical-polar basis to a zonal-meridional-radial basis."""
    import numpy as np
    transformationMatrix = np.array([[0.0, 0.0, 1.0], [0.0, -1.0, 0.0], [
        1.0, 0.0, 0.0]])
    transformed_Tensor = np.dot(np.dot(transformationMatrix, np.array(
        tensor)), transformationMatrix)
    return transformed_Tensor


def list_domains(MaxNumberOfDomains=None, NextToken=None):
    """
    The ListDomains operation lists all domains associated with the Access Key ID. It returns domain names up to the limit set by MaxNumberOfDomains . A NextToken is returned if there are more than MaxNumberOfDomains domains. Calling ListDomains successive times with the NextToken provided by the operation returns up to MaxNumberOfDomains more domain names with each successive operation call.
    See also: AWS API Documentation

    :example: response = client.list_domains(
        MaxNumberOfDomains=123,
        NextToken='string'
    )

    :type MaxNumberOfDomains: integer
    :param MaxNumberOfDomains: The maximum number of domain names you want returned. The range is 1 to 100. The default setting is 100.

    :type NextToken: string
    :param NextToken: A string informing Amazon SimpleDB where to start the next list of domain names.

    :rtype: dict
    :return: {
        'DomainNames': [
            'string',
        ],
        'NextToken': 'string'
    }

    :returns:
    (dict) --
    DomainNames (list) -- A list of domain names that match the expression.
    (string) --

    NextToken (string) -- An opaque token indicating that there are more domains than the specified MaxNumberOfDomains still available.

    """
    pass


def get_command(name):
    """
    Gets an instance of the named jig sub-command.

    For example::

        >>> get_command('init')
        <jig.commands.init.Command object at 0x10048fed0>
    """
    mod = __import__('jig.commands.{0}'.format(name.lower()), globals(),
        locals(), ['Command'], 0)
    return mod.Command


@classmethod
def class_initialize(cls, scom):
    """Tells devices with which SCOM interface to communicate."""
    cls.scom = scom


def train(text, good):
    """
        Обучить модель на указанном тексте.

        @param text: текст, на котором обучаемся
        @type text: C{unicode}
        @param good: хороший это текст или плохой с точки зрения классификации?
        @type good: C{bool}
        @return: результат операции
        @rtype: C{Deferred}
        """


def assert_has_n_lines(output, n):
    """Asserts the specified output contains ``n`` lines."""
    n_lines_found = len(output.splitlines())
    assert n_lines_found == int(n
        ), 'Expected %s lines in output, found %s lines' % (n, n_lines_found)


@staticmethod
def getKeyIndex(text):
    """Get the index of the key in the circle of fifths.

        'Cb' returns 0, 'C' returns 7, 'B#' returns 14.
        """
    circleOfFifths = ['Cb', 'Gb', 'Db', 'Ab', 'Eb', 'Bb', 'F', 'C', 'G',
        'D', 'A', 'E', 'B', 'F#', 'C#']
    return circleOfFifths.index(text.capitalize())


def _status_decode(status):
    """Decode a 1 byte status into logical and physical statuses."""
    logical_status = (status & 12) >> 2
    physical_status = status & 3
    return logical_status, physical_status


def freeze(model):
    """ Set all layers in a model to non-trainable.

    The weights for these layers will not be updated during training.

    This function modifies the given model in-place,
    but it also returns the modified model to allow easy chaining with other functions.
    """
    for layer in model.layers:
        layer.trainable = False
    return model


def attr(obj, *path, **kwargs):
    """Safely get a nested attribute from an dictionary"""
    default = kwargs.get('default')
    if obj is None:
        return default
    res = obj
    for p in path:
        if p not in res:
            return default
        res = res[p]
    return res


def list_remove_by_index(l, index):
    """将list中的index位的数据删除"""
    if index < 0 or index >= len(l):
        raise ValueError('index out of range')
    if index == len(l) - 1:
        l.pop()
    elif index == 0:
        l = l[1:]
    else:
        l = l[0:index] + l[index + 1:]
    return l


def svg_text(pos, text, font_size=12, align_right=False):
    """Return svg code for text."""
    x, y = pos.astype(int)
    if align_right:
        return (
            '<text text-anchor="end" x="{}" y="{}" font-size="{}">{}</text>'
            .format(x, y, font_size, str(text)))
    else:
        return '<text x="{}" y="{}" font-size="{}">{}</text>'.format(x, y,
            font_size, str(text))


def truncate(number, rounding_factor):
    """Truncate to nearest arbitrary multiple

    >>> truncate(1000, 100)
    1000
    >>> truncate(1099, 100)
    1000
    >>> truncate(1099, 50)
    1050
    >>> truncate(1099, 50)
    1050
    """
    return int(number) / int(rounding_factor) * int(rounding_factor)


@classmethod
def _inContext(cls, adaptor, tokenNames, t, context):
    """The worker for inContext.

        It's static and full of parameters for testing purposes.
        """
    if cls.dotdotPattern.match(context):
        raise ValueError('invalid syntax: ..')
    if cls.doubleEtcPattern.match(context):
        raise ValueError('invalid syntax: ... ...')
    context = context.replace('...', ' ... ')
    context = context.strip()
    nodes = context.split()
    ni = len(nodes) - 1
    t = adaptor.getParent(t)
    while ni >= 0 and t is not None:
        if nodes[ni] == '...':
            if ni == 0:
                return True
            goal = nodes[ni - 1]
            ancestor = cls._getAncestor(adaptor, tokenNames, t, goal)
            if ancestor is None:
                return False
            t = ancestor
            ni -= 1
        name = tokenNames[adaptor.getType(t)]
        if name != nodes[ni]:
            return False
        ni -= 1
        t = adaptor.getParent(t)
    if t is None and ni >= 0:
        return False
    return True


def _translate_keys(cons):
    """Coerces a console instance into proper dictionary format."""
    pool = cons['pool']
    info = {'id': cons['id'], 'console_type': pool['console_type']}
    return dict(console=info)


def get_service_name(wrapped, instance, args, kwargs):
    """Return the AWS service name the client is communicating with."""
    if 'serviceAbbreviation' not in instance._service_model.metadata:
        return instance._service_model.metadata['endpointPrefix']
    return instance._service_model.metadata['serviceAbbreviation']


def game_property_remove(index: int=0):
    """Remove game property

    :param index: Index, Property index to remove
    :type index: int
    """
    pass


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

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

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


def geom_avg(vals) ->float:
    """
    Compute the geometric average of a list of values.

    :param vals: A list-like of numbers

    :return: The geometric average of the values.
    """
    rval = 1.0
    count = 0
    for val in vals:
        val = vals[count]
        if val != 0:
            rval *= val
            count += 1
    if count != 0:
        rval = pow(rval, 1.0 / count)
    return rval


@staticmethod
def default():
    """ return default options, available options:
        - max_name_length: maximum length of name for additionalProperties
        - max_prop_count: maximum count of properties (count of fixed properties + additional properties)
        - max_str_length: maximum length of string type
        - max_byte_length: maximum length of byte type
        - max_array_length: maximum length of array
        - max_file_length: maximum length of file, in byte
        - minimal_property: only generate 'required' properties
        - minimal_parameter: only generate 'required' parameter
        - files: registered file object: refer to pyswagger.primitives.File for details
        - object_template: dict of default values assigned for properties when 'name' matched
        - parameter_template: dict of default values assigned for parameters when 'name matched
        - max_property: all properties are generated, ignore 'required'
        - max_parameter: all parameters are generated, ignore 'required'

        :return: options
        :rtype: dict
        """
    return dict(max_name_length=64, max_prop_count=32, max_str_length=100,
        max_byte_length=100, max_array_length=100, max_file_length=200,
        minimal_property=False, minimal_parameter=False, files=[],
        object_template={}, parameter_template={}, max_property=False,
        max_parameter=False)


def __bin_peak_interval(mod, ii):
    """Ensures that peak bounds are opened to either positive real axis
    or negative real axes"""
    return mod.binpeaklower[ii] + mod.binpeakupper[ii] <= 1


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 prompt(zelf, colors=False):
    """ echo prompt to sys.stdout. """
    pass


def stack(seq, dim):
    """Stack the sequence of tensors along the given dimension.

    Parameters
    ----------
    seq : list of Tensor
        The tensor sequence.
    dim : int
        The concat dim.

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


def load(raw_bytes):
    """
        given a bytes object, should return a base python data
        structure that represents the object.

        a ValueError should be returned in the case where
        the object cannot be serialized.
        """
    raise NotImplementedError()


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

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