def vertex_group_copy_to_selected():
    """Replace vertex groups of selected objects by vertex groups of active object

    """
    pass


def int_coercable(string):
    """
    Check if string can be coerced to int
    :param string:
    :type string:
    :return:
    :rtype:
    """
    try:
        int(string)
        return True
    except ValueError:
        return False


@staticmethod
def loss(options):
    """Return the loss function."""
    raise NotImplementedError()


@classmethod
def get_collection_endpoint(cls):
    """
        Get the relative path to the API resource collection, using the corresponding resource class

        :param cls: Manager class
        :return: Relative path to the resource collection
        """
    return cls.resource_class.get_collection_endpoint()


def format_as_hex(char):
    """
    Formats a single ascii character as a lower case hex string

    :param char: a single ascii character
    :type char: str
    :returns: the character formatted as a lower case hex string
    :rtype: str
    """
    return '%2x' % ord(char)


def get_keywords():
    """Get the keywords needed to look up the version information."""
    git_refnames = '$Format:%d$'
    git_full = '$Format:%H$'
    git_date = '$Format:%ci$'
    keywords = {'refnames': git_refnames, 'full': git_full, 'date': git_date}
    return keywords


@classmethod
def clone(cls, value):
    """
        Clone byte array.
        """
    tmp = value[0:]
    return tmp


def delete_reconnect():
    """Delete nodes; will reconnect nodes as if deletion was muted

    """
    pass


def bC_Mg_SO3_RZM91(T, P):
    """c-a: magnesium sulfite [RZM91]."""
    b0 = -2.8
    b1 = 12.9
    b2 = -201
    C0 = 0
    C1 = 0
    alph1 = 1.4
    alph2 = 12
    omega = -9
    valid = T == 298.15
    return b0, b1, b2, C0, C1, alph1, alph2, omega, valid


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


def parse_to_none(val):
    """
    Convert value to None if match, pass otherwise.
    """
    if val in ['Unknown', 'NA', '']:
        return None
    return val


def _mark_asn1_named_ec_curve(backend, ec_cdata):
    """
    Set the named curve flag on the EC_KEY. This causes OpenSSL to
    serialize EC keys along with their curve OID which makes
    deserialization easier.
    """
    backend._lib.EC_KEY_set_asn1_flag(ec_cdata, backend._lib.
        OPENSSL_EC_NAMED_CURVE)


def get_exception_message(err):
    """
    Python 2 has the 'message' attribute for exceptions, however python 3 does not.  This helper method
    gives us the ability to sort out which one to use.
    :param err: Some exception
    :return: The exception message string
    """
    try:
        return err.message
    except AttributeError:
        return str(err)


@classmethod
def from_quat(cls, quat, normalized=False):
    """Initialize from quaternions.

        3D rotations can be represented using unit-norm quaternions [1]_.

        Parameters
        ----------
        quat : array_like, shape (N, 4) or (4,)
            Each row is a (possibly non-unit norm) quaternion in scalar-last
            (x, y, z, w) format.
        normalized : bool, optional
            If False, input quaternions are normalized to unit norm before
            being stored. If True, quaternions are assumed to already have
            unit norm and are stored as given. Default is False.

        Returns
        -------
        rotation : `Rotation` instance
            Object containing the rotations represented by input quaternions.

        References
        ----------
        .. [1] https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation

        Examples
        --------
        >>> from scipy.spatial.transform import Rotation as R

        Initialize a single rotation:

        >>> r = R.from_quat([1, 0, 0, 0])
        >>> r.as_quat()
        array([1., 0., 0., 0.])
        >>> r.as_quat().shape
        (4,)

        Initialize multiple rotations in a single object:

        >>> r = R.from_quat([
        ... [1, 0, 0, 0],
        ... [0, 0, 0, 1]
        ... ])
        >>> r.as_quat()
        array([[1., 0., 0., 0.],
               [0., 0., 0., 1.]])
        >>> r.as_quat().shape
        (2, 4)

        It is also possible to have a stack of a single rotation:

        >>> r = R.from_quat([[0, 0, 0, 1]])
        >>> r.as_quat()
        array([[0., 0., 0., 1.]])
        >>> r.as_quat().shape
        (1, 4)

        By default, quaternions are normalized before initialization.

        >>> r = R.from_quat([0, 0, 1, 1])
        >>> r.as_quat()
        array([0.        , 0.        , 0.70710678, 0.70710678])

        If unit norms are ensured, skip the normalization step.

        >>> r = R.from_quat([0, 0, 1, 0], normalized=True)
        >>> r.as_quat()
        array([0., 0., 1., 0.])

        """
    return cls(quat, normalized)


@classmethod
def from_node(cls, node):
    """
        Create an :class:`NodeItem` instance and initialize it from a
        :class:`SchemeNode` instance.

        """
    self = cls()
    self.setWidgetDescription(node.description)
    return self


def callables(potential_callables):
    """Ensure that the callables are in fact a sequence."""
    if callable(potential_callables):
        return [potential_callables]
    return potential_callables


def get_vbox_version(config_kmk):
    """Return the vbox config major, minor, build"""
    with open(config_kmk, 'rb') as f:
        config = f.read()
    major = b'6'
    minor = b'0'
    build = b'4'
    return b'.'.join([major, minor, build])


def eigenvalues(eigenvalues_at_kpoints, kpoint_index=0, spin_index=0):
    """
    Returns eigenvalues for a given kpoint and spin.

    Args:
        eigenvalues_at_kpoints (list): a list of eigenvalues for all kpoints.
        kpoint_index (int): kpoint index.
        spin_index (int): spin index.

    Returns:
         ndarray
    """
    spin_map = {(0): 0.5, (1): -0.5}
    for eigenvalue in eigenvalues_at_kpoints[kpoint_index]['eigenvalues']:
        if eigenvalue['spin'] == spin_map[spin_index]:
            return eigenvalue['energies']


def replay_queue_filler(replay_queue, replay_list):
    """A thread that fills the replay_queue with replay filenames."""
    for replay_path in replay_list:
        replay_queue.put(replay_path)


def p_paren_list(val):
    """paren_list : '[' flat_list ']'"""
    val[0] = val[2]


def sha(commit):
    """Return the sha hex for a commit."""
    return commit.hexsha


def delete_user_pool_client(UserPoolId=None, ClientId=None):
    """
    Allows the developer to delete the user pool client.
    See also: AWS API Documentation

    :example: response = client.delete_user_pool_client(
        UserPoolId='string',
        ClientId='string'
    )

    :type UserPoolId: string
    :param UserPoolId: [REQUIRED]
            The user pool ID for the user pool where you want to delete the client.

    :type ClientId: string
    :param ClientId: [REQUIRED]
            The ID of the client associated with the user pool.

    """
    pass


def add_linebreaks(text, max_len=80):
    """
	Add linebreaks on whitespace such that no line is longer than `max_len`, unless it contains a single word that's longer.

	There are probably way faster methods, but this is simple and works.
	"""
    br_text = ''
    len_cnt = 0
    for word in text.split(' '):
        len_cnt += len(word) + 1
        if len_cnt > max_len:
            len_cnt = len(word)
            br_text += '\n' + word
        else:
            br_text += ' ' + word
    return br_text[1:]


def pad_size(size):
    """
        Pad `size` to be a multiple of 16.

        :param size: `int`, size to be padded

        :returns: `int`
    """
    if size % 16 == 0:
        return size
    return size + 16 - size % 16


def _mini_batch_convergence(model, iteration_idx, n_iter, tol, n_samples,
    centers_squared_diff, batch_inertia, context, verbose=0):
    """Helper function to encapsulate the early stopping logic"""
    batch_inertia /= model.batch_size
    centers_squared_diff /= model.batch_size
    ewa_diff = context.get('ewa_diff')
    ewa_inertia = context.get('ewa_inertia')
    if ewa_diff is None:
        ewa_diff = centers_squared_diff
        ewa_inertia = batch_inertia
    else:
        alpha = float(model.batch_size) * 2.0 / (n_samples + 1)
        alpha = 1.0 if alpha > 1.0 else alpha
        ewa_diff = ewa_diff * (1 - alpha) + centers_squared_diff * alpha
        ewa_inertia = ewa_inertia * (1 - alpha) + batch_inertia * alpha
    if verbose:
        progress_msg = (
            'Minibatch iteration %d/%d: mean batch inertia: %f, ewa inertia: %f '
             % (iteration_idx + 1, n_iter, batch_inertia, ewa_inertia))
        print(progress_msg)
    if tol > 0.0 and ewa_diff <= tol:
        if verbose:
            print('Converged (small centers change) at iteration %d/%d' % (
                iteration_idx + 1, n_iter))
        return True
    ewa_inertia_min = context.get('ewa_inertia_min')
    no_improvement = context.get('no_improvement', 0)
    if ewa_inertia_min is None or ewa_inertia < ewa_inertia_min:
        no_improvement = 0
        ewa_inertia_min = ewa_inertia
    else:
        no_improvement += 1
    if (model.max_no_improvement is not None and no_improvement >= model.
        max_no_improvement):
        if verbose:
            print(
                'Converged (lack of improvement in inertia) at iteration %d/%d'
                 % (iteration_idx + 1, n_iter))
        return True
    context['ewa_diff'] = ewa_diff
    context['ewa_inertia'] = ewa_inertia
    context['ewa_inertia_min'] = ewa_inertia_min
    context['no_improvement'] = no_improvement
    return False


def raise_for_unexpected_kwargs(method_name, arguments, sig_args,
    sig_kwargs, is_iterable):
    """Raise TypeError if arguments are not in sig_args or sig_kwargs."""
    expected = set(sig_args) | set(sig_kwargs)
    if is_iterable:
        expected |= {'iterator'}
    unexpected = set(arguments.keys()) - expected
    if unexpected:
        msg_fmt = '{}() got an unexpected keyword argument(s) {}'
        raise TypeError(msg_fmt.format(method_name, str(unexpected)))


def cron_dow_to_calendar(cron_values):
    """ Converts a cron index day of week to a calendar index day of week. """
    if type(cron_values) in [str, int]:
        cron_values = [int(cron_values)]
    calendar_days = []
    for value in cron_values:
        calendar_days.append({(1): 6, (2): 0, (3): 1, (4): 2, (5): 3, (6):
            4, (7): 5}[int(value)])
    return list(calendar_days)


def edges_to_centers_nd(axis_range, edges_axis):
    """
    Converts ND array of pixel edges to pixel centers along one axis.

    Parameters
    ----------
    axis_range: `numpy.ndarray`
        Array of pixel edges.
    edges_axis: `int`
        Index of axis along which centers are to be calculated.
    """
    upper_edge_indices = [slice(None)] * axis_range.ndim
    upper_edge_indices[edges_axis] = slice(1, axis_range.shape[edges_axis])
    upper_edges = axis_range[tuple(upper_edge_indices)]
    lower_edge_indices = [slice(None)] * axis_range.ndim
    lower_edge_indices[edges_axis] = slice(0, -1)
    lower_edges = axis_range[tuple(lower_edge_indices)]
    return (upper_edges - lower_edges) / 2 + lower_edges


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

        :param TeamActivityCreateReportDetails val:
        :rtype: EventDetails
        """
    return cls('team_activity_create_report_details', val)


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

        :param MemberChangeAdminRoleType val:
        :rtype: EventType
        """
    return cls('member_change_admin_role', val)


def cfg_to_opts(config):
    """ converts a config to opts

    Args:
      config (ConfigParser): configuration object from which options are to be extracted

    Returns:
      opts (dict): dictionary of options read in from the configuration object
    """
    opts = {}
    opts['prot_file'] = config.get('General', 'prot_file', fallback=None)
    opts['lig_file'] = config.get('General', 'lig_file', fallback=None)
    opts['min_rad'] = config.getfloat('General', 'min_rad', fallback=1.4)
    opts['max_rad'] = config.getfloat('General', 'max_rad', fallback=3.4)
    opts['mode'] = config.get('Specification', 'mode', fallback=None)
    opts['resid'] = config.get('Specification', 'resid', fallback=None)
    opts['coordinates'] = config.get('Specification', 'coordinates',
        fallback=None)
    opts['lig_excl_rad'] = config.getfloat('Specification', 'lig_excl_rad',
        fallback=-1)
    opts['lig_incl_rad'] = config.getfloat('Specification', 'lig_incl_rad',
        fallback=-1)
    opts['subdivide'] = config.getboolean('Partitioning', 'subdivide',
        fallback=False)
    opts['min_volume'] = config.getint('Partitioning', 'min_volume',
        fallback=200)
    opts['max_clusters'] = config.getint('Partitioning', 'max_clusters',
        fallback=100)
    opts['min_subpocket_rad'] = config.getfloat('Partitioning',
        'min_subpocket_rad', fallback=1.7)
    opts['max_subpocket_rad'] = config.getfloat('Partitioning',
        'max_subpocket_rad', fallback=3.4)
    opts['min_subpocket_surf_rad'] = config.getfloat('Partitioning',
        'min_subpocket_surf_rad', fallback=1.0)
    opts['radial_sampling'] = config.getfloat('Partitioning',
        'radial_sampling', fallback=0.1)
    opts['inclusion_radius_buffer'] = config.getfloat('Partitioning',
        'inclusion_radius_buffer', fallback=1.0)
    opts['min_cluster_size'] = config.getint('Partitioning',
        'min_cluster_size', fallback=50)
    opts['project_dir'] = config.get('Output', 'project_dir', fallback=None)
    opts['output_dir'] = config.get('Output', 'output_dir', fallback=None)
    opts['prefix'] = config.get('Output', 'prefix', fallback=None)
    opts['logger_stream_level'] = config.get('Output',
        'logger_stream_level', fallback='INFO')
    opts['logger_file_level'] = config.get('Output', 'logger_file_level',
        fallback='DEBUG')
    opts['protein'] = config.get('PyMOL', 'protein', fallback=None)
    opts['ligand'] = config.get('PyMOL', 'ligand', fallback=None)
    opts['protein_only'] = config.get('PyMOL', 'protein_only', fallback=True)
    opts['display_mode'] = config.get('PyMOL', 'display_mode', fallback='solid'
        )
    opts['palette'] = config.get('PyMOL', 'palette', fallback=None)
    opts['alpha'] = config.get('PyMOL', 'alpha', fallback=0.85)
    return opts


@staticmethod
def has_battery():
    """Return whether the device has a battery."""
    return False


def IsReservedUserName(name):
    """
    Check if name can be used for users
    """
    if not name:
        return True
    name = name.strip()
    if not name:
        return True
    name = name.lower()
    if name.startswith('group:'):
        return True
    return False


def fromOpenIDRequest(cls, request):
    """Create a simple registration request that contains the
        fields that were requested in the OpenID request with the
        given arguments

        @param request: The OpenID request
        @type request: openid.server.CheckIDRequest

        @returns: The newly created simple registration request
        @rtype: C{L{SRegRequest}}
        """
    self = cls()
    message = request.message.copy()
    self.ns_uri = self._getSRegNS(message)
    args = message.getArgs(self.ns_uri)
    self.parseExtensionArgs(args)
    return self


@classmethod
def api_list(cls):
    """
        Returns a URL that will produce a list of JSON objects
        of this class' type
        """
    return '/'.join(cls.api_endpoint.split('/')[:-1])


@staticmethod
def split_large_text(text, length=4096):
    """
        Split text into chunks with specified length.

        :param text: text for splitting
        :param length: maximum size for one chunk
        :returns: tuple of chunks
        """
    text = str(text)
    yield text[0:length]
    for i in range(length, len(text), length):
        yield text[i:i + length]


def compute_voltages(grid, configs_raw, potentials_raw):
    """Given a list of potential distribution and corresponding four-point
    spreads, compute the voltages

    Parameters
    ----------
    grid:
        crt_grid object the grid is used to infer electrode positions
    configs_raw: Nx4 array
        containing the measurement configs (1-indexed)
    potentials_raw: list with N entries
        corresponding to each measurement, containing the node potentials of
        each injection dipole.
    """
    voltages = []
    for config, potentials in zip(configs_raw, potentials_raw):
        print('config', config)
        e3_node = grid.get_electrode_node(config[2])
        e4_node = grid.get_electrode_node(config[3])
        print(e3_node, e4_node)
        print('pot1', potentials[e3_node])
        print('pot2', potentials[e4_node])
        voltage = potentials[e3_node] - potentials[e4_node]
        voltages.append(voltage)
    return voltages


def simulate():
    """ Sequence of commands to simulate network """
    from .. import sim
    sim.runSim()
    sim.gatherData()


def basename(p):
    """Returns the final component of a pathname"""
    i = p.rfind('/') + 1
    return p[i:]


def copy_attrs(src_obj, dest_obj, attr_list):
    """ Copies list of attributes form source to destination"""
    src_attrs = src_obj.attrs.mget(attr_list)
    src_list = dict(list(zip(attr_list, src_attrs)))
    te_key = 'xnat:mrScanData/parameters/te'
    if te_key in src_list:
        src_list[te_key] = src_obj.attrs.get(te_key)
    dest_obj.attrs.mset(src_list)
    return 0


def collection_holdout_clear():
    """Clear masking of collection in the active view layer

    """
    pass


def qualname(func):
    """Get a qualified name of a function"""
    if func.__module__ == '__main__':
        return func.__name__
    else:
        return func.__module__ + '.' + func.__name__


@classmethod
def is_valid(cls, name):
    """Check if a string is a valid hypervisor type

        :param name: hypervisor type name to validate

        :returns: True if @name is valid
        """
    return name in cls.ALL


def clear_caches():
    """Jinja2 keeps internal caches for environments and lexers.  These are
    used so that Jinja2 doesn't have to recreate environments and lexers all
    the time.  Normally you don't have to care about that but if you are
    measuring memory consumption you may want to clean the caches.
    """
    from jinja2.environment import _spontaneous_environments
    from jinja2.lexer import _lexer_cache
    _spontaneous_environments.clear()
    _lexer_cache.clear()


def _adjancency_list(matches, score=0.61):
    """Returns an adjacency list for matches with a given score or higher"""
    graph = {}
    for pair, score in matches.items():
        if score > 0.61:
            a, b = pair
            graph.setdefault(a, []).append(b)
            graph.setdefault(b, []).append(a)
    return graph


def _timeitlike_time_format(time_seconds, precision=3):
    """Shamelessly adapted formatting from timeit.py

    Parameters
    ----------
    time_seconds : float
        The time in seconds
    precision : int
        The precision of the output. All digits.

    Returns
    -------
    str
        A timeit-like format (with usec, msec, sec).
    """
    usec = time_seconds * 1000000.0
    if usec < 1000:
        return '%.*g usec' % (precision, usec)
    else:
        msec = usec / 1000
        if msec < 1000:
            return '%.*g msec' % (precision, msec)
        else:
            sec = msec / 1000
            return '%.*g sec' % (precision, sec)


def convert_string_none(value):
    """
    this method will convert string none to the python none type
    """
    if type(value) is str:
        val = value.lower()
        if val == 'none' or val == 'null':
            return None
    return value


def getPiI2CBusNumber():
    """
    Returns the I2C bus number (/dev/i2c-#) for the Raspberry Pi being used.

    Courtesy quick2wire-python-api
    https://github.com/quick2wire/quick2wire-python-api
    """
    try:
        with open('/proc/cpuinfo', 'r') as f:
            for line in f:
                if line.startswith('Revision'):
                    return 1
    except:
        return 0


def _money_formater(amount, precision, currency=''):
    """

    Formats money to be human-readable.

    :param amount: amount of money
    :type amount: ``float``, ``str`` or ``int``
    :param precision: number of place after the decimal to round to.
    :type amount: ``int``
    :param currency: A currency code to append to the result. Defaults to none ('').
    :type currency: ``str``
    :return: formated money
    :rtype: ``str``
    """
    return ('{:,.2f}'.format(round(float(amount), precision)) + ' ' + currency
        ).strip()


def unit2uniform(x, vmin, vmax):
    """
    mapping from uniform distribution on parameter space
    to uniform distribution on unit hypercube
    """
    return vmin + (vmax - vmin) * x


@classmethod
def _from_items(cls, items):
    """Generates a new set from iterator over Item objects

        Usually used to make a new set from ``item._iter_to(other_item)``
        """
    self = cls()
    for item in items:
        self[item.key] = item.score
    return self


def _any_to_list(_input):
    """Convert anything to list."""
    if isinstance(_input, str):
        res = [_input]
    else:
        res = list(_input)
    return res


@staticmethod
def hint_check_range(ans, term):
    """
        ans = student answer
        term = list [bot, top] giving numerical range to check to see if answer is within
        """
    nans = float(eval(ans))
    [bot, top] = term
    if nans < bot:
        return False
    if nans > top:
        return False
    return True


@staticmethod
def _separated_ground_floor(base_story):
    """Get a separated ground floor from a base_story."""
    bottom = base_story.duplicate()
    bottom.multiplier = 1
    bottom.add_prefix('Ground')
    return bottom


def flexible_set_value(object, value, attr=True, null_others=True):
    """Given an object, set either value_int, value_str, or value_float as appropriate.

    :param attr: if True, the attribute is set. If False, the dictionary value is set instead.
    :param null_others: if True, the remaining values are set to None. If False, they are ignored.
    """
    all_names = ['value_float', 'value_int', 'value_str']
    if isinstance(value, float):
        assigned_name = 'value_float'
    elif isinstance(value, int):
        assigned_name = 'value_int'
    elif isinstance(value, str):
        assigned_name = 'value_str'
    else:
        raise TypeError('Unable to assign this value to any of ' + str(
            all_names))
    if attr:
        set_function = object.__setattr__
    else:
        set_function = object.__setitem__
    set_function(assigned_name, value)
    if null_others:
        for other_name in all_names:
            if other_name != assigned_name:
                set_function(other_name, None)


def get_field_name(field_dict, field):
    """
    Return a nice field name for a particular field

    Parameters
    ----------
    field_dict : dict
        dictionary containing field metadata
    field : str
        name of the field

    Returns
    -------
    field_name : str
        the field name

    """
    if 'standard_name' in field_dict:
        field_name = field_dict['standard_name']
    elif 'long_name' in field_dict:
        field_name = field_dict['long_name']
    else:
        field_name = str(field)
    field_name = field_name.replace('_', ' ')
    field_name = field_name[0].upper() + field_name[1:]
    return field_name


def _get_reference_header(header_element):
    """Parses ReferenceInput Header element
    """
    header = {}
    header['key'] = header_element.attrib('key')
    header['value'] = header_element.attrib('value')
    return header


def get_params_list(*args, **kwargs):
    """Turn dict-like arguments into an ordered list of pairs."""
    params = []
    if args:
        if len(args) > 1:
            raise TypeError('Expected at most 1 arguments, got 2')
        arg = args[0]
        if hasattr(arg, 'items'):
            params.extend(arg.items())
        else:
            params.extend(list(arg))
    if kwargs:
        params.extend(kwargs.items())
    return params


def default_object_scoper(object_name):
    """ Scopes a basic data model object name, via a tag for that object """
    return 'tag="{}"'.format(object_name)


def purge(obj, selector, comment='', metadata={}, countPurged=True):
    """Purge a Version of a Content

        Purge the given version of the object. Referenced content objects
        versions aren't purged. No recursive purging takes place.

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

        Example:

        An object got saved ten times. Two versions got purged in earlier
        calls. The histor looks like this (a ``p`` stands for purged)::

            versions: 0, 1, 2, 3p, 4p, 5, 6, 7, 8, 9
            selector: 0, 1, 2, 3,  4,  5, 6, 7, 8, 9 (countPurged==True)
            selector: 0, 1, 2, -,  -,  3, 4, 5, 6, 7 (countPurged==False)

        The comment and metadata passed may be used to store informations
        about the reasons of the purging.
        """


@classmethod
def iter_all_subclasses(cls, level=0) ->(int, type):
    """
        walk all subclasses of this class
        """
    for subclass in cls.__direct_subclasses:
        yield level, subclass
        yield from subclass.iter_all_subclasses(level=level + 1)


@staticmethod
def get_remove_cset(engine, csets):
    """Generate the cset of what files shall be removed from the livefs."""
    return csets['old_cset'].difference(csets['install'])


def format_box(box):
    """Format box description for display."""
    x0, y0, x1, y1 = box
    return '({}, {}: {}x{})'.format(x0, y0, x1 - x0, y1 - y0)


def delete(chanjo_db, sample_obj):
    """Delete sample from database."""
    chanjo_db.session.delete(sample_obj)
    chanjo_db.save()


@classmethod
def time(cls):
    """
        Get the current timestamp and timezone for the trakt server.
        """
    return cls._get('server/time')


@classmethod
def validate_batch(cls, batch, sellable, storable=None):
    """Verifies if the given |batch| is valid for the given |sellable|.

        :param batch: A |storablebatch| that is being validated
        :param sellable: A |sellable| that we should use to validate against the batch
        :param storable: If provided, the corresponding |storable| for the given
            batch, to avoid unecessary queries.
         """
    if not storable:
        product = sellable.product
        storable = product and product.storable or None
    if not batch:
        if not storable or not storable.is_batch:
            return
        raise ValueError('Batch should not be None for %r' % sellable)
    if not storable:
        raise ValueError(
            'Batches should only be used with storables, but %r is not one' %
            sellable)
    if not storable.is_batch:
        raise ValueError('This storable %r does not require a batch' % storable
            )
    if batch.storable != storable:
        raise ValueError('Given batch %r and storable %r are not related' %
            (batch, storable))


def get_availability_zone_hosts(nova, zone_name='nova'):
    """
    Returns the names of all nova active compute servers
    :param nova: the Nova client
    :param zone_name: the Nova client
    :return: a list of compute server names
    """
    out = list()
    zones = nova.availability_zones.list()
    for zone in zones:
        if zone.zoneName == zone_name and zone.hosts:
            for key, host in zone.hosts.items():
                if host['nova-compute']['available']:
                    out.append(zone.zoneName + ':' + key)
    return out


def magnitude(x):
    """
	Determine the magnitude of the given value

	:param x: Numerical value to find the magnitude of

	:return: magnitude
	:rtype: int
	"""
    from math import log10
    if x > 0.0:
        return int(log10(x))
    else:
        return 0


def p_list_iter_1(p):
    """list_iter : list_for"""
    p[0] = [], p[1]


def delete_replication_job(replicationJobId=None):
    """
    The DeleteReplicationJob API is used to delete a ReplicationJob, resulting in no further ReplicationRuns. This will delete the contents of the S3 bucket used to store SMS artifacts, but will not delete any AMIs created by the SMS service.
    See also: AWS API Documentation

    :example: response = client.delete_replication_job(
        replicationJobId='string'
    )

    :type replicationJobId: string
    :param replicationJobId: [REQUIRED] The unique identifier for a Replication Job.

    :rtype: dict
    :return: {}

    """
    pass


def zeroprice(rate, duration=9, yearly=2, face=100):
    """Compute price of zero-coupon bond given its duration."""
    periodrate = rate / float(yearly * 100)
    periods = duration * yearly
    return float(face) / (1 + periodrate) ** periods


def assert_called(_mock_self):
    """assert that the mock was called at least once."""
    self = _mock_self
    if self.call_count == 0:
        msg = "Expected '%s' to have been called." % self._mock_name or 'mock'
        raise AssertionError(msg)


def is_char_esc(c):
    """Check whether `c` is the escape character."""
    return c == u'\x1b'


def context(input):
    """Return the context/device of the input tensor.

    Parameters
    ----------
    input : Tensor
        The input tensor.

    Returns
    -------
    Context object
        A framework-specific context object.
    """
    pass


def glRotate(angle, x, y, z):
    """Multiply the current matrix by a rotation matrix

    :param angle: Specifies the angle of rotation in degrees.
    :param z: Specify the x, y, and z coordinates of a vector respectively.
    """
    pass


def snow_permittivity(rho, fs, m=0.0, fw=9070000000.0):
    """
    Calculate the dielectric permittivity of snow
    Kendra et al. (1998), IEEE

    Parameters
    ---------
    rho:        snow density       (g/cm3)
    fs:         radar frequency     (Hz)
    m:          snow wetness        (%)
    fw:         relaxation frequency of water at 0C

    Output
    ---------
    eps_ds:     snow permittivity
    """
    eps_s = 1.0 + 1.7 * rho + 0.7 * rho ** 2.0
    eps_s += 0.02 * m ** 1.015 + 0.073 * m ** 1.31 / (1 + fs / fw)
    return eps_s


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 intersection_point(l1, l2):
    """Intersection of two Lines."""
    return NotImplemented


@staticmethod
def daylight_hours(ws):
    """Return the daylight hours (:math:`N`) *[hour]* as defined in
        `FAO 56 <http://www.fao.org/tempref/SD/Reserved/Agromet/PET/FAO_Irrigation_Drainage_Paper_56.pdf>`_
        (eq. 34, p. 49):

        .. math::

            N = \\frac{24}{\\pi} \\omega_s

        :param ws: sunset hour angle (:math:`\\omega_s`) *[rad]*. See :meth:`sunset_hour_angle`
        :type ws: float or np.numpy
        :return: (*float or np.numpy*) daylight hours (:math:`N`) *[hour]*
        """
    return 7.639437268410976 * ws


def window_close():
    """Close the current Blender window

    """
    pass


def escape_html(text):
    """Replace <, >, &, " with their HTML encoded representation. Intended to
    prevent HTML errors in rendered displaCy markup.

    text (unicode): The original text.
    RETURNS (unicode): Equivalent text to be safely used within HTML.
    """
    text = text.replace('&', '&')
    text = text.replace('<', '<')
    text = text.replace('>', '>')
    text = text.replace('"', '"')
    return text


def find_variables_from_constraints(constraints):
    """
    Return a list of all "proper" Variable objects appearing in some ``c in constraints``.
    """
    variable_ids = set()
    variables = []
    for c in constraints:
        for v in c.variables():
            if v.is_proper():
                vid = id(v)
                if vid not in variable_ids:
                    variable_ids.add(vid)
                    variables.append(v)
            else:
                msg = 'Constraint \n \t' + str(c) + '\n'
                msg += 'returned an improper Variable \n \t' + str(v) + '\n'
                raise RuntimeError(msg)
    return variables


def access_settings_to_dict(control_access_params):
    """Convert a lxml.objectify.ObjectifiedElement access settings to dict.

    :param lxml.objectify.ObjectifiedElement control_access_params: an object
        containing EntityType.CONTROL_ACCESS_PARAMS XML data.

    :return: dict representation of access control settings.

    :rtype: dict
    """
    result = {}
    if hasattr(control_access_params, 'IsSharedToEveryone'):
        result['is_shared_to_everyone'] = control_access_params[
            'IsSharedToEveryone']
    if hasattr(control_access_params, 'EveryoneAccessLevel'):
        result['everyone_access_level'] = control_access_params[
            'EveryoneAccessLevel']
    if hasattr(control_access_params, 'AccessSettings') and hasattr(
        control_access_params.AccessSettings, 'AccessSetting') and len(
        control_access_params.AccessSettings.AccessSetting) > 0:
        n = 1
        for access_setting in list(control_access_params.AccessSettings.
            AccessSetting):
            access_str = 'access_settings'
            if hasattr(access_setting, 'Subject'):
                result['%s_%s_subject_name' % (access_str, n)
                    ] = access_setting.Subject.get('name')
            if hasattr(access_setting, 'Subject'):
                result['%s_%s_subject_href' % (access_str, n)
                    ] = access_setting.Subject.get('href')
            if hasattr(access_setting, 'Subject'):
                result['%s_%s_subject_type' % (access_str, n)
                    ] = access_setting.Subject.get('type')
            if hasattr(access_setting, 'AccessLevel'):
                result['%s_%s_access_level' % (access_str, n)
                    ] = access_setting.AccessLevel
            n += 1
    return result


def _obtain_nb_classifiers(model_a_name=None, model_b_name=None,
    model_c_name=None):
    """Obtains the number of different classifiers based on given model names.
        Note that EMOTIC model has already combined body backbone CNN features (which in this case are the  `model_b_name` or `model_c_name`
        features, with `VGG16_Places365` features at training stage, but for simplicity reasons only the body backbone CNN name is adjustable.

    # Arguments
        model_b_name: One of `VGG16`, `VGG19`, `ResNet50` or `None`.
        model_c_name: One of `VGG16`, `VGG19`, `ResNet50` or `None`.

    # Returns
        The number of different classifiers alongside a polished file_name
    """
    if model_b_name is None and model_c_name is not None:
        raise ValueError(
            'The models names must be set in the correct order starting from model_a --> model_b --> model_c. '
            )
    if model_b_name in {None} and model_c_name in {None}:
        nb_classifiers = 1
        file_name = model_a_name
        return nb_classifiers, file_name
    if model_b_name in {'VGG16', 'VGG19', 'ResNet50'} and model_c_name in {None
        }:
        nb_classifiers = 2
        file_name = model_a_name + '_' + model_b_name
        return nb_classifiers, file_name
    if model_b_name in {'VGG16', 'VGG19', 'ResNet50'} and model_c_name in {
        'VGG16', 'VGG19', 'ResNet50'}:
        nb_classifiers = 3
        file_name = model_a_name + '_' + model_b_name + '_' + model_c_name
        return nb_classifiers, file_name


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

        :param PaperContentArchiveType val:
        :rtype: EventType
        """
    return cls('paper_content_archive', val)


def simplex_iterator(scale, boundary=True):
    """
    Systematically iterates through a lattice of points on the 2-simplex.

    Parameters
    ----------
    scale: Int
        The normalized scale of the simplex, i.e. N such that points (x,y,z)
        satisify x + y + z == N

    boundary: bool, True
        Include the boundary points (tuples where at least one
        coordinate is zero)

    Yields
    ------
    3-tuples, There are binom(n+2, 2) points (the triangular
    number for scale + 1, less 3*(scale+1) if boundary=False
    """
    start = 0
    if not boundary:
        start = 1
    for i in range(start, scale + (1 - start)):
        for j in range(start, scale + (1 - start) - i):
            k = scale - i - j
            yield i, j, k


def array_set_diag(arr, val, row_labels, col_labels):
    """
    Sets the diagonal of an 2D array to a value. Diagonal in this case is anything where row label == column label.

    :param arr: Array to modify in place
    :type arr: np.ndarray
    :param val: Value to insert into any cells where row label == column label
    :type val: numeric
    :param row_labels: Labels which correspond to the rows
    :type row_labels: list, pd.Index
    :param col_labels: Labels which correspond to the columns
    :type col_labels: list, pd.Index
    :return: Return the number of common row and column labels
    :rtype: int
    """
    if arr.ndim != 2:
        raise ValueError('Array must be 2D')
    isect = set(row_labels).intersection(col_labels)
    for i in isect:
        arr[row_labels == i, col_labels == i] = val
    return len(isect)


def dist_init(config, dist_device):
    """Distribution Configuration"""
    from . import dist
    dist.init()
    config.DIST.RUN = True
    config.DIST.RANK = dist.rank()
    config.DIST.SIZE = dist.size()
    config.DIST.LOCAL_RANK = dist.local_rank()
    config.DIST.LOCAL_SIZE = dist.local_size()
    config.DIST.ROOT_RANK = 0
    config.DIST.IS_ROOT = config.DIST.RANK == config.DIST.ROOT_RANK
    if dist_device == 'cpu':
        devices = ['cpu' for i in range(config.DIST.LOCAL_SIZE)]
    elif dist_device == 'cuda':
        devices = [('cuda:%d' % i) for i in range(config.DIST.LOCAL_SIZE)]
    else:
        devices = dist_device.split(',')
    config.INFO.DEVICE = devices[config.DIST.LOCAL_RANK]


def _merge_statistics(stats, s):
    """ Update `stats` with vaules in `s`
    """
    stats[-1]['total_byte_size'] += s['total_byte_size']
    stats[-1]['num-rows'] += s['num-rows']
    ncols = len(stats[-1]['columns'])
    ncols_n = len(s['columns'])
    if ncols != ncols_n:
        raise ValueError(f'Column count not equal ({ncols} vs {ncols_n})')
    for i in range(ncols):
        name = stats[-1]['columns'][i]['name']
        j = i
        for ii in range(ncols):
            if name == s['columns'][j]['name']:
                break
            if ii == ncols - 1:
                raise KeyError(f'Column statistics missing for {name}')
            j = (j + 1) % ncols
        min_n = s['columns'][j]['min']
        max_n = s['columns'][j]['max']
        null_count_n = s['columns'][j]['null_count']
        min_i = stats[-1]['columns'][i]['min']
        max_i = stats[-1]['columns'][i]['max']
        stats[-1]['columns'][i]['min'] = min(min_i, min_n)
        stats[-1]['columns'][i]['max'] = max(max_i, max_n)
        stats[-1]['columns'][i]['null_count'] += null_count_n
    return True


def print_options(run_dir):
    """
    Prints options used in a previous run.

    Parameters
    ----------
    run_dir : str
        Path to a folder to with options from a previous run stored.

    """
    from neuropredict.utils import load_options
    user_options = load_options(run_dir)
    print('\n\nOptions used in the run\n{}\n'.format(run_dir))
    for key, val in user_options.items():
        if key.lower() not in ('sample_ids', 'classes'):
            print('{:>25} : {}'.format(key, val))
    return


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

        :param FileRequestCloseDetails val:
        :rtype: EventDetails
        """
    return cls('file_request_close_details', val)


def chunk(iterable, size):
    """
    chunk('ABCDEFG', 3) --> ABC DEF G
    """
    iterator = iter(iterable)
    while size:
        result = []
        try:
            for i in range(size):
                elem = next(iterator)
                result.append(elem)
            yield tuple(result)
        except StopIteration:
            if result:
                yield tuple(result)
            return


def image_to_image_filter(*args, **kwargs):
    """Procedural interface for ImageToImageFilter"""
    import itk
    instance = itk.ImageToImageFilter.New(*args, **kwargs)
    return instance.__internal_call__()


def _get_target_rectangle(left_top_pos, w, h):
    """根据左上角点和宽高求出目标区域."""
    x_min, y_min = left_top_pos
    x_middle, y_middle = int(x_min + w / 2), int(y_min + h / 2)
    left_bottom_pos, right_bottom_pos = (x_min, y_min + h), (x_min + w,
        y_min + h)
    right_top_pos = x_min + w, y_min
    middle_point = x_middle, y_middle
    rectangle = left_top_pos, left_bottom_pos, right_bottom_pos, right_top_pos
    return middle_point, rectangle


def pluralize(container_type):
    """ Convert container_type to plural name

    Simplistic logic that supports:
    group,  project,  session, subject, acquisition, analysis, collection
    """
    if container_type == 'analysis':
        return 'analyses'
    if not container_type.endswith('s'):
        return container_type + 's'
    return container_type


def p_func_arg(p):
    """func_arg : expression """
    p[0] = p[1]


def is_relative_url(url):
    """ simple method to determine if a url is relative or absolute """
    if url.startswith('#'):
        return None
    if url.find('://') > 0 or url.startswith('//'):
        return False
    return True


def init_colorama():
    """Initialize colorama if it is available.

    Returns:
        bool: result of check
    """
    try:
        import colorama
        colorama.init()
        return True
    except ImportError:
        return False


def load_book_supply(cli_supply, book_supply):
    """
    Updates CLI supply with supply from campaign book.
    But do not overwrite CLI supply with book supply - values from CLI have bigger priority.
    """
    for var, val in book_supply.items():
        if var not in cli_supply:
            cli_supply[var] = val.format(**cli_supply) if isinstance(val, str
                ) else val


def serializeModel(model):
    """Return an XML string representing the given model, as returned by
        the loadFile() or loadString() method.
        """


def matches_querytime(instance, querytime):
    """
    Checks whether the given instance satisfies the given QueryTime object.

    :param instance: an instance of Versionable
    :param querytime: QueryTime value to check against
    """
    if not querytime.active:
        return True
    if not querytime.time:
        return instance.version_end_date is None
    return instance.version_start_date <= querytime.time and (instance.
        version_end_date is None or instance.version_end_date > querytime.time)


def get_path(obj):
    """ Return the path used to store the object's json dump. """
    try:
        return obj._container.path
    except:
        pass


def _fill_function(func, globals, defaults, dict, module):
    """ Fills in the rest of function data into the skeleton function object
        that were created via _make_skel_func().
         """
    func.__globals__.update(globals)
    func.__defaults__ = defaults
    func.__dict__ = dict
    func.__module__ = module
    return func


def Color(red, green, blue, white=0):
    """Convert the provided red, green, blue color to a 24-bit color value.
    Each color component should be a value 0-255 where 0 is the lowest intensity
    and 255 is the highest intensity.
    """
    return white << 24 | red << 16 | green << 8 | blue


def within_geobox(tweet, sw_lon, sw_lat, ne_lon, ne_lat):
    """
    True if tweet is geotagged and is sent within the box specified by GeoJSON points (longitude, latitude)
    (sw_lon, sw_lat)  <-  the southwest corner
    (ne_lon, ne_lat)  <-  the northeast corner

    Example:
    ========
    within_geobox(tweet, -75.280303,39.8670041,-74.9557629,40.1379919)
    # true for tweets tweeted within a box surrounding Philadelphia
    """
    if 'coordinates' not in tweet or tweet['coordinates'
        ] is None or 'coordinates' not in tweet['coordinates']:
        return False
    coords = tweet['coordinates']['coordinates']
    return coords[0] > float(sw_lon) and coords[0] < float(ne_lon) and coords[1
        ] > float(sw_lat) and coords[1] < float(ne_lat)


@classmethod
def fromSubsample(cls, prices, datetimes, prices_per_day, aggregator=None):
    """Constructor: Creates a Stock instance by subsampling prices to a smaller
        number of prices per day than present in the original data.

        Args:
            prices (numpy.ndarray, float): A vector containing stock prices.
            datetimes (numpy.ndarray, int): A vector containing datetime.datetime
                    instances each containing date (and possible time) stamps
                    associated with the price observations.
            prices_per_day (int): Number of prices per day to sample. For example, if
                the original data has 400 prices per day, it is possible to
                subsample it to have 80 prices per day by taking every 5th price of
                the original data.
            aggregator (function): Function used to aggregate prices. If None is given,
                then the last value of the subsampling interval is used.

        Returns:
            (Stock): An instance of the Stock class.

        """
    return cls.fromDatetimes(prices, datetimes).subsample(prices_per_day,
        aggregator=aggregator)


def fmt_kcut(cut):
    """Format a |KCut|."""
    return 'KCut {}\n{}'.format(cut.direction, cut.partition)


def euclid(a, b):
    """Solve x*a + y*b = ggt(a, b) and return (x, y, ggt(a, b))"""
    x = yy = 0
    y = xx = 1
    while b:
        q = a // b
        a, b = b, a % b
        x, xx = xx - q * x, x
        y, yy = yy - q * y, y
    return xx, yy, a


def fullname(obj):
    """Returns the qualified name of an object's class

    :param obj: An object to inspect
    :returns: The name of the objects class
    """
    name = obj.__name__ if hasattr(obj, '__name__') else obj.__class__.__name__
    return '.'.join([obj.__module__, name])


def unicode_path(utf8path):
    """Turn an utf8 path into a unicode path."""
    if isinstance(utf8path, bytes):
        return utf8path.decode('utf-8')
    return utf8path


def filter_tracks(track_threshold: float=5.0):
    """Filter tracks which has weirdly looking spikes in motion curves

    :param track_threshold: Track Threshold, Filter Threshold to select problematic tracks
    :type track_threshold: float
    """
    pass


def paths_clear(only_selected: bool=False):
    """Clear path caches for all bones, hold Shift key for selected bones only

    :param only_selected: Only Selected, Only clear paths from selected bones
    :type only_selected: bool
    """
    pass


def MOD(x, y):
    """
    Divides one number by another and returns the remainder.
    See https://docs.mongodb.com/manual/reference/operator/aggregation/mod/
    for more details
    :param x: The number or field is the dividend,
    :param y: The number or field is the divisor,
    :return: Aggregation operator
    """
    return {'$mod': [x, y]}


@classmethod
def get_operation(cls, name):
    """
        Returns an operation that was previously registered with *name*.
        """
    return cls._instances[name]


def setChainForPortalTypes(pt_names, chain, verify=True):
    """ Set a chain for specific portal types.

        o If chain is None, set the chain for the portal types to be the
          default chain.

        o Permission:  Manage portal
        """


def send_raw_email(Source=None, Destinations=None, RawMessage=None, FromArn
    =None, SourceArn=None, ReturnPathArn=None, Tags=None,
    ConfigurationSetName=None):
    """
    Sends an email message, with header and content specified by the client. The SendRawEmail action is useful for sending multipart MIME emails. The raw text of the message must comply with Internet email standards; otherwise, the message cannot be sent.
    There are several important points to know about SendRawEmail :
    For the most common sending authorization use case, we recommend that you specify the SourceIdentityArn and do not specify either the FromIdentityArn or ReturnPathIdentityArn . (The same note applies to the corresponding X-headers.) If you only specify the SourceIdentityArn , Amazon SES will simply set the "From" address and the "Return Path" address to the identity specified in SourceIdentityArn . For more information about sending authorization, see the Amazon SES Developer Guide .
    See also: AWS API Documentation

    Examples
    The following example sends an email with an attachment:
    Expected Output:

    :example: response = client.send_raw_email(
        Source='string',
        Destinations=[
            'string',
        ],
        RawMessage={
            'Data': b'bytes'
        },
        FromArn='string',
        SourceArn='string',
        ReturnPathArn='string',
        Tags=[
            {
                'Name': 'string',
                'Value': 'string'
            },
        ],
        ConfigurationSetName='string'
    )

    :type Source: string
    :param Source: The identity's email address. If you do not provide a value for this parameter, you must specify a 'From' address in the raw text of the message. (You can also specify both.)
            By default, the string must be 7-bit ASCII. If the text must contain any other characters, then you must use MIME encoded-word syntax (RFC 2047) instead of a literal string. MIME encoded-word syntax uses the following form: =?charset?encoding?encoded-text?= . For more information, see RFC 2047 .
            Note
            If you specify the Source parameter and have feedback forwarding enabled, then bounces and complaints will be sent to this email address. This takes precedence over any Return-Path header that you might include in the raw text of the message.

    :type Destinations: list
    :param Destinations: A list of destinations for the message, consisting of To:, CC:, and BCC: addresses.
            (string) --

    :type RawMessage: dict
    :param RawMessage: [REQUIRED]
            The raw text of the message. The client is responsible for ensuring the following:
            Message must contain a header and a body, separated by a blank line.
            All required header fields must be present.
            Each part of a multipart MIME message must be formatted properly.
            MIME content types must be among those supported by Amazon SES. For more information, go to the Amazon SES Developer Guide .
            Must be base64-encoded.
            Data (bytes) -- [REQUIRED]The raw data of the message. The client must ensure that the message format complies with Internet email standards regarding email header fields, MIME types, MIME encoding, and base64 encoding.
            The To:, CC:, and BCC: headers in the raw message can contain a group list.
            If you are using SendRawEmail with sending authorization, you can include X-headers in the raw message to specify the 'Source,' 'From,' and 'Return-Path' addresses. For more information, see the documentation for SendRawEmail .
            Warning
            Do not include these X-headers in the DKIM signature, because they are removed by Amazon SES before sending the email.
            For more information, go to the Amazon SES Developer Guide .

    :type FromArn: string
    :param FromArn: This parameter is used only for sending authorization. It is the ARN of the identity that is associated with the sending authorization policy that permits you to specify a particular 'From' address in the header of the raw email.
            Instead of using this parameter, you can use the X-header X-SES-FROM-ARN in the raw message of the email. If you use both the FromArn parameter and the corresponding X-header, Amazon SES uses the value of the FromArn parameter.
            Note
            For information about when to use this parameter, see the description of SendRawEmail in this guide, or see the Amazon SES Developer Guide .

    :type SourceArn: string
    :param SourceArn: This parameter is used only for sending authorization. It is the ARN of the identity that is associated with the sending authorization policy that permits you to send for the email address specified in the Source parameter.
            For example, if the owner of example.com (which has ARN arn:aws:ses:us-east-1:123456789012:identity/example.com ) attaches a policy to it that authorizes you to send from user@example.com , then you would specify the SourceArn to be arn:aws:ses:us-east-1:123456789012:identity/example.com , and the Source to be user@example.com .
            Instead of using this parameter, you can use the X-header X-SES-SOURCE-ARN in the raw message of the email. If you use both the SourceArn parameter and the corresponding X-header, Amazon SES uses the value of the SourceArn parameter.
            Note
            For information about when to use this parameter, see the description of SendRawEmail in this guide, or see the Amazon SES Developer Guide .

    :type ReturnPathArn: string
    :param ReturnPathArn: This parameter is used only for sending authorization. It is the ARN of the identity that is associated with the sending authorization policy that permits you to use the email address specified in the ReturnPath parameter.
            For example, if the owner of example.com (which has ARN arn:aws:ses:us-east-1:123456789012:identity/example.com ) attaches a policy to it that authorizes you to use feedback@example.com , then you would specify the ReturnPathArn to be arn:aws:ses:us-east-1:123456789012:identity/example.com , and the ReturnPath to be feedback@example.com .
            Instead of using this parameter, you can use the X-header X-SES-RETURN-PATH-ARN in the raw message of the email. If you use both the ReturnPathArn parameter and the corresponding X-header, Amazon SES uses the value of the ReturnPathArn parameter.
            Note
            For information about when to use this parameter, see the description of SendRawEmail in this guide, or see the Amazon SES Developer Guide .

    :type Tags: list
    :param Tags: A list of tags, in the form of name/value pairs, to apply to an email that you send using SendRawEmail . Tags correspond to characteristics of the email that you define, so that you can publish email sending events.
            (dict) --Contains the name and value of a tag that you can provide to SendEmail or SendRawEmail to apply to an email.
            Message tags, which you use with configuration sets, enable you to publish email sending events. For information about using configuration sets, see the Amazon SES Developer Guide .
            Name (string) -- [REQUIRED]The name of the tag. The name must:
            Contain only ASCII letters (a-z, A-Z), numbers (0-9), underscores (_), or dashes (-).
            Contain less than 256 characters.
            Value (string) -- [REQUIRED]The value of the tag. The value must:
            Contain only ASCII letters (a-z, A-Z), numbers (0-9), underscores (_), or dashes (-).
            Contain less than 256 characters.

    :type ConfigurationSetName: string
    :param ConfigurationSetName: The name of the configuration set to use when you send an email using SendRawEmail .

    :rtype: dict
    :return: {
        'MessageId': 'string'
    }

    :returns:
    Source (string) -- The identity's email address. If you do not provide a value for this parameter, you must specify a "From" address in the raw text of the message. (You can also specify both.)
    By default, the string must be 7-bit ASCII. If the text must contain any other characters, then you must use MIME encoded-word syntax (RFC 2047) instead of a literal string. MIME encoded-word syntax uses the following form: =?charset?encoding?encoded-text?= . For more information, see RFC 2047 .

    Note
    If you specify the Source parameter and have feedback forwarding enabled, then bounces and complaints will be sent to this email address. This takes precedence over any Return-Path header that you might include in the raw text of the message.

    Destinations (list) -- A list of destinations for the message, consisting of To:, CC:, and BCC: addresses.

    (string) --

    RawMessage (dict) -- [REQUIRED]
    The raw text of the message. The client is responsible for ensuring the following:

    Message must contain a header and a body, separated by a blank line.
    All required header fields must be present.
    Each part of a multipart MIME message must be formatted properly.
    MIME content types must be among those supported by Amazon SES. For more information, go to the Amazon SES Developer Guide .
    Must be base64-encoded.

    Data (bytes) -- [REQUIRED]The raw data of the message. The client must ensure that the message format complies with Internet email standards regarding email header fields, MIME types, MIME encoding, and base64 encoding.
    The To:, CC:, and BCC: headers in the raw message can contain a group list.
    If you are using SendRawEmail with sending authorization, you can include X-headers in the raw message to specify the "Source," "From," and "Return-Path" addresses. For more information, see the documentation for SendRawEmail .

    Warning
    Do not include these X-headers in the DKIM signature, because they are removed by Amazon SES before sending the email.

    For more information, go to the Amazon SES Developer Guide .

    FromArn (string) -- This parameter is used only for sending authorization. It is the ARN of the identity that is associated with the sending authorization policy that permits you to specify a particular "From" address in the header of the raw email.
    Instead of using this parameter, you can use the X-header X-SES-FROM-ARN in the raw message of the email. If you use both the FromArn parameter and the corresponding X-header, Amazon SES uses the value of the FromArn parameter.

    Note
    For information about when to use this parameter, see the description of SendRawEmail in this guide, or see the Amazon SES Developer Guide .

    SourceArn (string) -- This parameter is used only for sending authorization. It is the ARN of the identity that is associated with the sending authorization policy that permits you to send for the email address specified in the Source parameter.
    For example, if the owner of example.com (which has ARN arn:aws:ses:us-east-1:123456789012:identity/example.com ) attaches a policy to it that authorizes you to send from user@example.com , then you would specify the SourceArn to be arn:aws:ses:us-east-1:123456789012:identity/example.com , and the Source to be user@example.com .
    Instead of using this parameter, you can use the X-header X-SES-SOURCE-ARN in the raw message of the email. If you use both the SourceArn parameter and the corresponding X-header, Amazon SES uses the value of the SourceArn parameter.

    Note
    For information about when to use this parameter, see the description of SendRawEmail in this guide, or see the Amazon SES Developer Guide .

    ReturnPathArn (string) -- This parameter is used only for sending authorization. It is the ARN of the identity that is associated with the sending authorization policy that permits you to use the email address specified in the ReturnPath parameter.
    For example, if the owner of example.com (which has ARN arn:aws:ses:us-east-1:123456789012:identity/example.com ) attaches a policy to it that authorizes you to use feedback@example.com , then you would specify the ReturnPathArn to be arn:aws:ses:us-east-1:123456789012:identity/example.com , and the ReturnPath to be feedback@example.com .
    Instead of using this parameter, you can use the X-header X-SES-RETURN-PATH-ARN in the raw message of the email. If you use both the ReturnPathArn parameter and the corresponding X-header, Amazon SES uses the value of the ReturnPathArn parameter.

    Note
    For information about when to use this parameter, see the description of SendRawEmail in this guide, or see the Amazon SES Developer Guide .

    Tags (list) -- A list of tags, in the form of name/value pairs, to apply to an email that you send using SendRawEmail . Tags correspond to characteristics of the email that you define, so that you can publish email sending events.

    (dict) --Contains the name and value of a tag that you can provide to SendEmail or SendRawEmail to apply to an email.
    Message tags, which you use with configuration sets, enable you to publish email sending events. For information about using configuration sets, see the Amazon SES Developer Guide .

    Name (string) -- [REQUIRED]The name of the tag. The name must:

    Contain only ASCII letters (a-z, A-Z), numbers (0-9), underscores (_), or dashes (-).
    Contain less than 256 characters.

    Value (string) -- [REQUIRED]The value of the tag. The value must:

    Contain only ASCII letters (a-z, A-Z), numbers (0-9), underscores (_), or dashes (-).
    Contain less than 256 characters.

    ConfigurationSetName (string) -- The name of the configuration set to use when you send an email using SendRawEmail .

    """
    pass


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

    The ".dev0" means dirty.

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


def getLoops(main_twist, conjugate_by):
    """
    Returns two (homotopy classes of) loops for a twist.

    Pass in a main_twist (integer) and conjugate_by (list of integers);
    the braid you should construct is:
        conjugate_by main_twist conjugate_by^{-1}
    This braid corresponds to an element [f] of the mapping class group
    MCG(D) of a punctured disk D. MCG(D) acts on the fundamental group
    of D (with some basepoint fixed below the punctures).

    The return value encodes the homotopy classes of [f](r_1) and [f](r_2)
    where r_1 and r_2 are loops enclosing the punctures corresponding to
    the two strings involved in main_twist.

    The return value is formatted as [loop1, loop2].
    Each loop is written as a list of gaps (in +/- 1 thru n+1) through
    which it passes. Gap i lies between punctures i and i+1.

    A positive sign indicates an approach from below.
    As an artifact of the format and the choice of basepoint,
    each loop will alternate signs and begin with a positive entry.

    There is some ambiguity about whether the action described above
    is a left action or right action. I have chosen to take it as a left
    action in this implementation, but as long as you can apply an
    appropriate automorphism of the braid group, it shouldn't matter.

    """
    paths = [[main_twist + 1, -main_twist], [main_twist + 2, -main_twist - 1]]
    for twist in reversed(conjugate_by):
        for i in range(len(paths)):
            a = []
            for x in paths[i]:
                if abs(x) == abs(twist) + 1:
                    if twist < 0:
                        a.extend([x + 1, -x, x - 1])
                    else:
                        a.extend([x - 1, -x, x + 1])
                else:
                    a.append(x)
            paths[i] = a
    return paths


def remove_theater(theater_name):
    """Remove theater from you list of favorite theaters"""
    pass


def test_sqla_utf8_chain():
    """Test insert and select of a UTF-8 string."""
    from sqlalchemy import Table, Column
    from sqlalchemy.types import CHAR, VARBINARY
    from sqlalchemy.ext.declarative import declarative_base
    from invenio_ext.sqlalchemy import db
    print('Test UTF-8 support... \t', end='')
    tmptable = 'test__invenio__utf8'
    beta_in_utf8 = 'β'
    Base = declarative_base()
    table = Table(tmptable, Base.metadata, Column('x', CHAR(1)), Column('y',
        VARBINARY(2)))
    if table.exists(bind=db.engine):
        table.drop(bind=db.engine)
    table.create(bind=db.engine)
    db.engine.execute(table.insert(), x=beta_in_utf8, y=beta_in_utf8)
    result = db.engine.execute(table.select().where(table.c.x ==
        beta_in_utf8).where(table.c.y == beta_in_utf8))
    assert result.rowcount == 1
    for row in result:
        assert row['x'] == beta_in_utf8.decode('utf-8')
        assert row['y'] == beta_in_utf8
    table.drop(bind=db.engine)
    print(' [OK]')


@classmethod
def set_default_num_threads(cls, num_threads):
    """Set the default number of threads for ITK calls

        This method is used to set the default number of ITK threads for all
        the ANTS interfaces. However, setting this will not update the output
        type for any existing instances.  For these, assign the
        <instance>.inputs.num_threads
        """
    cls._num_threads = num_threads


def encode_timestamps(t1, t2=None, t3=None, explicit=False):
    """
    Encode up to three timestamps into a string. Unlike a Timestamp object, the
    encoded string does NOT used fixed width fields and consequently no
    relative chronology of the timestamps can be inferred from lexicographic
    sorting of encoded timestamp strings.

    The format of the encoded string is:
        <t1>[<+/-><t2 - t1>[<+/-><t3 - t2>]]

    i.e. if t1 = t2 = t3 then just the string representation of t1 is returned,
    otherwise the time offsets for t2 and t3 are appended. If explicit is True
    then the offsets for t2 and t3 are always appended even if zero.

    Note: any offset value in t1 will be preserved, but offsets on t2 and t3
    are not preserved. In the anticipated use cases for this method (and the
    inverse decode_timestamps method) the timestamps passed as t2 and t3 are
    not expected to have offsets as they will be timestamps associated with a
    POST request. In the case where the encoding is used in a container objects
    table row, t1 could be the PUT or DELETE time but t2 and t3 represent the
    content type and metadata times (if different from the data file) i.e.
    correspond to POST timestamps. In the case where the encoded form is used
    in a .meta file name, t1 and t2 both correspond to POST timestamps.
    """
    form = '{0}'
    values = [t1.short]
    if t2 is not None:
        t2_t1_delta = t2.raw - t1.raw
        explicit = explicit or t2_t1_delta != 0
        values.append(t2_t1_delta)
        if t3 is not None:
            t3_t2_delta = t3.raw - t2.raw
            explicit = explicit or t3_t2_delta != 0
            values.append(t3_t2_delta)
        if explicit:
            form += '{1:+x}'
            if t3 is not None:
                form += '{2:+x}'
    return form.format(*values)


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


def _union_all(iterables):
    """Union entries in ``iterables`` into a set.
    """
    return set().union(*iterables)


def start_timer():
    """ Module that calculates the total time of the execution of the program.
    NB: Optionnal. If the module 'time' in not found, this will be skipped."""
    try:
        global time
        import time
        return time.time()
    except ModuleNotFoundError:
        print(
            'The module "time" was not found. The executation time of this program will not be displayed.'
            )
        return 0


@staticmethod
def create_initial_state(nclasses):
    """Factory method returning a model with random initial parameters.

        Arguments
        ---------
        nclasses : int
            Number of label classes
        """
    raise NotImplementedError()


def asnumpy(input):
    """Convert the input tensor to numpy array.

    The data is copied.

    Parameters
    ----------
    input : Tensor
        The input tensor.

    Returns
    -------
    numpy.ndarray
        Numpy array.
    """
    pass


def humanize_name(name):
    """
    "Humanize" camel case or Python variable name.

    Usage:
        >>> humanize_name('SomeName')
        'some name'
    """
    name = name.replace('_', ' ')
    parts = []
    buffer = []
    is_last_lower = False
    for chr in name:
        if chr.isupper():
            if is_last_lower:
                parts.append(''.join(buffer))
                buffer = [chr]
            else:
                buffer.append(chr)
            is_last_lower = False
        else:
            is_last_lower = True
            buffer.append(chr)
    parts.append(''.join(buffer))
    return ' '.join(parts)


def _set_class_module(module_class):
    """Initialize the module."""
    global _CLASS_MODULE
    _CLASS_MODULE = module_class


@classmethod
def _import_it(cls):
    """
        Imports Future from concurrent.futures.
        """
    from concurrent.futures import Future
    return Future


def wid_to_gid(wid):
    """Calculate gid of a worksheet from its wid."""
    widval = wid[1:] if len(wid) > 3 else wid
    xorval = 474 if len(wid) > 3 else 31578
    return str(int(widval, 36) ^ xorval)


def trunc(data=None, name=None, attr=None, out=None, **kwargs):
    """Return the element-wise truncated value of the input.

    The truncated value of the scalar x is the nearest integer i which is closer to
    zero than x is. In short, the fractional part of the signed number x is discarded.

    Example::

       trunc([-2.1, -1.9, 1.5, 1.9, 2.1]) = [-2., -1.,  1.,  1.,  2.]

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

       - trunc(default) = default
       - trunc(row_sparse) = row_sparse
       - trunc(csr) = csr

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

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

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

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


def popnames_parser(popnames_file):
    """
    Parses a file with population names and returns a list with these names.
    The order must be the same as in the baypass input files (geno and env).
    """
    popnames = []
    popfile = open(popnames_file, 'r')
    for lines in popfile:
        popnames.append(lines.strip())
    popfile.close()
    return popnames


def axis_symetry(a, b):
    """
    definition: func(a, b) {...}
    objective : returns the 'x' of the axis symetry formula
                x = -b/2a
    """
    result = -b / (2 * a)
    return result


def _slice_at_axis(sl, axis):
    """
    Construct tuple of slices to slice an array in the given dimension.

    Parameters
    ----------
    sl : slice
        The slice for the given dimension.
    axis : int
        The axis to which `sl` is applied. All other dimensions are left
        "unsliced".

    Returns
    -------
    sl : tuple of slices
        A tuple with slices matching `shape` in length.

    Examples
    --------
    >>> _slice_at_axis(slice(None, 3, -1), 1)
    (slice(None, None, None), slice(None, 3, -1), (...,))
    """
    return (slice(None),) * axis + (sl,) + (...,)


def OmegaSnglCompare(sim, burst, offsetvector, delta_t=10.0):
    """
	Return False (injection matches event) if the time of the sim and
	the peak time of the burst event differ by less than or equal to
	delta_t seconds.
	"""
    return abs(float(sim.time_at_instrument(burst.ifo, offsetvector) -
        burst.peak)) > delta_t


def formula_2003_01_01(foyer_fiscal, period, parameters):
    """
        Mécénat d'entreprise (case 7US)
        2003-
        """
    f7us = foyer_fiscal('f7us', period)
    return f7us


def set_start_datetime(value):
    """Sets the start datetime to value (DateTime)"""


def decorate(string, decoration='=', n1=10, n2=None):
    """
    Decorate a string to emphasise it

    Args:
        :string: string to decorate
        :decoration: string used
        :n1: prefix multiplier
        :n2: suffix multiplier

    Returns:
        :mod_string: modified string
    """
    if not isinstance(string, str):
        raise TypeError("'string' must be of type str")
    if not isinstance(decoration, str):
        raise TypeError("'decoration' must be of type str")
    if not isinstance(n1, int):
        raise TypeError("'n1' must be of type int")
    if n2 is None:
        n2 = n1
    mod_string = decoration * n1 + ' ' + string + ' ' + decoration * n2
    return mod_string


@staticmethod
def getJavaPackage():
    """ Returns package name String. """
    return 'com.microsoft.ml.spark.cognitive.BingImageSearch'


@classmethod
def createFromPidFile(cls, pidfile):
    """
            createFromPidFile - Creates a Program from a pidfile.

            @param pidfile <str> - Path to pid file

            @raises - An exception if no process can be created from the pidfile. Specific exception depends on error. Not validated with proctitle_re, do that in an additional call.
        """
    with open(pidfile, 'rt') as f:
        pid = f.read().strip()
    pid = int(pid)
    procCmdline = cls._getProcCmdline(pid)
    return cls(pidfile, pid, running=True, **procCmdline)


def calculate_max_speed_velocity_ratio(speed_velocity_ratios):
    """
    Calculates the maximum speed velocity ratio of the gear box [h*RPM/km].

    :param speed_velocity_ratios:
        Speed velocity ratios of the gear box [h*RPM/km].
    :type speed_velocity_ratios: dict[int | float]

    :return:
        Maximum speed velocity ratio of the gear box [h*RPM/km].
    :rtype: float
    """
    return speed_velocity_ratios[max(speed_velocity_ratios)]


@classmethod
def on_mapping_configuration_init(cls, controller):
    """
    Callback function that is triggered, when the configuration of a controller starts

    :param controller:              the controller that should be configured
    :type controller:               steuer.Controller
    """
    print('EVENT:' + 'Start configure controller type :{0}'.format(
        controller.name))


def camel_to_underscore(string):
    """Translates amazon Camelcased strings to
    lowercased underscored strings"""
    res = []
    for index, char in enumerate(string):
        if index != 0 and char.isupper():
            res.extend(['_', char.lower()])
        else:
            res.extend([char.lower()])
    return ''.join(res)


def plot_registration(anat_nii, div_id, plot_params=None, order=('z', 'x',
    'y'), cuts=None, estimate_brightness=False, label=None, contour=None,
    compress='auto', overlay=None, overlay_params=None):
    """
    Plot the foreground and background views.

    Default order is: axial, coronal, sagittal
    """
    from uuid import uuid4
    from lxml import etree
    import matplotlib.pyplot as plt
    from nilearn.plotting import plot_anat
    from svgutils.transform import SVGFigure
    from niworkflows.viz.utils import robust_set_limits, extract_svg, SVGNS
    plot_params = plot_params or {}
    if cuts is None:
        raise NotImplementedError
    out_files = []
    if estimate_brightness:
        plot_params = robust_set_limits(anat_nii.get_fdata(dtype='float32')
            .reshape(-1), plot_params)
    for i, mode in enumerate(list(order)):
        plot_params['display_mode'] = mode
        plot_params['cut_coords'] = cuts[mode]
        if i == 0:
            plot_params['title'] = label
        else:
            plot_params['title'] = None
        display = plot_anat(anat_nii, **plot_params)
        if overlay is not None:
            _overlay_params = {'vmin': overlay.get_fdata(dtype='float32').
                min(), 'vmax': overlay.get_fdata(dtype='float32').max(),
                'cmap': plt.cm.gray, 'interpolation': 'nearest'}
            _overlay_params.update(overlay_params)
            display.add_overlay(overlay, **_overlay_params)
        if contour is not None:
            display.add_contours(contour, colors='g', levels=[0.5],
                linewidths=0.5)
        svg = extract_svg(display, compress=compress)
        display.close()
        xml_data = etree.fromstring(svg)
        find_text = etree.ETXPath("//{%s}g[@id='figure_1']" % SVGNS)
        find_text(xml_data)[0].set('id', '%s-%s-%s' % (div_id, mode, uuid4()))
        svg_fig = SVGFigure()
        svg_fig.root = xml_data
        out_files.append(svg_fig)
    return out_files


def rms_prop_step(p, lr, sqr_avg, eps, grad_avg=None, **kwargs):
    """Step for SGD with momentum with `lr`"""
    denom = sqr_avg.sqrt().add_(eps)
    p.data.addcdiv_(grad_avg if grad_avg is not None else p.grad, denom,
        value=-lr)


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

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

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

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

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

    """
    pass


@classmethod
def _to_int(cls, string_):
    """Converts an unformatted string of this type to an int

        Must be implemented by subclass"""
    raise NotImplementedError


def get_dn_path(dn):
    """
    节点向上追溯至root的节点路径
    :example: cn=dev,cn=IT,ou=group,dc=example,dc=org
    - > [
        cn=dev,cn=IT,ou=group,dc=example,dc=org,
        cn=IT,ou=group,dc=example,dc=org,
        ou=group,dc=example,dc=org,
        dc=example,dc=org,
        dc=org,
    ]
    """
    bits = dn.split(',')
    res = []
    for index in range(len(bits)):
        res.append(','.join(bits[-index - 1:]))
    res.reverse()
    return res


def is_dynamic(field_def, field_value=None):
    """Implements two checks for a dynamic field defintion."""
    if field_value is not None:
        return field_def.is_dynamic and isinstance(field_value, bytes)
    else:
        return field_def.is_dynamic


def _validate_course(course: str) ->str:
    """Validates course is a four digit number,
     otherwise adds zero(s) to create four digit number or,
     raises an exception.
     """
    if len(course) > 4 or not course.isdigit():
        raise ValueError('Invalid course number')
    elif len(course) == 4:
        return course
    return '0' * (4 - len(course)) + course


def html(text):
    """
    Macro tag <<html>>...<</html>>
    Pass-trought for html code (or other stuff)
    """
    return text


def is_custom_resource(resource_type):
    """ Return True if resource_type is a custom resource """
    return resource_type and (resource_type ==
        'AWS::CloudFormation::CustomResource' or resource_type.startswith(
        'Custom::'))


def train_test_val_split(X, y, test_size=0.2, val_size=0.1):
    """Performs 2 successive train_test_splits to produce a training, testing, and validation dataset"""
    from sklearn.model_selection import train_test_split
    if val_size == 0:
        X_train, X_test, y_train, y_test = train_test_split(X, y, test_size
            =test_size)
        return X_train, X_test, y_train, y_test
    else:
        first_split_size = test_size + val_size
        second_split_size = val_size / (test_size + val_size)
        X_train, X_test_val, y_train, y_test_val = train_test_split(X, y,
            test_size=first_split_size)
        X_test, X_val, y_test, y_val = train_test_split(X_test_val,
            y_test_val, test_size=second_split_size)
        return X_train, X_test, X_val, y_train, y_test, y_val


def _icon_classes(name):
    """
    Given the name of an icon, return the classes that will render it
    """
    if name.startswith('fa-'):
        return 'fa ' + name
    if name.startswith('glyphicon'):
        return 'glyphicon ' + name
    return name


def handleSubmit(actions, data, default_validate=None):
    """Handle a submit."""
    for action in actions:
        if action.submitted():
            errors = action.validate(data)
            if errors is None and default_validate is not None:
                errors = default_validate(action, data)
            return errors, action
    return None, None


@classmethod
def has_archiving(cls):
    """Returns whether it supports archiving entries on the fetch process.

        :returns: this backend does not support entries archive
        """
    return False


@classmethod
def get_global(cls, convert=None):
    """
        This endpoint displays the global data found at the top of coinmarketcap.com.
        Args:
            convert(str): return pricing info in terms of another currency.
            Valid fiat currency values are: "AUD", "BRL", "CAD", "CHF", "CLP", "CNY", "CZK", "DKK",
                                                           "EUR", "GBP", "HKD", "HUF", "IDR", "ILS", "INR", "JPY",
                                                           "KRW", "MXN", "MYR", "NOK", "NZD", "PHP", "PKR", "PLN",
                                                           "RUB", "SEK", "SGD", "THB", "TRY", "TWD", "ZAR"
            Valid crypto currency values are: "BTC", "ETH" "XRP", "LTC", and "BCH"
        Returns:
        {
            "data": {
                "active_cryptocurrencies": 1594,
                "active_markets": 10526,
                "bitcoin_percentage_of_market_cap": 37.65,
                "quotes": {
                    "USD": {
                        "total_market_cap": 407690157494.0,
                        "total_volume_24h": 30969801118.0
                    }
                },
                "last_updated": 1525137271
            },
            "metadata": {
                "timestamp": 1525237332,
                "error": null
            }
        }
        """
    path = '/global/'
    params = {'convert': convert}
    res = cls._get(path, params=params)
    return res


def arg_byref(args, offset=-1):
    """Returns the pointer argument's by-reference value."""
    return args[offset]._obj.value


def setTimeout(timeout):
    """ Set a timeout value in seconds
        """


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


def desigil(value, **sigils):
    """
    Parse a ``{sigil: value}`` expression and unpack the value inside.
    """
    if isinstance(value, dict) and len(value) == 1:
        for sig, typ in sigils.items():
            try:
                inner = value[sig]
            except KeyError:
                pass
            else:
                if not isinstance(inner, typ):
                    raise ValueError(
                        'This Dynamo value {} must have a member encoded as type {}'
                        .format(sig, typ.__name__))
                return sig, inner
    for sig, typ in sigils.items():
        break
    raise ValueError(
        'This Dynamo value must be encoded as a single-item dict {%r: %s}' %
        (sig, typ.__name__))


@classmethod
def register_metric(cls, meter):
    """Append a new meter to the meters list.

        Args:
            meter: Metrics meter.
        """
    cls.meters.append(meter)


def alpha(requestContext, seriesList, alpha):
    """
    Assigns the given alpha transparency setting to the series. Takes a float
    value between 0 and 1.
    """
    for series in seriesList:
        series.options['alpha'] = alpha
    return seriesList


@classmethod
def isvalid(cls):
    """Ensure the user has the credential to use the file/repository."""
    return True


def fromOpenIDRequest(cls, request):
    """Create a simple teams extension request that contains the
        team names that were requested in the OpenID request with the
        given arguments

        @param request: The OpenID request
        @type request: openid.server.CheckIDRequest

        @returns: The newly created teams extension request
        @rtype: C{L{TeamsRequest}}
        """
    self = cls()
    message = request.message.copy()
    args = message.getArgs(self.ns_uri)
    self.parseExtensionArgs(args)
    return self


@classmethod
def _validate_token_class(cls, token_class):
    """Validate token_class.

        Ensures that the token_class supplied has `blacklist_jti` and `get_blacklisted`
        methods

        :param token_class: ORM database model.
        :return: token_class
        :raises RuntimeError if token_class is missing required methods.
        """
    if getattr(token_class, 'blacklist_jti') is None:
        raise RuntimeError(
            'token_class must have a blacklist_jti method that persists data to database'
            )
    if getattr(token_class, 'get_blacklisted') is None:
        raise RuntimeError(
            'token_class must have a get_blacklisted method that returns a list of blacklisted tokens with attr `jti`'
            )
    return token_class


@staticmethod
def remove_ts3_smilies(text):
    """
        Place a zero-width space inbetween characters which are transformed on display into ts3 smilies.

        Does not replace ':/' as this messes up the linking of [url=https://...][/url].

        :param text: text to be replaced in
        :return: text, but with disabled smilies
        """
    return str(text).replace(':)', ':\u200b)').replace(':D', ':\u200bD'
        ).replace('8)', '8\u200b)').replace(';)', ';\u200b)').replace(':(',
        ':\u200b(').replace(':C', ':\u200bC').replace(':0', ':\u200b0'
        ).replace(':x', ':\u200bx').replace(':P', ':\u200bP')


def clear_builtins(attrs):
    """
    Clears the builtins from an ``attrs`` dict

    Returns a new dict without the builtins

    """
    new_attrs = {}
    for key in attrs.keys():
        if not (key.startswith('__') and key.endswith('__')):
            new_attrs[key] = attrs[key]
    return new_attrs


def index_of_str(s1, s2):
    """
        索引字符串再另一个字符串中第一次出现的位置，可以用str.rfind代替
        s1为长字符串，s2为短字符串，如果s1被切片后传入函数
        那么s2在原s1中的位置应该再加上切片的起始位置，可用str.rfind替换
    """
    lt = s1.split(s2, 1)
    if s2 not in s1:
        return None
    elif len(lt) == 1:
        return -1
    return len(lt[0])


@classmethod
def _parse_trace_logging(cls, trace_def):
    """Parse tracing by Python's logging facilities.

        :param trace_def: definition of tracing as supplied in the YAML file
        """
    if trace_def is True:
        cls._trace_logging.append(trace_def)


def crop_string_middle(s, length=32, cropper='...'):
    """Crops string by adding ... in the middle.

    Args:
        s: String.
        length: Length to crop to.

    Returns:
        Cropped string
    """
    if len(s) <= length:
        return s
    half = (length - len(cropper)) // 2
    return s[:half] + cropper + s[-half - 1:]


@classmethod
def get(cls, key):
    """
        Gets the nucleic acid corresponding to either the residue name or
        abbreviation. It is case-insensitive.

        Parameters
        ----------
        key : str
            abbreviation or residue name

        Returns
        -------
        residue : :class:`RNAResidue`
            The residue corresponding to the given key

        Raises
        ------
        KeyError if ``key`` is not a recognized residue name or abbreviation for
        an RNA residue.
        """
    try:
        if key[-1] in '35':
            return cls._all_residues_by_abbr[key[:-1].upper()]
        return cls._all_residues_by_abbr[key.upper()]
    except KeyError:
        return cls._all_residues_by_name[key.upper()]


def compute_sizes(sizes, size_fn, scaling_factor, scaling_method, base_size):
    """
    Scales point sizes according to a scaling factor,
    base size and size_fn, which will be applied before
    scaling.
    """
    if sizes.dtype.kind not in ('i', 'f'):
        return None
    if scaling_method == 'area':
        pass
    elif scaling_method == 'width':
        scaling_factor = scaling_factor ** 2
    else:
        raise ValueError(
            'Invalid value for argument "scaling_method": "{}". Valid values are: "width", "area".'
            .format(scaling_method))
    sizes = size_fn(sizes)
    return base_size * scaling_factor * sizes


def check_availability():
    """
        Return a boolean indicating whether a call to this factory
        will return a driver (True) or will raise an error (False).
        """


def collection_isolate(extend: bool=False):
    """Hide all but this collection and its parents

    :param extend: Extend, Extend current visible collections
    :type extend: bool
    """
    pass


def get_orders_by_loc(phase_proto, orderable_locations, powers):
    """ Returns a dictionary with loc as key and its corresponding order as value
        Note: only the locs in orderable_locations are included in the dictionary

        :param phase_proto: A `.proto.game.SavedGame.Phase` object from the dataset.
        :param orderable_locations: A list of locs from which we want the orders
        :param powers: A list of powers for which to retrieve orders
        :return: A dictionary with locs as key, and their corresponding order as value
               (e.g. {'PAR': 'A PAR - MAR'})
    """
    orders_by_loc = {}
    for power_name in phase_proto.orders:
        if power_name not in powers:
            continue
        for order in phase_proto.orders[power_name].value:
            order_loc = order.split()[1]
            if order_loc not in orderable_locations and order_loc[:3
                ] not in orderable_locations:
                continue
            orders_by_loc[order_loc[:3]] = order
    return orders_by_loc


def frame_jump():
    """Set the current frame to the average frame value of selected keyframes

    """
    pass


def pad_line(line):
    """Helper function to pad line to 80 characters in case it is shorter"""
    size_of_line = len(line)
    if size_of_line < 80:
        padding = 80 - size_of_line + 1
        line = line.strip('\n') + ' ' * padding + '\n'
    return line[:81]


def hex_to_int(hex_string, bits=16):
    """Convert a four-character hex string to an integer.

    This uses two's complement in decoding the hex string, per Huber's
    manual. This also manages the value '7fff' (32767), which is
    Huber's version of a command-not-implemented error.
    """
    number = int(hex_string, bits)
    if number == 32767:
        raise IOError('Command not enabled on this Huber model.')
    if number >> bits - 1 == 1:
        number -= 1 << bits
    return number


def int_to_alpha(n, upper=True):
    """Generates alphanumeric labels of form A-Z, AA-ZZ etc."""
    casenum = 65 if upper else 97
    label = ''
    count = 0
    if n == 0:
        return str(chr(n + casenum))
    while n >= 0:
        mod, div = n % 26, n
        for _ in range(count):
            div //= 26
        div %= 26
        if count == 0:
            val = mod
        else:
            val = div
        label += str(chr(val + casenum))
        count += 1
        n -= 26 ** count
    return label[::-1]


def df_drop_nanrows(data, destructive=False):
    """Drop rows based on presences of nan values. The optimal
    approach, especially for small datasets, seems to be to first
    start with df_drop_nancols, then follow with df_drop_nanrows,
    and then do one more pass with df_drop_nancols.

    data : pandas dataframe
        A pandas dataframe to be processed
    destructive : bool
        If set to True, will make changes directly to the dataframe which
        may be useful with very large dataframes instead of making a copy.

    """
    if destructive is False:
        data = data.copy(deep=True)
    return data.dropna()


def failover_group_failover(client, resource_group_name, server_name,
    failover_group_name, allow_data_loss=False):
    """
    Failover a failover group.
    """
    failover_group = client.get(resource_group_name=resource_group_name,
        server_name=server_name, failover_group_name=failover_group_name)
    if failover_group.replication_role == 'Primary':
        return
    if allow_data_loss:
        failover_func = client.force_failover_allow_data_loss
    else:
        failover_func = client.failover
    return failover_func(resource_group_name=resource_group_name,
        server_name=server_name, failover_group_name=failover_group_name)


def is_int(s):
    """ :return True iff s can be converted to an integer using int() """
    try:
        int(s)
        return True
    except ValueError:
        return False


@staticmethod
def _fix_result_tuple__single_entity(row):
    """ Fix the result tuple: get the first Entity only """
    return row[0]


def image_field_names():
    """Returns the names of all image fields"""


@staticmethod
def _build_mac(fields, data):
    """Build MAC string ('003one003two') for required fields."""
    f = lambda x: data.get('VK_%s' % x)
    return u''.join(map(lambda k: '%03d%s' % (len(f(k).encode('utf-8')), f(
        k)), fields)).encode('utf-8')


@classmethod
def check(cls, control_instance):
    """ Check if a controller widget dict control is filled correctly.

        Parameters
        ----------
        cls: DictControlWidget (mandatory)
            a DictControlWidget control
        control_instance: QFrame (mandatory)
            the control widget we want to validate
        """
    pass


@classmethod
def _norm_hash(cls, hash):
    """helper for subclasses to normalize case if needed"""
    return hash


def escape_html(s):
    """
	Escapes a string so that it can be displayed as HTML. This is useful for
	example for tracebacks, which use <> characters.

	Arguments:
	s	--	A string to escape. We assume Unicode input. str objects may cause
			decoding errors.

	Returns:
	An escaped string.
	"""
    l = [(u'&', u'&'), (u' ', u' '), (u'\t',
        u'    '), (u'<', u'<'), (u'>', u'>')]
    for orig, new in l:
        s = s.replace(orig, new)
    return s


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

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

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


def dict_seq_reducer(seq, dict_key, value_keys, add_kv_dict=None):
    """
    Reduce a sequence of dicts to single dict of dicts,
    optionally adding additional k,v pairs
    """
    reduced_dict = dict()
    for element in seq:
        if len(element['REF']) > 1400 or len(element['ALT']) >= 1400:
            continue
        reduced_dict[element[dict_key]] = dict()
        for key in value_keys:
            reduced_dict[element[dict_key]][key] = element[key]
        if add_kv_dict:
            for k, v in add_kv_dict.items():
                reduced_dict[element[dict_key]][k] = v
    return reduced_dict


@staticmethod
def __collection_init__(client):
    """Write some collection initial operation, like set some index."""
    pass


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


def split_address(address):
    """Splits a url into a protocol, host name and port"""
    if '://' in address:
        protocol, address = address.split('://')
    else:
        protocol = 'http'
    if ':' in address:
        address, port = address.split(':')
    else:
        port = 443 if protocol == 'https' else 8000
    return protocol, address, int(port)


def capitalize_haiku(haiku_array):
    """Capitalize appropriate words in haiku"""
    period = '.'
    haiku_array[0] = haiku_array[0].capitalize()
    for i in range(1, len(haiku_array)):
        if haiku_array[i] == period and i + 2 < len(haiku_array):
            haiku_array[i + 2] = haiku_array[i + 2].capitalize()
    return haiku_array


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

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


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


def forwardMessage(instance, message, receiver):
    """ Forward a IMS message to somebody
        """


def createElementXML(name, type, prefix='xsd'):
    """ Function used for the creation of xml elements. """
    return '<%s:element name="%s" type="%s:%s"/>' % (prefix, name, prefix, type
        )