def put_bot_alias(name=None, description=None, botVersion=None, botName=
    None, checksum=None):
    """
    Creates an alias for the specified version of the bot or replaces an alias for the specified bot. To change the version of the bot that the alias points to, replace the alias. For more information about aliases, see  versioning-aliases .
    This operation requires permissions for the lex:PutBotAlias action.
    See also: AWS API Documentation

    :example: response = client.put_bot_alias(
        name='string',
        description='string',
        botVersion='string',
        botName='string',
        checksum='string'
    )

    :type name: string
    :param name: [REQUIRED]
            The name of the alias. The name is not case sensitive.

    :type description: string
    :param description: A description of the alias.

    :type botVersion: string
    :param botVersion: [REQUIRED]
            The version of the bot.

    :type botName: string
    :param botName: [REQUIRED]
            The name of the bot.

    :type checksum: string
    :param checksum: Identifies a specific revision of the $LATEST version.
            When you create a new bot alias, leave the checksum field blank. If you specify a checksum you get a BadRequestException exception.
            When you want to update a bot alias, set the checksum field to the checksum of the most recent revision of the $LATEST version. If you don't specify the checksum field, or if the checksum does not match the $LATEST version, you get a PreconditionFailedException exception.

    :rtype: dict
    :return: {
        'name': 'string',
        'description': 'string',
        'botVersion': 'string',
        'botName': 'string',
        'lastUpdatedDate': datetime(2015, 1, 1),
        'createdDate': datetime(2015, 1, 1),
        'checksum': 'string'
    }

    """
    pass


@staticmethod
def _default_match(original, test):
    """
        A function determining the way single nodes are matched

        This function is used to test for __contains__

        Parameters
        ----------
        original : node
            the original node to be tested
        test : node-like
            the object a node should be tested for

        Returns
        -------
        bool
            True if the original is of type test. This depends on the
            actual implementation

        Notes
        -----
        Default is to test for equality `original == test`, often we might
        also allow for testing of classes, subclasses, e.g.
        [1,2,3] as a node could be tested for list and return True
        """
    if original == test:
        return True
    else:
        return False


def scroller_activate():
    """Scroll view by mouse click and drag

    """
    pass


def trimesh_swap_edge(mesh, u, v, allow_boundary=True):
    """Replace an edge of the mesh by an edge connecting the opposite
    vertices of the adjacent faces.

    Parameters
    ----------
    mesh : compas.datastructures.Mesh
        Instance of mesh.
    u : str
        The key of one of the vertices of the edge.
    v : str
        The key of the other vertex of the edge.

    Returns
    -------
    None

    """
    fkey_uv = mesh.halfedge[u][v]
    fkey_vu = mesh.halfedge[v][u]
    u_on = mesh.is_vertex_on_boundary(u)
    v_on = mesh.is_vertex_on_boundary(v)
    if u_on and v_on:
        return False
    if not allow_boundary:
        if mesh.is_vertex_on_boundary(u) or mesh.is_vertex_on_boundary(v):
            return False
    uv = mesh.face[fkey_uv]
    vu = mesh.face[fkey_vu]
    o_uv = uv[uv.index(u) - 1]
    o_vu = vu[vu.index(v) - 1]
    if o_uv in mesh.halfedge[o_vu] and o_vu in mesh.halfedge[o_uv]:
        return False
    del mesh.halfedge[u][v]
    del mesh.halfedge[v][u]
    del mesh.face[fkey_uv]
    del mesh.face[fkey_vu]
    a = mesh.add_face([o_uv, o_vu, v])
    b = mesh.add_face([o_vu, o_uv, u])
    return a, b


def unique_everseen(iterable, key=None):
    """
    Yield unique elements, preserving order.

        >>> list(unique_everseen('AAAABBBCCDAABBB'))
        ['A', 'B', 'C', 'D']
        >>> list(unique_everseen('ABBCcAD', str.lower))
        ['A', 'B', 'C', 'D']

    Sequences with a mix of hashable and unhashable items can be used.
    The function will be slower (i.e., `O(n^2)`) for unhashable items.

    """
    seenset = set()
    seenset_add = seenset.add
    seenlist = []
    seenlist_add = seenlist.append
    if key is None:
        for element in iterable:
            try:
                if element not in seenset:
                    seenset_add(element)
                    yield element
            except TypeError:
                if element not in seenlist:
                    seenlist_add(element)
                    yield element
    else:
        for element in iterable:
            k = key(element)
            try:
                if k not in seenset:
                    seenset_add(k)
                    yield element
            except TypeError:
                if k not in seenlist:
                    seenlist_add(k)
                    yield element


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


@classmethod
def build_pollsters(cls, conf):
    """Return a list of tuple (name, pollster).

        The name is the meter name which the pollster would return, the
        pollster is a pollster object instance. The pollster which implements
        this method should be registered in the namespace of
        ceilometer.builder.xxx instead of ceilometer.poll.xxx.
        """
    return []


def configForAutodetect():
    """Find the IFeedConfig for feed autodetection. Returns None if no
        autodetect feed is configured.
        """


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


def fix_frame_records_filenames(records):
    """Try to fix the filenames in each record from inspect.getinnerframes().

    Particularly, modules loaded from within zip files have useless filenames
    attached to their code object, and inspect.getinnerframes() just uses it.
    """
    fixed_records = []
    for frame, filename, line_no, func_name, lines, index in records:
        better_fn = frame.f_globals.get('__file__', None)
        if isinstance(better_fn, str):
            filename = better_fn
        fixed_records.append((frame, filename, line_no, func_name, lines,
            index))
    return fixed_records


def get(isdsAppliance, check_mode=False, force=False):
    """
    Retrieving the administrator settings
    """
    return isdsAppliance.invoke_get('Retrieving the administrator settings',
        '/admin_cfg')


def parse_ports(ports_text):
    """Parse ports text

    e.g. ports_text = "12345,13000-15000,20000-30000"
    """
    ports_set = set()
    for bit in ports_text.split(','):
        if '-' in bit:
            low, high = bit.split('-', 1)
            ports_set = ports_set.union(range(int(low), int(high) + 1))
        else:
            ports_set.add(int(bit))
    return sorted(list(ports_set))


@classmethod
def reserve_subnet_cidr(cls, addr, **ipnetwork_kwargs):
    """Reserve given subnet CIDR making sure it is not used by create_subnet

        :param addr: the CIDR address to be reserved
        It can be a str or netaddr.IPNetwork instance

        :param **ipnetwork_kwargs: optional netaddr.IPNetwork constructor
        parameters
        """
    if not cls.try_reserve_subnet_cidr(addr, **ipnetwork_kwargs):
        raise ValueError('Subnet CIDR already reserved: %r'.format(addr))


@staticmethod
def split_uniformly_in_every_dimension(region):
    """
        Split the region uniformly in every region.
        :param region: Region.
        :return: New regions after splitting.
        """
    return region.region.split_in_every_dimension()


def binary_int_to_bool(_value):
    """Converts 1 to True and 1 and None to False."""
    if _value is None or _value == 0:
        return False
    elif _value == 1:
        return True


def __call__(email):
    """ Resolve a user that has the given email
        """


@classmethod
def build(cls, params):
    """ Class currently does nothing, but was created to conform to spec."""
    return cls.merge(cls.default_params(), params)


def set_creator(creator):
    """Set the Creator object to be used in all writes during the lifetime of the current process.

    A Creator object is normally constructed automatically, but this function allows all future writes to be
    associated with a different Creator. This is mainly used by MPI runs to give the illusion that all data was
    written by one process."""
    global _current_creator
    _current_creator = creator


def to_byte(string):
    """ convert byte to string in pytohn2/3
    """
    return string.encode()


def doc_return(returns):
    """format return for doc-string"""
    return '    :returns: {0}'.format(repr(returns).replace("'", '"'))


@classmethod
def redo(cls):
    """Re-does the last undone action.
        """
    return cls.build_send_payload('redo', {}), None


def apply_pose(pose_index: int=-1):
    """Apply specified Pose Library pose to the rig

    :param pose_index: Pose, Index of the pose to apply (-2 for no change to pose, -1 for poselib active pose)
    :type pose_index: int
    """
    pass


def _test():
    """
    >>> text = "Line\\\\nLong Line\\\\\\nVery long line and...\\nHere \\n\\n \\n\\n \\n \\\\n"
    >>> for i in range(1, 80):
    ...     if not join_long_lines(break_long_lines(text, i)) == text:
    ...         raise Exception("Test failure")
    """
    pass


def add_pattern(parser):
    """ Add --pattern option to parser """
    parser.add_argument('--pattern', help='Pattern of log files to operate on.'
        )


def closer_points_rel(p1, p2, offset_ratio, abs_offset=0):
    """Returns a pair of points that are in the line that joins
       p1 and p2, but closer than them by the given ratio.

       Example: offset_ratio == 0.9 implies the distance between the
       new points is 0.9 the distance between the original points.
       Points go then closer by abs_offset on each side.

    """
    dx = p2[0] - p1[0]
    dy = p2[1] - p1[1]
    xoff = abs_offset * float(dx) / (abs(dx) + abs(dy))
    yoff = abs_offset * float(dy) / (abs(dx) + abs(dy))
    k = (1.0 - float(offset_ratio)) / 2
    return (int(p1[0] + dx * k + xoff), int(p1[1] + dy * k + yoff)), (int(
        p2[0] - dx * k - xoff), int(p2[1] - dy * k - yoff))


def asbool(value):
    """
    >>> all([asbool(True), asbool('trUE'), asbool('ON'), asbool(1)])
    True
    >>> any([asbool(False), asbool('false'), asbool('foo'), asbool(None)])
    False
    """
    value = str(value).lower()
    return value in ('1', 'true', 'yes', 'on')


def hasProperty(id):
    """Return true if object has a property 'id'.
        """


def _hex_to_rgb(hex_code):
    """
    >>> _hex_to_rgb("007fff")
    (0, 127, 255)
    """
    return tuple(map(ord, hex_code.decode('hex')))


def replace_last_stop(orf_seq):
    """
    replace * with nothing as the final character in in string

    Parameters
    ----------
    orf_seq : str
        orf_sequence

    Returns
    -------
    orf_seq : str
        orf_sequence

    Examples
    --------

    replace_last_stop("META*")
    replace_last_stop("METAL")

    """
    if orf_seq[-1] == '*':
        replaced_orf_seq = orf_seq[0:-1]
        return replaced_orf_seq
    else:
        return orf_seq


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

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

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


def read_uic2tag(fh, byteorder, dtype, plane_count):
    """Read MetaMorph STK UIC2Tag from file and return as dictionary."""
    assert dtype == '2I' and byteorder == '<'
    values = fh.read_array('<u4', 6 * plane_count).reshape(plane_count, 6)
    return {'z_distance': values[:, (0)] / values[:, (1)], 'date_created':
        values[:, (2)], 'time_created': values[:, (3)], 'date_modified':
        values[:, (4)], 'time_modified': values[:, (5)]}


def i_love_python():
    """
        Let's explain why do we love Python.
    """
    return 'I love Python!'


def avoid():
    """Prints a soda to avoid."""
    print('Avoid Pepsi.')


def get_strand_bias(var):
    """
    Return the likelihood of strand bias,
    or None if it isn't present in the VCF.
    """
    return var.INFO.get('SB')


def build_description(summary, description):
    """
    Return a description string from a summary and description
    """
    summary = (summary or '').strip()
    description = (description or '').strip()
    if not description:
        description = summary
    elif summary and summary not in description:
        description = '\n'.join([summary, description])
    return description


def __init__(context, request):
    """Adapts context and request.
        """


def unsplit(t):
    """Make a RI from a split RI(5-tuple)"""
    s = ''
    if t[0] is not None:
        s += t[0]
        s += '://'
    if t[1] is not None:
        s += t[1]
    if t[2] is not None:
        s += '/'
        s += t[2]
    if t[3] is not None:
        s += '?'
        s += t[3]
    if t[4] is not None:
        s += '#'
        s += t[4]
    return s


def _get_plotly_axis_labels(i, j, ncols):
    """Gets plotly axis labels from subplot indices i, j"""
    plot_ind = i * ncols + j + 1
    return 'xaxis%d' % plot_ind, 'yaxis%d' % plot_ind


def get_key():
    """Returns the key for the dictstorage where the default tab is
        stored.
        """


@classmethod
def _ap_compute_external_mimetype(cls, package_name, unused_a_type,
    ext_class_name):
    """
        Return the string value of the external mime type for the given
        type in the given package having the given external name (probably
        derived from :meth:`_ap_compute_external_class_name_from_concrete_class`).

        For example, given the arguments ('nti.assessment', FooBar, 'FooBar'), the
        result will be 'application/vnd.nextthought.assessment.foobar'.

        Subclasses may override.
        """
    local = package_name.rsplit('.', 1)[-1]
    return str('application/vnd.nextthought.' + local + '.' +
        ext_class_name.lower())


def sliding_box(start, stop, size, step=1):
    """
    Find sliding boxes of region

    Parameters:
    -----------
    start: int
        0 based start coordinate of the region.
    stop : int
        0 based stop coordinate of the region, i.e. stop is not part of the
        region anymore;
    size : int
        The size of the box regions
    step : int, optional
        The step size of the sliding box.

    Return
    ------
    regions : list
        List of tuples (start,stop) with the extracted regions.
    """
    if (stop - start) / step != 0:
        overhead = (stop - start) % step
        if overhead % 2 == 0:
            start += overhead // 2
            stop -= overhead // 2
        else:
            start += overhead // 2
            stop -= overhead // 2 + 1
    regions = []
    for i in range(0, stop - start, step):
        regions.append((i + start, i + start + size))
    return regions


@classmethod
def decode(cls, stream):
    """Decodes transfer syntax sub-item from data stream

        :param stream: raw data stream
        :return: decoded transfer syntax sub-item
        """
    _, reserved, item_length = cls.header.unpack(stream.read(4))
    name = stream.read(item_length)
    return cls(name=name.decode(), reserved=reserved)


def pagetemplate(page):
    """Locate the template file from the layout's template sub-directory
        and return the template file.

        ``page``,
            An instance of class :class:`Page`.

        Return template file as absolute file path. If False or None is
        returned then, either template file couldn't be located or not located
        for other reasons.
        """


def find():
    """Find specified text

    """
    pass


def compare_report_print(sorted_list, scores, best_name):
    """
    Return compare report.

    :param sorted_list: sorted list of cm's
    :type sorted_list: list
    :param scores: scores of cm's
    :type scores: dict
    :param best_name: best cm name
    :type best_name: str
    :return: printable result as str
    """
    title_items = ['Rank', 'Name', 'Class-Score', 'Overall-Score']
    class_scores_len = map(lambda x: len(str(x['class'])), list(scores.
        values()))
    shifts = ['%-' + str(len(sorted_list) + 4) + 's', '%-' + str(max(map(lambda
        x: len(str(x)), sorted_list)) + 4) + 's', '%-' + str(max(
        class_scores_len) + 11) + 's']
    result = ''
    result += 'Best : ' + str(best_name) + '\n\n'
    result += ''.join(shifts) % tuple(title_items[:-1]) + title_items[-1
        ] + '\n'
    prev_rank = 0
    for index, cm in enumerate(sorted_list):
        rank = index
        if scores[sorted_list[rank]] == scores[sorted_list[prev_rank]]:
            rank = prev_rank
        result += ''.join(shifts) % (str(rank + 1), str(cm), str(scores[cm]
            ['class'])) + str(scores[cm]['overall']) + '\n'
        prev_rank = rank
    return result


def readbe(b: bytes) ->int:
    """Convert big-endian bytes to an int."""
    return int.from_bytes(b, 'big')


def is_int(value):
    """Return `True` if ``value`` is an integer."""
    if isinstance(value, bool):
        return False
    try:
        int(value)
        return True
    except ValueError:
        return False


def HTML_Overall_Params_Table(Input_Dict, Input_Params, file, header=False):
    """
    Add table to html file.

    :param Input_Dict: input values dictionary
    :type Input_Dict : dict
    :param Input_Params: input parameters dictionary
    :type Input_Params : dict
    :param file: html file object
    :type file : file object
    :return: None
    """
    if header:
        file.write('
Overall Parameters
\n')
    file.write(
        '
\n'
        )
    file.write(
        '
\n'
        )
    file.write(
        '\n'
         + 'Parameter\n	')
    file.write(
        '\n'
         + """Description
	""")
    file.write(
        '\n'
         + """Value

""")
    Input_Params_Keys = sorted(Input_Params.keys())
    for key in Input_Params_Keys:
        file.write(
            """

"""
            )
        file.write(
            '\n'
             + key + '\n	\n')
        file.write(
            '\n'
             + Input_Params[key] + '\n	\n')
        file.write(
            '\n'
             + str(Input_Dict[key]) + '\n	\n')
    file.write('
\n')
    if header:
        file.write('
Graphs
\n')


def string_to_float(float_str):
    """
    Convert a float in string format to a float.

    :param float_str: Float in string format ("25.01")
    :return: float from string
    """
    if float_str:
        return float(float_str)
    return None


@staticmethod
def get_port_name_from_id(node_id, port_id, nodes):
    """
        Get the name of a port for a given node and port ID

        :param int node_id: node ID
        :param int port_id: port ID
        :param list nodes: list of nodes from :py:meth:`generate_nodes`
        :return: port name
        :rtype: str
        """
    port_name = ''
    for node in nodes:
        if node['id'] == node_id:
            for port in node['ports']:
                if port['id'] == port_id:
                    port_name = port['name']
                    break
    return port_name


def get_best_mutable_version():
    """Return a Deferred that fires with an IMutableFileVersion for
        the 'best' available version of the file. The best version is
        the recoverable version with the highest sequence number. If no
        uncoordinated writes have occurred, and if enough shares are
        available, then this will be the most recent version that has
        been uploaded.

        If no version is recoverable, the Deferred will errback with an
        UnrecoverableFileError.
        """


def _check_is_max_context(doc_spans, cur_span_index, position):
    """Check if this is the 'max context' doc span for the token."""
    best_score = None
    best_span_index = None
    for span_index, doc_span in enumerate(doc_spans):
        end = doc_span.start + doc_span.length - 1
        if position < doc_span.start:
            continue
        if position > end:
            continue
        num_left_context = position - doc_span.start
        num_right_context = end - position
        score = min(num_left_context, num_right_context
            ) + 0.01 * doc_span.length
        if best_score is None or score > best_score:
            best_score = score
            best_span_index = span_index
    return cur_span_index == best_span_index


def listify(dct, key):
    """Make sure a key in this dct is a list"""
    if key not in dct:
        dct[key] = []
    elif not isinstance(dct[key], list):
        dct[key] = [dct[key]]
    return dct[key]


@staticmethod
def import_class(cl):
    """
		Imports class by name
		"""
    d = cl.rfind('.')
    classname = cl[d + 1:len(cl)]
    m = __import__(cl[0:d], globals(), locals(), [classname])
    return getattr(m, classname)


def register(module_name: str, translations_dict: dict):
    """Registers an addon’s UI translations.

    :param module_name: The name identifying the addon.
    :type module_name: str
    :param translations_dict: A dictionary built like that: {locale: {msg_key: msg_translation, ...}, ...}
    :type translations_dict: dict
    """
    pass


def describe_snapshot_copy_grants(SnapshotCopyGrantName=None, MaxRecords=
    None, Marker=None, TagKeys=None, TagValues=None):
    """
    Returns a list of snapshot copy grants owned by the AWS account in the destination region.
    For more information about managing snapshot copy grants, go to Amazon Redshift Database Encryption in the Amazon Redshift Cluster Management Guide .
    See also: AWS API Documentation

    :example: response = client.describe_snapshot_copy_grants(
        SnapshotCopyGrantName='string',
        MaxRecords=123,
        Marker='string',
        TagKeys=[
            'string',
        ],
        TagValues=[
            'string',
        ]
    )

    :type SnapshotCopyGrantName: string
    :param SnapshotCopyGrantName: The name of the snapshot copy grant.

    :type MaxRecords: integer
    :param MaxRecords: The maximum number of response records to return in each call. If the number of remaining response records exceeds the specified MaxRecords value, a value is returned in a marker field of the response. You can retrieve the next set of records by retrying the command with the returned marker value.
            Default: 100
            Constraints: minimum 20, maximum 100.

    :type Marker: string
    :param Marker: An optional parameter that specifies the starting point to return a set of response records. When the results of a DescribeSnapshotCopyGrant request exceed the value specified in MaxRecords , AWS returns a value in the Marker field of the response. You can retrieve the next set of response records by providing the returned marker value in the Marker parameter and retrying the request.
            Constraints: You can specify either the SnapshotCopyGrantName parameter or the Marker parameter, but not both.

    :type TagKeys: list
    :param TagKeys: A tag key or keys for which you want to return all matching resources that are associated with the specified key or keys. For example, suppose that you have resources tagged with keys called owner and environment . If you specify both of these tag keys in the request, Amazon Redshift returns a response with all resources that have either or both of these tag keys associated with them.
            (string) --

    :type TagValues: list
    :param TagValues: A tag value or values for which you want to return all matching resources that are associated with the specified value or values. For example, suppose that you have resources tagged with values called admin and test . If you specify both of these tag values in the request, Amazon Redshift returns a response with all resources that have either or both of these tag values associated with them.
            (string) --

    :rtype: dict
    :return: {
        'Marker': 'string',
        'SnapshotCopyGrants': [
            {
                'SnapshotCopyGrantName': 'string',
                'KmsKeyId': 'string',
                'Tags': [
                    {
                        'Key': 'string',
                        'Value': 'string'
                    },
                ]
            },
        ]
    }

    """
    pass


def stripnull(string, null=b'\x00'):
    """Return string truncated at first null character.

    Clean NULL terminated C strings. For unicode strings use null='\\0'.

    >>> stripnull(b'string\\x00')
    b'string'
    >>> stripnull('string\\x00', null='\\0')
    'string'

    """
    i = string.find(null)
    return string if i < 0 else string[:i]


@classmethod
def hascreds(cls, config):
    """Determine if the given configuration has proper credentials

        Parameters
        ----------
        cls : class
            A Session class.
        config : dict
            GDAL configuration as a dict.

        Returns
        -------
        bool

        """
    return 'OSS_ACCESS_KEY_ID' in config and 'OSS_SECRET_ACCESS_KEY' in config


@classmethod
def get_session_class(cls, interface_type, resource_class):
    """Return the session class for a given interface type and resource class.

        :type interface_type: constants.InterfaceType
        :type resource_class: str
        :return: Session
        """
    try:
        return cls._session_classes[interface_type, resource_class]
    except KeyError:
        raise ValueError('No class registered for %s, %s' % (interface_type,
            resource_class))


def are_adjacent(inds):
    """"Check if all int indices in the interable are consecutive.

    :param inds: iterable of ints
    :returns: bool
    """
    if len(inds) == 1:
        adjacent = True
    else:
        adjacent = False
        i = inds[0]
        for n in inds[1:]:
            if n - i != 1:
                break
            i = n
        else:
            adjacent = True
    return adjacent


def convert_flatten(builder, layer, input_names, output_names, keras_layer):
    """
    Convert a flatten layer from keras to coreml.
    ----------
    Parameters
    keras_layer: layer
        A keras layer object.

    builder: NeuralNetworkBuilder
        A neural network builder object.
    """
    input_name, output_name = input_names[0], output_names[0]
    blob_order = 0
    try:
        in_shape = keras_layer.input_shape
        if len(in_shape) == 4:
            blob_order = 1
        if len(in_shape) == 3 and in_shape[0] is None:
            permute_output_name = output_name + '__permute__'
            builder.add_permute(name=layer + '__permute__', dim=(2, 1, 0, 3
                ), input_name=input_name, output_name=permute_output_name)
            builder.add_flatten(name=layer, mode=1, input_name=
                permute_output_name, output_name=output_name)
        else:
            builder.add_flatten(name=layer, mode=blob_order, input_name=
                input_name, output_name=output_name)
    except:
        builder.add_flatten(name=layer, mode=1, input_name=input_name,
            output_name=output_name)


def load_class(module, class_name):
    """ Loads the class from a module by the class name"""
    klass = getattr(module, class_name, None)
    return klass


def scale_data(data, lo, hi, factor=None):
    """Function to scale data."""
    return (data - lo) / (hi - lo) * factor if factor else (data - lo) / (hi -
        lo)


def joints_2_angles(jin, type):
    """Converts the robot encoders into angles between links depending on the type of the robot."""
    jout = jin
    if type == 2:
        jout[2] = -jin[1] - jin[2]
        jout[3] = -jin[3]
        jout[4] = -jin[4]
        jout[5] = -jin[5]
    elif type == 3:
        jout[2] = -jin[2]
        jout[3] = -jin[3]
        jout[4] = -jin[4]
        jout[5] = -jin[5]
    elif type == 4:
        jout[2] = +jin[1] + jin[2]
    elif type == 11:
        jout[2] = -jin[1] - jin[2]
        jout[0] = -jin[0]
        jout[3] = -jin[3]
        jout[5] = -jin[5]
    return jout


@classmethod
def get(cls, name: str):
    """Get a ``StarPowers`` instance of the given Brawler.

        Parameters
        --------------
        name: :class:`str`
            The full/partial name of the Brawler.

        Returns
        ----------
        :class:`StarPowers`
            ``StarPowers`` instance from given name.

        Raises
        --------
        BrawlerNotFound
            If a Brawler can't be found from the given ``name``.
        """
    data = cls._get(name)
    return cls(data)


def stroke_flip():
    """Change direction of the points of the selected strokes

    """
    pass


def set_location(value):
    """Sets the location"""


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

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

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


@staticmethod
def _sanitizer(obj):
    """Sanitizer method that will be passed to jsonutils.loads."""
    return obj


def batch_get_applications(applicationNames=None):
    """
    Gets information about one or more applications.
    See also: AWS API Documentation

    :example: response = client.batch_get_applications(
        applicationNames=[
            'string',
        ]
    )

    :type applicationNames: list
    :param applicationNames: A list of application names separated by spaces.
            (string) --

    :rtype: dict
    :return: {
        'applicationsInfo': [
            {
                'applicationId': 'string',
                'applicationName': 'string',
                'createTime': datetime(2015, 1, 1),
                'linkedToGitHub': True|False,
                'gitHubAccountName': 'string'
            },
        ]
    }

    """
    pass


@classmethod
def create(cls, label, display, description, default=2, verbosity=1):
    """
        Creates a new NoticeType.

        This is intended to be used by other apps as a post_syncdb manangement step.
        """
    try:
        notice_type = cls._default_manager.get(label=label)
        updated = False
        if display != notice_type.display:
            notice_type.display = display
            updated = True
        if description != notice_type.description:
            notice_type.description = description
            updated = True
        if default != notice_type.default:
            notice_type.default = default
            updated = True
        if updated:
            notice_type.save()
            if verbosity > 1:
                print('Updated %s NoticeType' % label)
    except cls.DoesNotExist:
        cls(label=label, display=display, description=description, default=
            default).save()
        if verbosity > 1:
            print('Created %s NoticeType' % label)


def is_valid_nuc(nuc):
    """Check if valid single letter base.

    Parameters
    ----------
    nuc : str
        String to check if valid single nucleotide base

    Returns
    -------
    is_valid : bool
        flag indicating valid nucleotide base
    """
    valid_nucs = ['A', 'C', 'T', 'G', 'N']
    is_valid = nuc in valid_nucs
    return is_valid


def fib(n):
    """Fibonacci example function

    Args:
      n (int): integer

    Returns:
      int: n-th Fibonacci number
    """
    assert n > 0
    a, b = 1, 1
    for i in range(n - 1):
        a, b = b, a + b
    return a


@staticmethod
def supports(uri):
    """Whether or not this provider supports a given uri."""
    if 'zenodo' in uri.lower():
        return True
    return False


def from_two_bytes(bytes):
    """
    Return an integer from two 7 bit bytes.
    """
    lsb, msb = bytes
    try:
        return msb << 7 | lsb
    except TypeError:
        try:
            lsb = ord(lsb)
        except TypeError:
            pass
        try:
            msb = ord(msb)
        except TypeError:
            pass
        return msb << 7 | lsb


def copy_memmap_h5dt(arr, dt):
    """Copies a :class:`numpy.memmap` to a hdf5 dataset."""
    if arr.ndim > 2:
        raise Exception("I don't know how to handle arrays" +
            ' with more than 2 dimensions yet.')
    assert arr.shape == dt.shape
    if arr.ndim == 1:
        dt[:] = arr[:]
    else:
        if dt.chunks is not None:
            chunk_row = dt.chunks[0]
        else:
            chunk_row = 512
        r = 0
        while r < arr.shape[0]:
            re = r + chunk_row
            re = min(re, arr.shape[0])
            dt[r:re, :] = arr[r:re, :]
            r = re


def create_keys_and_certificate(setAsActive=None):
    """
    Creates a 2048-bit RSA key pair and issues an X.509 certificate using the issued public key.
    Note This is the only time AWS IoT issues the private key for this certificate, so it is important to keep it in a secure location.
    See also: AWS API Documentation

    :example: response = client.create_keys_and_certificate(
        setAsActive=True|False
    )

    :type setAsActive: boolean
    :param setAsActive: Specifies whether the certificate is active.

    :rtype: dict
    :return: {
        'certificateArn': 'string',
        'certificateId': 'string',
        'certificatePem': 'string',
        'keyPair': {
            'PublicKey': 'string',
            'PrivateKey': 'string'
        }
    }

    """
    pass


def regtestli(item, li, match=False):
    """
    Test elements in a list with Regular Expression.
    Extract elements that work well with a Regular Expression (item) from a list(li), and return a result list.
    """
    import re
    c = re.compile(item)
    n = 0
    rs = []
    for i in li:
        if match == True:
            b = re.match(c, i)
            if b is not None:
                rs.append(li[n])
        else:
            b = re.search(c, i)
            if b is not None:
                rs.append(li[n])
        n += 1
    return rs


def read_numpy(fh, byteorder, dtype, count):
    """Read tag data from file and return as numpy array."""
    dtype = 'b' if dtype[-1] == 's' else byteorder + dtype[-1]
    return fh.read_array(dtype, count)


def add_permission(QueueUrl=None, Label=None, AWSAccountIds=None, Actions=None
    ):
    """
    Adds a permission to a queue for a specific principal . This allows sharing access to the queue.
    When you create a queue, you have full control access rights for the queue. Only you, the owner of the queue, can grant or deny permissions to the queue. For more information about these permissions, see Shared Queues in the Amazon SQS Developer Guide .
    See also: AWS API Documentation

    :example: response = client.add_permission(
        QueueUrl='string',
        Label='string',
        AWSAccountIds=[
            'string',
        ],
        Actions=[
            'string',
        ]
    )

    :type QueueUrl: string
    :param QueueUrl: [REQUIRED]
            The URL of the Amazon SQS queue to which permissions are added.
            Queue URLs are case-sensitive.

    :type Label: string
    :param Label: [REQUIRED]
            The unique identification of the permission you're setting (for example, AliceSendMessage ). Maximum 80 characters. Allowed characters include alphanumeric characters, hyphens (- ), and underscores (_ ).

    :type AWSAccountIds: list
    :param AWSAccountIds: [REQUIRED]
            The AWS account number of the principal who is given permission. The principal must have an AWS account, but does not need to be signed up for Amazon SQS. For information about locating the AWS account identification, see Your AWS Identifiers in the Amazon SQS Developer Guide .
            (string) --

    :type Actions: list
    :param Actions: [REQUIRED]
            The action the client wants to allow for the specified principal. The following values are valid:
            *
            ChangeMessageVisibility
            DeleteMessage
            GetQueueAttributes
            GetQueueUrl
            ReceiveMessage
            SendMessage
            For more information about these actions, see Understanding Permissions in the Amazon SQS Developer Guide .
            Specifying SendMessage , DeleteMessage , or ChangeMessageVisibility for ActionName.n also grants permissions for the corresponding batch versions of those actions: SendMessageBatch , DeleteMessageBatch , and ChangeMessageVisibilityBatch .
            (string) --

    """
    pass


def create_number_type(lang):
    """ Creates a sort corresponding to the PDDL "number" """
    parent = lang.get_sort('Integer')
    lower = parent.lower_bound
    upper = parent.upper_bound
    lang.interval('number', parent, lower, upper)


@classmethod
def stream_deserialize(cls, f, **kwargs):
    """Deserialize from a stream"""
    raise NotImplementedError


def set_verbose(verbose):
    """A convenience function for setting the verbosity of a popeye model/fit.

    Paramaters
    ----------

    verbose : int
        0 = silent
        1 = print the final solution of an error-minimization
        2 = print each error-minimization step

    """
    if verbose == 0:
        verbose = False
        very_verbose = False
    if verbose == 1:
        verbose = True
        very_verbose = False
    if verbose == 2:
        verbose = True
        very_verbose = True
    return verbose, very_verbose


def bagel_constraint_constructor(ai_parser, ai_variant=0):
    """
  Add arguments relative to the bagel
  """
    r_parser = ai_parser
    r_parser.add_argument('--bagel_axle_diameter', '--bgad', action='store',
        type=float, default=10.0, help='Set the axle_diameter. Default: 10.0')
    r_parser.add_argument('--bagel_axle_internal_diameter', '--bgaid',
        action='store', type=float, default=20.0, help=
        'Set the axle_internal_diameter. If equal to 0.0, set to 2*bagel_axle_diameter. Default: 0.0'
        )
    r_parser.add_argument('--bagel_axle_external_diameter', '--bgaed',
        action='store', type=float, default=0.0, help=
        'Set the axle_external_diameter. If equal to 0.0, set to 2*bagel_axle_internal_diameter. Default: 0.0'
        )
    if ai_variant != 1:
        r_parser.add_argument('--axle_hole_nb', '--ahn', action='store',
            type=int, default=6, help=
            'Set the number of the axle-holes. If equal to 0, no axle-hole is created. Default: 6'
            )
        r_parser.add_argument('--axle_hole_diameter', '--ahd', action=
            'store', type=float, default=4.0, help=
            'Set the diameter of the axle-holes. Default: 4.0')
        r_parser.add_argument('--axle_hole_position_diameter', '--ahpd',
            action='store', type=float, default=0.0, help=
            'Set the diameter of the axle-hole position circle. If equal to 0.0, set to (axle_internal_diameter+axle_external_diameter)/2. Default: 0.0'
            )
        r_parser.add_argument('--axle_hole_angle', '--aha', action='store',
            type=float, default=0.0, help=
            'Set the position angle of the first axle-hole. Default: 0.0')
    r_parser.add_argument('--external_bagel_thickness', '--ebt', action=
        'store', type=float, default=2.0, help=
        'Set the thickness (z-size) of the external_bagel part. Default: 2.0')
    if ai_variant != 1:
        r_parser.add_argument('--middle_bagel_thickness', '--mbt', action=
            'store', type=float, default=6.0, help=
            'Set the thickness (z-size) of the middle_bagel part. Default: 6.0'
            )
    r_parser.add_argument('--internal_bagel_thickness', '--ibt', action=
        'store', type=float, default=2.0, help=
        'Set the thickness (z-size) of the internal_bagel part. Default: 2.0')
    r_parser.add_argument('--bagel_extra_cut_thickness', '--bgect', action=
        'store', type=float, default=0.0, help=
        'Set the extra-cut-thickness for the internal-bagel cut. It can be used to compensate the manufacturing process or to check the 3D assembly with FreeCAD. Default: 0.0'
        )
    return r_parser


def p_to_q(p_values):
    """
    Uses the Benjamini-Hochberg procedure to convert p_values to q_values

    :param p_values:  numpy.ndarray of p_values
    :return q_values: numpy.ndarray of q_values, same shape as p_values
    """
    original_shape = p_values.shape
    p_vals_flat = p_values.flatten()
    rank = p_vals_flat.argsort().argsort() + 1
    num_tests = p_values.size
    q_vals = p_vals_flat * num_tests / rank
    q_vals.shape = original_shape
    q_vals[q_vals > 1.0] = 1.0
    return q_vals


def version_to_string(version, parts=3):
    """ Convert an n-part version number encoded as a hexadecimal value to a
    string.  version is the version number.  Returns the string.
    """
    part_list = [str(version >> 16 & 255)]
    if parts > 1:
        part_list.append(str(version >> 8 & 255))
        if parts > 2:
            part_list.append(str(version & 255))
    return '.'.join(part_list)


def _get_min_overlap_timestamp(df1_timestamps, df2_timestamps):
    """
    Get the minimum overlapping timestamp from two series
    """
    if df1_timestamps.max() < df2_timestamps.min() or df1_timestamps.min(
        ) > df2_timestamps.max():
        raise IndexError(
            'No overlapping data. Ranges: {0} to {1}  and {2} to {3}'.
            format(df1_timestamps.min(), df1_timestamps.max(),
            df2_timestamps.min(), df2_timestamps.max()))
    return max(df1_timestamps.min(), df2_timestamps.min())


def decodeInfoValue(val):
    """
    Return text where special characters was unescaped. This method is used to read values coming from INFO or FORMAT.

    :param val: A string value of an item of INFO or FORMAT.
    :type val: str
    :return: Text where special characters was unescaped (%3A, %3B, %3D, %2C).
    :rtype: str
    """
    return val.replace('%3A', ':').replace('%3B', ';').replace('%3D', '='
        ).replace('%2C', ',')


def supports_encryption() ->bool:
    """Test if we support encryption."""
    try:
        import nacl
        return True
    except OSError:
        return False


def resolve_ecodes(ecode_dict, ecode_list, unknown='?'):
    """
    Resolve event codes and types to their verbose names.

    Example
    -------
    >>> resolve_ecodes([272, 273, 274])
    [('BTN_MOUSE',  272), ('BTN_RIGHT',  273), ('BTN_MIDDLE', 274)]
    """
    res = []
    for ecode in ecode_list:
        if isinstance(ecode, tuple):
            if ecode[0] in ecode_dict:
                l = (ecode_dict[ecode[0]], ecode[0]), ecode[1]
            else:
                l = (unknown, ecode[0]), ecode[1]
        elif ecode in ecode_dict:
            l = ecode_dict[ecode], ecode
        else:
            l = unknown, ecode
        res.append(l)
    return res


@classmethod
def factory(cls):
    """Return a class of this sensor"""
    return cls


def check_name(name, reserved_names=()):
    """ Performs all checks associated with ``validate_name`` but also
        raises a :class:`substanced.folder.FolderKeyError` if an object with
        the name ``name`` already exists in the folder.  Returns the name (with
        any modifications) returned by ``validate_name``."""


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


@classmethod
def _fix_kline_pd(cls, kl_df, n_folds, start=None, end=None):
    """修复kline接口的返回金融时间序列"""
    return cls._fix_kline_pd_se(kl_df, n_folds, start=start, end=end)


def get_import_jobs(ApplicationId=None, PageSize=None, Token=None):
    """
    Returns information about your import jobs.

    :example: response = client.get_import_jobs(
        ApplicationId='string',
        PageSize='string',
        Token='string'
    )

    :type ApplicationId: string
    :param ApplicationId: [REQUIRED]

    :type PageSize: string
    :param PageSize:

    :type Token: string
    :param Token:

    :rtype: dict
    :return: {
        'ImportJobsResponse': {
            'Item': [
                {
                    'ApplicationId': 'string',
                    'CompletedPieces': 123,
                    'CompletionDate': 'string',
                    'CreationDate': 'string',
                    'Definition': {
                        'DefineSegment': True|False,
                        'ExternalId': 'string',
                        'Format': 'CSV'|'JSON',
                        'RegisterEndpoints': True|False,
                        'RoleArn': 'string',
                        'S3Url': 'string',
                        'SegmentId': 'string',
                        'SegmentName': 'string'
                    },
                    'FailedPieces': 123,
                    'Failures': [
                        'string',
                    ],
                    'Id': 'string',
                    'JobStatus': 'CREATED'|'INITIALIZING'|'PROCESSING'|'COMPLETING'|'COMPLETED'|'FAILING'|'FAILED',
                    'TotalFailures': 123,
                    'TotalPieces': 123,
                    'TotalProcessed': 123,
                    'Type': 'string'
                },
            ],
            'NextToken': 'string'
        }
    }

    :returns:
    (dict) -- 200 response
    ImportJobsResponse (dict) -- Import job list.
    Item (list) -- A list of import jobs for the application.
    (dict) --
    ApplicationId (string) -- The unique ID of the application to which the import job applies.
    CompletedPieces (integer) -- The number of pieces that have successfully imported as of the time of the request.
    CompletionDate (string) -- The date the import job completed in ISO 8601 format.
    CreationDate (string) -- The date the import job was created in ISO 8601 format.
    Definition (dict) -- The import job settings.
    DefineSegment (boolean) -- Sets whether the endpoints create a segment when they are imported.
    ExternalId (string) -- A unique, custom ID assigned to the IAM role that restricts who can assume the role.
    Format (string) -- The format of the files that contain the endpoint definitions. Valid values: CSV, JSON
    RegisterEndpoints (boolean) -- Sets whether the endpoints are registered with Amazon Pinpoint when they are imported.
    RoleArn (string) -- The Amazon Resource Name (ARN) of an IAM role that grants Amazon Pinpoint access to the Amazon S3 location that contains the endpoints to import.
    S3Url (string) -- A URL that points to the location within an Amazon S3 bucket that contains the endpoints to import. The location can be a folder or a single file. The URL should follow this format: s3://bucket-name/folder-name/file-name Amazon Pinpoint will import endpoints from this location and any subfolders it contains.
    SegmentId (string) -- The ID of the segment to update if the import job is meant to update an existing segment.
    SegmentName (string) -- A custom name for the segment created by the import job. Use if DefineSegment is true.

    FailedPieces (integer) -- The number of pieces that have failed to import as of the time of the request.
    Failures (list) -- Provides up to 100 of the first failed entries for the job, if any exist.
    (string) --

    Id (string) -- The unique ID of the import job.
    JobStatus (string) -- The status of the import job. Valid values: CREATED, INITIALIZING, PROCESSING, COMPLETING, COMPLETED, FAILING, FAILED The job status is FAILED if one or more pieces failed to import.
    TotalFailures (integer) -- The number of endpoints that failed to import; for example, because of syntax errors.
    TotalPieces (integer) -- The total number of pieces that must be imported to finish the job. Each piece is an approximately equal portion of the endpoints to import.
    TotalProcessed (integer) -- The number of endpoints that were processed by the import job.
    Type (string) -- The job type. Will be Import.

    NextToken (string) -- The string that you use in a subsequent request to get the next page of results in a paginated response.

    """
    pass


@staticmethod
def _get_name_from_dn(dn):
    """
        Get the instance name from the dn

        :param dn: string containing the distinguished name URL
        :return: string containing the name
        """
    if '/inst-' in dn:
        name = dn.split('/sys/inst-')[1].split('/')[0]
        return name
    elif '/ctx-' in dn:
        name = dn.split('/sys/ctx-')[1].split('/')[0]
        return name
    else:
        return None


def predictRecallMedian(prior, tnow, percentile=0.5):
    """Median (or percentile) of the immediate recall probability.

  Same arguments as `ebisu.predictRecall`, see that docstring for details.

  An extra keyword argument, `percentile`, is a float between 0 and 1, and
  specifies the percentile rather than 50% (median).
  """
    from scipy.special import betaincinv
    alpha, beta, t = prior
    dt = tnow / t
    return betaincinv(alpha, beta, percentile) ** dt


def gauss_print(d, value):
    """
    Decides how to print a parameter.
    For example, opt, opt=ts or opt=(ts,eigentest,calcfc).
    Checks a |Settings| object, `d`, for a key, `value`.
    For example, sett.input.freq=True in the script would
    produce 'freq', sett.input.scf='tight' would produce
    'scf=tight', and sett.input.opt='ts,noeigentest,calcfc'
    produces 'opt=(ts,noeigentest,calcfc)'. Note: doesn't
    work with lists or dict values, but unlikely that they would
    be passed in as settings values anyway.
    """
    if isinstance(d[f'{value}'], bool) or isinstance(d[f'{value}'], int):
        return value
    elif len(d[f'{value}'].split(',')) > 1 or '=' in d[f'{value}']:
        return f"{value}=({d[f'{value}']})"
    else:
        return f"{value}={d[f'{value}']}"


@staticmethod
def bg24(r, g, b):
    """Return 24-bit bg color ANSI escape sequence from an rgb value"""
    return '\x1b[48;2;{};{};{}m'.format(r, g, b)


@classmethod
def get_default(cls, interface, key):
    """Returns the value of the key for the default implementation of the
        provided interface, as defined in the 'default_plugins' section in
        the mush config file"""
    section = '{}.{}'.format(interface, cls._config.get('default_plugins',
        interface))
    return cls._config.get(section, key)


def is_ascii_problem(s):
    """
    Test if a string contains other chars than ASCII

    :param s: a string to test
    :return: True if string contains other chars than ASCII, False otherwise
    """
    try:
        s.encode('ascii')
        return False
    except (UnicodeEncodeError, UnicodeDecodeError):
        return True


@staticmethod
def get_group(match, group):
    """Get a group from a regular expression match object if it exists.

        Parameters
        ----------
        match : `_sre.SRE_Match`
            Regular expression match object.
        group : `str` or `int`
            Group name or index.

        Returns
        -------
        `str` or `None`
        """
    try:
        return match.group(group)
    except IndexError:
        return None


def add_named(linked: bool=False, name: str=''):
    """Add named object

    :param linked: Linked, Duplicate object but not object data, linking to the original data
    :type linked: bool
    :param name: Name, Object name to add
    :type name: str
    """
    pass


def remove_stack(topology, node):
    """Remove stack from a node

    Parameters
    ----------
    topology : Topology
        The topology
    node : any hashable type
        The ID of the node
    """
    topology.node[node].pop('stack', None)


def no_tradable_strategies_message():
    """
    Prints in the console a message saying that there is no Tradable Strategies.
    """
    print('\n----------------------------------------------')
    print('AI FOUND NO TRADE-ABLE STRATEGIES')
    print('----------------------------------------------')


def edit_field(name, numpy_dtype, shape, nullable=False):
    """
    A helper method to create the 4-tuples (name, numpy_dtype, shape, is_nullable)
    used in the `edit_fields` of `TransformSpec`.
    """
    return name, numpy_dtype, shape, nullable


def pick_first_not_none(*values):
    """Returns first of values that is *not* None (or None if all are/were)."""
    for val in values:
        if val is not None:
            return val
    return None


def consume_digest():
    """
        Retrieves the current digest message and clears the digest so
        add'l messages will be added to a new digest.
        """


def delitem_via_sibseqs(ol, *sibseqs):
    """
        from elist.elist import *
        y = ['a',['b',["bb"]],'c']
        y[1][1]
        delitem_via_sibseqs(y,1,1)
        y
    """
    pathlist = list(sibseqs)
    this = ol
    for i in range(0, pathlist.__len__() - 1):
        key = pathlist[i]
        this = this.__getitem__(key)
    this.__delitem__(pathlist[-1])
    return ol


@classmethod
def de_json(cls, json_type):
    """
        Returns an instance of this class from the given json dict or string.

        This function must be overridden by subclasses.
        :return: an instance of this class created from the given json dict or string.
        """
    raise NotImplementedError


def get_grouped_snapshots(snapshot, mode):
    """ Get grouped snapshots per opf mode

    Parameters
    ----------
    snapshot : datetime
    mode : str
        [day, week, month]
    """
    periods = {'day': snapshot.groupby(snapshot.day).values(), 'week':
        snapshot.groupby(snapshot.week).values(), 'month': snapshot.groupby
        (snapshot.month).values()}
    return periods[mode]


@classmethod
def from_wfs_element(cls, feature, namespace):
    """Build `Boring` instance from a WFS feature element.

        Parameters
        ----------
        feature : etree.Element
            XML element representing a single record of the WFS layer.
        namespace : str
            Namespace associated with this WFS featuretype.

        Returns
        -------
        boring : Boring
            An instance of this class populated with the data from the WFS
            element.

        """
    b = cls(feature.findtext('./{{{}}}fiche'.format(namespace)))
    for field in cls.get_fields(source=('wfs',)).values():
        b.data[field['name']] = cls._parse(func=feature.findtext, xpath=
            field['sourcefield'], namespace=namespace, returntype=field.get
            ('type', None))
    return b


def clone(cls, original):
    """Return an exact copy of an object."""
    """The original object must have an empty constructor."""
    return cls.create(original.__class__)


def hardsigmoid(attrs, inputs, proto_obj):
    """Computes elementwise hard sigmoid of the input array"""
    return 'hard_sigmoid', attrs, inputs


def types():
    """Get supported layer network types for network building."""
    return {'autoencoder': 'autoencoder', 'model': 'generic network model'}


def strip_url(url):
    """
    Best attempt to standardize websites.

    :input url: a string of a URl
    :returns: a URL stripped of www. and https:
    """
    if url:
        return url.replace('www.', '').replace('http://', '').replace(
            'https://', '').rstrip('/')
    else:
        return url


def is_mutable():
    """Return True if this file or directory is mutable (by *somebody*,
        not necessarily you), False if it is is immutable. Note that a file
        might be mutable overall, but your reference to it might be
        read-only. On the other hand, all references to an immutable file
        will be read-only; there are no read-write references to an immutable
        file."""


def date_value(dt):
    """
    Returns a string representation of a date for C3

    This is like .isoformat, only we strip the timezone info and
    output the time portion (as 00:00) for dates to make it easy
    for C3 to parse.
    """
    return dt.strftime('%Y-%m-%dT%H:%M:%S')


def atse_registerSchema(schema_id, schema, filtered_schemas=(),
    undeleteable_fields=(), undeleteable_schematas=('default', 'metadata'),
    domain='plone'):
    """ registers a working copy of a schema """


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


def insert(text: str=''):
    """Insert text at cursor position

    :param text: Text, Text to insert at the cursor position
    :type text: str
    """
    pass


def signature(frame):
    """return suitable frame signature to key display expressions off of."""
    if not frame:
        return None
    code = frame.f_code
    return code.co_name, code.co_filename, code.co_firstlineno


@classmethod
def from_index(cls, index):
    """Return the Enum value at a given index."""
    return cls.ALL[index]


def validate_format(*_arg):
    """
    This method can be overridden with format validation logic.
    """
    return True


def iso_name_slugify(name):
    """Slugify a name in the ISO-9660 way.

    Example:
        >>> slugify('épatant')
        "_patant"
    """
    name = name.encode('ascii', 'replace').replace(b'?', b'_')
    return name.decode('ascii')


@classmethod
def get_stats(cls):
    """Return the stats to the caller, clearing the list of what is returned

            We use a classmethod to support inheritance (over staticmethod)
        """
    result = list(cls.stats)
    del cls.stats[:len(result)]
    return result


def get_object_tid_after(cursor, oid, tid):
    """Returns the tid of the next change after an object revision.

        Returns None if no later state exists.
        """


@staticmethod
def encode_task(task):
    """ Encodes a task to its syllogistic encoding.

        Parameters
        ----------
        task : list(list(str))
            List representation of the syllogism (e.g., [['All', 'A', 'B'], ['Some', 'B', 'C']]).

        Returns
        -------
        str
            Syllogistic task encoding (e.g., 'AI1').

        Raises
        ------
        ValueError
            If figure of syllogism cannot be determined.

        """
    prem_1, prem_2 = task
    quant1 = prem_1[0].replace('All', 'A').replace('Some not', 'O').replace(
        'Some', 'I').replace('No', 'E')
    quant2 = prem_2[0].replace('All', 'A').replace('Some not', 'O').replace(
        'Some', 'I').replace('No', 'E')
    figure = 1
    if prem_1[1] == prem_2[1]:
        figure = 4
    elif prem_1[2] == prem_2[1]:
        figure = 1
    elif prem_1[2] == prem_2[2]:
        figure = 3
    elif prem_1[1] == prem_2[2]:
        figure = 2
    else:
        raise ValueError('Could not determine figure of:', task)
    return quant1 + quant2 + str(figure)


def new(name: str=''):
    """Create new mask

    :param name: Name, Name of new mask
    :type name: str
    """
    pass


def __new__(cls, *args):
    """Overrides `__new__()` from `aiohttp` BasicAuth to allow other authentication
        methods.
        """
    return tuple.__new__(cls, args)


def batch_take(a=None, indices=None, out=None, name=None, **kwargs):
    """Takes elements from a data batch.

    .. note::
      `batch_take` is deprecated. Use `pick` instead.

    Given an input array of shape ``(d0, d1)`` and indices of shape ``(i0,)``, the result will be
    an output array of shape ``(i0,)`` with::

      output[i] = input[i, indices[i]]

    Examples::

      x = [[ 1.,  2.],
           [ 3.,  4.],
           [ 5.,  6.]]

      // takes elements with specified indices
      batch_take(x, [0,1,0]) = [ 1.  4.  5.]

    Defined in src/operator/tensor/indexing_op.cc:L777

    Parameters
    ----------
    a : NDArray
        The input array
    indices : NDArray
        The index array

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

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


def acknowledge():
    """Acknowledge handling of a received message to the queue.

        Raises `RuntimeError` if message was not recived.
        """


def validate_group(group_name):
    """Check that a group of users is not named ``free`` or ``shared``

    Parameters
    ----------
    group_name : str
        Group name to be validated
    """
    if group_name == 'free':
        raise Exception(
            'Can\'t free memory from the "free" group... it\'s already free.')
    elif group_name == 'shared':
        raise Exception('"shared" can\'t be a group name')


def should_build_with_cython(package, release=None):
    """Returns the previously used Cython version (or 'unknown' if not
    previously built) if Cython should be used to build extension modules from
    pyx files.  If the ``release`` parameter is not specified an attempt is
    made to determine the release flag from `astropy.version`.
    """
    try:
        version_module = __import__(package + '.cython_version', fromlist=[
            'release', 'cython_version'])
    except ImportError:
        version_module = None
    if release is None and version_module is not None:
        try:
            release = version_module.release
        except AttributeError:
            pass
    try:
        cython_version = version_module.cython_version
    except AttributeError:
        cython_version = 'unknown'
    have_cython = False
    try:
        import Cython
        have_cython = True
    except ImportError:
        pass
    if have_cython and (not release or cython_version == 'unknown'):
        return cython_version
    else:
        return False


def get_links(mlist, msg, msgdata):
    """Get an `IChainIterator` for processing.

        :param mlist: The mailing list.
        :param msg: The message being processed.
        :param msgdata: The message metadata dictionary.
        :return: `IChainIterator`.
        """


def _sign(a):
    """ Return the sign of *a* """
    if a == 0.0:
        return 1
    else:
        return a / abs(a)


def workdays():
    """ Returns a list of week days to be considered as work days

            0: Monday
            ...
            6: Sunday
        """


def empty_function():
    """Function that does nothing."""
    return


def detect_face(fname, opFile):
    """
    TODO - not implemented
    storage = cv.CreateMemStorage()
    haar=cv.LoadHaarClassifierCascade('haarcascade_frontalface_default.xml')
    detected = cv.HaarDetectObjects(fname, haar, storage, 1.2, 2,cv.CV_HAAR_DO_CANNY_PRUNING, (100,100))
    if detected:
        for face in detected:
            print (face, 'saving to ', opFile)
    """
    print('detect_face NOT IMPLEMENTED: ', fname, opFile)


def describe_chap_credentials(TargetARN=None):
    """
    Returns an array of Challenge-Handshake Authentication Protocol (CHAP) credentials information for a specified iSCSI target, one for each target-initiator pair.
    See also: AWS API Documentation

    Examples
    Returns an array of Challenge-Handshake Authentication Protocol (CHAP) credentials information for a specified iSCSI target, one for each target-initiator pair.
    Expected Output:

    :example: response = client.describe_chap_credentials(
        TargetARN='string'
    )

    :type TargetARN: string
    :param TargetARN: [REQUIRED]
            The Amazon Resource Name (ARN) of the iSCSI volume target. Use the DescribeStorediSCSIVolumes operation to return to retrieve the TargetARN for specified VolumeARN.

    :rtype: dict
    :return: {
        'ChapCredentials': [
            {
                'TargetARN': 'string',
                'SecretToAuthenticateInitiator': 'string',
                'InitiatorName': 'string',
                'SecretToAuthenticateTarget': 'string'
            },
        ]
    }

    """
    pass


def testPredicate(expr_context):
    """Does this request match our predicate?
        """


def dms2decimal(decString, delimiter):
    """Converts a delimited string of Degrees:Minutes:Seconds format into
    decimal degrees.

    @type decString: string
    @param decString: coordinate string in D:M:S format
    @type delimiter: string
    @param delimiter: delimiter character in decString
    @rtype: float
    @return: coordinate in decimal degrees

    """
    if delimiter == '':
        decBits = str(decString).split()
    else:
        decBits = str(decString).split(delimiter)
    if len(decBits) > 1:
        decDeg = float(decBits[0])
        if decBits[0].find('-') != -1:
            if len(decBits) > 1:
                decDeg = decDeg - float(decBits[1]) / 60.0
            if len(decBits) > 2:
                decDeg = decDeg - float(decBits[2]) / 3600.0
        else:
            if len(decBits) > 1:
                decDeg = decDeg + float(decBits[1]) / 60.0
            if len(decBits) > 2:
                decDeg = decDeg + float(decBits[2]) / 3600.0
    else:
        decDeg = float(decString)
    return decDeg


def cpu():
    """Return a context object for CPU device."""
    pass


def associate_configuration_items_to_application(applicationConfigurationId
    =None, configurationIds=None):
    """
    Associates one or more configuration items with an application.
    See also: AWS API Documentation

    :example: response = client.associate_configuration_items_to_application(
        applicationConfigurationId='string',
        configurationIds=[
            'string',
        ]
    )

    :type applicationConfigurationId: string
    :param applicationConfigurationId: [REQUIRED]
            The configuration ID of an application with which items are to be associated.

    :type configurationIds: list
    :param configurationIds: [REQUIRED]
            The ID of each configuration item to be associated with an application.
            (string) --

    :rtype: dict
    :return: {}

    :returns:
    (dict) --

    """
    pass


@classmethod
def add_exception_handler(cls, handler):
    """Adds a specific L{ExceptionHandler} to the HTTP client
        @warning: SHOULD ONLY BE CALLED FROM A PROVIDER THROUGH A TEST
                  FIXTURE
        """
    cls._exception_handlers.append(handler)


def v111_defaults_process_manager(defaults, runtime, harmonization, dry_run):
    """
    Fix typo in proccess_manager parameter
    """
    changed = None
    if 'proccess_manager' in defaults:
        if 'process_manager' in defaults:
            del defaults['proccess_manager']
        elif 'process_manager' not in defaults:
            defaults['process_manager'] = defaults['proccess_manager']
            del defaults['proccess_manager']
        changed = True
    elif 'process_manager' not in defaults:
        defaults['process_manager'] = 'intelmq'
        changed = True
    return changed, defaults, runtime, harmonization


def load_handlers(name):
    """Load the (URL pattern, handler) tuples for each component."""
    mod = __import__(name, fromlist=['default_handlers'])
    return mod.default_handlers


def _precook_1d_args(a, n, axis):
    """Turn ``*(n, axis)`` into ``(s, axes)``
    """
    if n is not None:
        s = [int(n)]
    else:
        s = None
    a.shape[axis]
    return s, (axis,)


def getIndexId():
    """Catalog Index to be queried.
        """


def _to_tornado_pattern(transmute_path):
    """ convert a transmute path to
    a tornado pattern.
    """
    return transmute_path.replace('{', '(?P<').replace('}', '>.*)')


def whitespace_tokenize(text):
    """Runs basic whitespace cleaning and splitting on a peice of text."""
    text = text.strip()
    if not text:
        return []
    tokens = text.split()
    return tokens


def __new__(cls):
    """There is no reason to instantiate this class"""
    raise NotImplementedError()


def is_ip_address(ip: str):
    """
    Returns whether it is an IP address

    :param str ip: String
    :return: bool
    """
    try:
        import IPy
        _ = IPy.IP(ip)
        return True
    except:
        return False


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 verify_splits(splits, keyfunc):
    """ Verifies that the splits of each transaction sum to 0

    Args:
       splits (dict): return value of group_transactions()
       keyfunc (func): function that returns the transaction amount

    Returns:
        (bool): true on success

    Examples:
        >>> from operator import itemgetter
        >>> splits = [{'amount': 100}, {'amount': -150}, {'amount': 50}]
        >>> verify_splits(splits, itemgetter('amount'))
        True
        >>> splits = [{'amount': 200}, {'amount': -150}, {'amount': 50}]
        >>> verify_splits(splits, itemgetter('amount'))
        False
    """
    return not sum(map(keyfunc, splits))


def list_jobs_by_status(Status=None, Ascending=None, PageToken=None):
    """
    The ListJobsByStatus operation gets a list of jobs that have a specified status. The response body contains one element for each job that satisfies the search criteria.
    See also: AWS API Documentation

    :example: response = client.list_jobs_by_status(
        Status='string',
        Ascending='string',
        PageToken='string'
    )

    :type Status: string
    :param Status: [REQUIRED]
            To get information about all of the jobs associated with the current AWS account that have a given status, specify the following status: Submitted , Progressing , Complete , Canceled , or Error .

    :type Ascending: string
    :param Ascending: To list jobs in chronological order by the date and time that they were submitted, enter true . To list jobs in reverse chronological order, enter false .

    :type PageToken: string
    :param PageToken: When Elastic Transcoder returns more than one page of results, use pageToken in subsequent GET requests to get each successive page of results.

    :rtype: dict
    :return: {
        'Jobs': [
            {
                'Id': 'string',
                'Arn': 'string',
                'PipelineId': 'string',
                'Input': {
                    'Key': 'string',
                    'FrameRate': 'string',
                    'Resolution': 'string',
                    'AspectRatio': 'string',
                    'Interlaced': 'string',
                    'Container': 'string',
                    'Encryption': {
                        'Mode': 'string',
                        'Key': 'string',
                        'KeyMd5': 'string',
                        'InitializationVector': 'string'
                    },
                    'TimeSpan': {
                        'StartTime': 'string',
                        'Duration': 'string'
                    },
                    'InputCaptions': {
                        'MergePolicy': 'string',
                        'CaptionSources': [
                            {
                                'Key': 'string',
                                'Language': 'string',
                                'TimeOffset': 'string',
                                'Label': 'string',
                                'Encryption': {
                                    'Mode': 'string',
                                    'Key': 'string',
                                    'KeyMd5': 'string',
                                    'InitializationVector': 'string'
                                }
                            },
                        ]
                    },
                    'DetectedProperties': {
                        'Width': 123,
                        'Height': 123,
                        'FrameRate': 'string',
                        'FileSize': 123,
                        'DurationMillis': 123
                    }
                },
                'Inputs': [
                    {
                        'Key': 'string',
                        'FrameRate': 'string',
                        'Resolution': 'string',
                        'AspectRatio': 'string',
                        'Interlaced': 'string',
                        'Container': 'string',
                        'Encryption': {
                            'Mode': 'string',
                            'Key': 'string',
                            'KeyMd5': 'string',
                            'InitializationVector': 'string'
                        },
                        'TimeSpan': {
                            'StartTime': 'string',
                            'Duration': 'string'
                        },
                        'InputCaptions': {
                            'MergePolicy': 'string',
                            'CaptionSources': [
                                {
                                    'Key': 'string',
                                    'Language': 'string',
                                    'TimeOffset': 'string',
                                    'Label': 'string',
                                    'Encryption': {
                                        'Mode': 'string',
                                        'Key': 'string',
                                        'KeyMd5': 'string',
                                        'InitializationVector': 'string'
                                    }
                                },
                            ]
                        },
                        'DetectedProperties': {
                            'Width': 123,
                            'Height': 123,
                            'FrameRate': 'string',
                            'FileSize': 123,
                            'DurationMillis': 123
                        }
                    },
                ],
                'Output': {
                    'Id': 'string',
                    'Key': 'string',
                    'ThumbnailPattern': 'string',
                    'ThumbnailEncryption': {
                        'Mode': 'string',
                        'Key': 'string',
                        'KeyMd5': 'string',
                        'InitializationVector': 'string'
                    },
                    'Rotate': 'string',
                    'PresetId': 'string',
                    'SegmentDuration': 'string',
                    'Status': 'string',
                    'StatusDetail': 'string',
                    'Duration': 123,
                    'Width': 123,
                    'Height': 123,
                    'FrameRate': 'string',
                    'FileSize': 123,
                    'DurationMillis': 123,
                    'Watermarks': [
                        {
                            'PresetWatermarkId': 'string',
                            'InputKey': 'string',
                            'Encryption': {
                                'Mode': 'string',
                                'Key': 'string',
                                'KeyMd5': 'string',
                                'InitializationVector': 'string'
                            }
                        },
                    ],
                    'AlbumArt': {
                        'MergePolicy': 'string',
                        'Artwork': [
                            {
                                'InputKey': 'string',
                                'MaxWidth': 'string',
                                'MaxHeight': 'string',
                                'SizingPolicy': 'string',
                                'PaddingPolicy': 'string',
                                'AlbumArtFormat': 'string',
                                'Encryption': {
                                    'Mode': 'string',
                                    'Key': 'string',
                                    'KeyMd5': 'string',
                                    'InitializationVector': 'string'
                                }
                            },
                        ]
                    },
                    'Composition': [
                        {
                            'TimeSpan': {
                                'StartTime': 'string',
                                'Duration': 'string'
                            }
                        },
                    ],
                    'Captions': {
                        'MergePolicy': 'string',
                        'CaptionSources': [
                            {
                                'Key': 'string',
                                'Language': 'string',
                                'TimeOffset': 'string',
                                'Label': 'string',
                                'Encryption': {
                                    'Mode': 'string',
                                    'Key': 'string',
                                    'KeyMd5': 'string',
                                    'InitializationVector': 'string'
                                }
                            },
                        ],
                        'CaptionFormats': [
                            {
                                'Format': 'string',
                                'Pattern': 'string',
                                'Encryption': {
                                    'Mode': 'string',
                                    'Key': 'string',
                                    'KeyMd5': 'string',
                                    'InitializationVector': 'string'
                                }
                            },
                        ]
                    },
                    'Encryption': {
                        'Mode': 'string',
                        'Key': 'string',
                        'KeyMd5': 'string',
                        'InitializationVector': 'string'
                    },
                    'AppliedColorSpaceConversion': 'string'
                },
                'Outputs': [
                    {
                        'Id': 'string',
                        'Key': 'string',
                        'ThumbnailPattern': 'string',
                        'ThumbnailEncryption': {
                            'Mode': 'string',
                            'Key': 'string',
                            'KeyMd5': 'string',
                            'InitializationVector': 'string'
                        },
                        'Rotate': 'string',
                        'PresetId': 'string',
                        'SegmentDuration': 'string',
                        'Status': 'string',
                        'StatusDetail': 'string',
                        'Duration': 123,
                        'Width': 123,
                        'Height': 123,
                        'FrameRate': 'string',
                        'FileSize': 123,
                        'DurationMillis': 123,
                        'Watermarks': [
                            {
                                'PresetWatermarkId': 'string',
                                'InputKey': 'string',
                                'Encryption': {
                                    'Mode': 'string',
                                    'Key': 'string',
                                    'KeyMd5': 'string',
                                    'InitializationVector': 'string'
                                }
                            },
                        ],
                        'AlbumArt': {
                            'MergePolicy': 'string',
                            'Artwork': [
                                {
                                    'InputKey': 'string',
                                    'MaxWidth': 'string',
                                    'MaxHeight': 'string',
                                    'SizingPolicy': 'string',
                                    'PaddingPolicy': 'string',
                                    'AlbumArtFormat': 'string',
                                    'Encryption': {
                                        'Mode': 'string',
                                        'Key': 'string',
                                        'KeyMd5': 'string',
                                        'InitializationVector': 'string'
                                    }
                                },
                            ]
                        },
                        'Composition': [
                            {
                                'TimeSpan': {
                                    'StartTime': 'string',
                                    'Duration': 'string'
                                }
                            },
                        ],
                        'Captions': {
                            'MergePolicy': 'string',
                            'CaptionSources': [
                                {
                                    'Key': 'string',
                                    'Language': 'string',
                                    'TimeOffset': 'string',
                                    'Label': 'string',
                                    'Encryption': {
                                        'Mode': 'string',
                                        'Key': 'string',
                                        'KeyMd5': 'string',
                                        'InitializationVector': 'string'
                                    }
                                },
                            ],
                            'CaptionFormats': [
                                {
                                    'Format': 'string',
                                    'Pattern': 'string',
                                    'Encryption': {
                                        'Mode': 'string',
                                        'Key': 'string',
                                        'KeyMd5': 'string',
                                        'InitializationVector': 'string'
                                    }
                                },
                            ]
                        },
                        'Encryption': {
                            'Mode': 'string',
                            'Key': 'string',
                            'KeyMd5': 'string',
                            'InitializationVector': 'string'
                        },
                        'AppliedColorSpaceConversion': 'string'
                    },
                ],
                'OutputKeyPrefix': 'string',
                'Playlists': [
                    {
                        'Name': 'string',
                        'Format': 'string',
                        'OutputKeys': [
                            'string',
                        ],
                        'HlsContentProtection': {
                            'Method': 'string',
                            'Key': 'string',
                            'KeyMd5': 'string',
                            'InitializationVector': 'string',
                            'LicenseAcquisitionUrl': 'string',
                            'KeyStoragePolicy': 'string'
                        },
                        'PlayReadyDrm': {
                            'Format': 'string',
                            'Key': 'string',
                            'KeyMd5': 'string',
                            'KeyId': 'string',
                            'InitializationVector': 'string',
                            'LicenseAcquisitionUrl': 'string'
                        },
                        'Status': 'string',
                        'StatusDetail': 'string'
                    },
                ],
                'Status': 'string',
                'UserMetadata': {
                    'string': 'string'
                },
                'Timing': {
                    'SubmitTimeMillis': 123,
                    'StartTimeMillis': 123,
                    'FinishTimeMillis': 123
                }
            },
        ],
        'NextPageToken': 'string'
    }

    :returns:
    S3: Amazon S3 creates and manages the keys used for encrypting your files.
    S3-AWS-KMS: Amazon S3 calls the Amazon Key Management Service, which creates and manages the keys that are used for encrypting your files. If you specify S3-AWS-KMS and you don't want to use the default key, you must add the AWS-KMS key that you want to use to your pipeline.
    AES-CBC-PKCS7: A padded cipher-block mode of operation originally used for HLS files.
    AES-CTR: AES Counter Mode.
    AES-GCM: AES Galois Counter Mode, a mode of operation that is an authenticated encryption format, meaning that a file, key, or initialization vector that has been tampered with fails the decryption process.

    """
    pass


def scale_action(action_space, action):
    """
    Rescale the action from [low, high] to [-1, 1]
    (no need for symmetric action space)

    :param action_space: (gym.spaces.box.Box)
    :param action: (np.ndarray)
    :return: (np.ndarray)
    """
    low, high = action_space.low, action_space.high
    return 2.0 * ((action - low) / (high - low)) - 1.0


def reshapeParams(hyperparams, reshaper):
    """
    A utility function that takes a dictionary of transformations for valid hyperparameters
    and filters out invalid params

    Testing the function:
    print reshapeParams({'regParam': 'invalid', 'elasticNetParam': 0.1, 'maxDepth': 0.1}, {'regParam': float, 'elasticNetParam': float, 'threshold': float})
    # Expect: {'elasticNetParam': 0.1}
    :param hyperparams: the dirty dictionary
    :param reshaper: the transformations
    :return: the clean dictionary
    """
    d = {}
    for k, v in hyperparams.items():
        if reshaper.has_key(k):
            f = reshaper[k]
            if isinstance(v, str):
                if v.replace('.', '', 1).isdigit():
                    d[k] = f(v)
                else:
                    continue
            elif isinstance(v, float):
                d[k] = f(v)
            elif isinstance(v, int):
                d[k] = f(v)
            else:
                continue
        else:
            continue
    return d


def getRootNode(nodes):
    """Return the node with the most children"""
    max = 0
    root = None
    for i in nodes:
        if len(i.children) > max:
            max = len(i.children)
            root = i
    return root


def median(series, n):
    """
    中位数: 求series在n个周期内居于中间的数值

        注意:
            1. 当n为有效值但当前的series序列元素个数不足n个, 函数返回 NaN 序列
            2. 对n个周期内所有series排序后, 若n为奇数, 则选择第(n + 1) / 2个为中位数, 若n为偶数, 则中位数是(n / 2)以及(n / 2 + 1)的平均数

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

        n (int): 周期

    Returns:
        pandas.Series: 中位数序列

    Example::

        例1:
            # 假设最近3日的收盘价为2727, 2754, 2748, 那么当前 median(df["close"], 3) 的返回值是2748
            median3 = tafunc.median(df["close"], 3)

        例2:
            # 假设最近4日的开盘价为2752, 2743, 2730, 2728, 那么当前 median(df["open"], 4) 的返回值是2736.5
            median4 = tafunc.median(df["open"], 4)
    """
    median_data = series.rolling(n).median()
    return median_data


def grouper(iterable, n, fillvalue=None):
    """
    Collect data into fixed-length chunks or blocks.
    """
    args = [iter(iterable)] * n
    from itertools import zip_longest
    return zip_longest(*args, fillvalue=fillvalue)


def gearbar_3d_construction(c):
    """ construct the 3D-assembly-configurations of the gearbar
  """
    gearbar_3dconf1 = []
    gearbar_3dconf1.append(('gearbar_fig', 0.0, 0.0, 0.0, 0.0, c[
        'gear_profile_height'], 'i', 'xy', 0.0, 0.0, 0.0))
    r_assembly = {}
    r_slice = {}
    r_assembly['gearbar_3dconf1'] = gearbar_3dconf1
    hh = c['gear_profile_height'] / 2.0
    r_slice['gearbar_3dconf1'] = c['gearbar_length'], c['gearbar_height'], c[
        'gear_profile_height'], c['center_position_x'], c['center_position_y'
        ], 0.0, [hh], [], []
    return r_assembly, r_slice


def unindex(obj):
    """ queue an unindex operation for the given object """


def squashstr(string):
    """Squashes a string by removing the spaces and lowering it"""
    nospaces = ''.join(string.split())
    return nospaces.lower()


def getIdentifierForCurrentRequest(request):
    """Return the identifier integer for the current user"""
    NotImplemented


def split_first(s, delims):
    """
    Given a string and an iterable of delimiters, split on the first found
    delimiter. Return two split parts and the matched delimiter.

    If not found, then the first part is the full input string.

    Example::

        >>> split_first('foo/bar?baz', '?/=')
        ('foo', 'bar?baz', '/')
        >>> split_first('foo/bar?baz', '123')
        ('foo/bar?baz', '', None)

    Scales linearly with number of delims. Not ideal for large number of delims.
    """
    min_idx = None
    min_delim = None
    for d in delims:
        idx = s.find(d)
        if idx < 0:
            continue
        if min_idx is None or idx < min_idx:
            min_idx = idx
            min_delim = d
    if min_idx is None or min_idx < 0:
        return s, '', None
    return s[:min_idx], s[min_idx + 1:], min_delim


@classmethod
def search(cls, client=None, includes=True):
    """A search query for all uploads.

        Return an `Search` instance for searching image uploads.

        Parameters
        ----------
        includes : bool
            Controls the inclusion of events. If True, includes these objects.
            If False, no events are included. Defaults to True.
        client : :class:`CatalogClient`, optional
            A `CatalogClient` instance to use for requests to the Descartes Labs
            catalog.

        Returns
        -------
        :class:`~descarteslabs.catalog.search.Search`
            An instance of the `Search` class

        Example
        -------
        >>> from descarteslabs.catalog import properties as p
        >>> search = ImageUpload.search().filter(p.status == ImageUploadStatus.FAILURE)
        >>> for result in search:
                print(result)

        """
    from .search import Search
    return Search(cls, client=client, includes=includes)


def colorize(string, color, bold=False, highlight=False):
    """Return string surrounded by appropriate terminal color codes to
    print colorized text. Valid colors: gray, red, green, yellow,
    blue, magenta, cyan, white, crimson
    """
    color2num = dict(gray=30, red=31, green=32, yellow=33, blue=34, magenta
        =35, cyan=36, white=37, crimson=38)
    import six
    attr = []
    num = color2num[color]
    if highlight:
        num += 10
    attr.append(six.u(str(num)))
    if bold:
        attr.append(six.u('1'))
    attrs = six.u(';').join(attr)
    return six.u('\x1b[%sm%s\x1b[0m') % (attrs, string)


def log_error_and_raise(message, exception, logger):
    """
    logs an 'error' message and subsequently throws an exception

    :param message: message to log
    :param exception: exception to rise
    :param logger: logger to use
    """
    logger.error(message)
    raise exception(message)


def set_css_prompts(app, config):
    """Set default value for CSS prompt width (optimized for two-digit numbers)."""
    if config.ipysphinx_prompt_width is None:
        config.ipysphinx_prompt_width = {'agogo': '4ex', 'alabaster': '5ex',
            'better': '5ex', 'classic': '4ex', 'cloud': '5ex', 'dotted':
            '5ex', 'guzzle_sphinx_theme': '6ex', 'haiku': '4ex', 'julia':
            '5ex', 'maisie_sphinx_theme': '6ex', 'nature': '5ex', 'pangeo':
            '5ex', 'pyramid': '5ex', 'redcloud': '5ex', 'sizzle': '5.5ex',
            'sphinx_py3doc_enhanced_theme': '6ex', 'sphinx_pyviz_theme':
            '5.5ex', 'sphinx_rtd_theme': '5ex', 'sphinx_typlog_theme':
            '5.5ex', 'traditional': '4ex'}.get(config.html_theme, '7ex')


@staticmethod
def longer_transpositions_are_more_costly(pos1, pos2):
    """Longer Transpositions Are More Costly.

        Parameters
        ----------
        pos1 : int
            The position of the first transposition
        pos2 : int
            The position of the second transposition

        Returns
        -------
        float
            A cost that grows as difference in the positions increases

        .. versionadded:: 0.4.0

        """
    return abs(pos2 - pos1) / 9 + 1


@classmethod
def load(cls, filename):
    """
        Loads a WordDictionary object from a vocabulary file.
        """
    words = []
    with open(filename, 'rb') as f:
        for word in f:
            word = str(word, 'utf-8').strip()
            if word:
                words.append(word)
    return cls.init_from_wordlist(words)


def _fixIfWindowsPath(filename):
    """Convert Windows-style path to valid local URL.
    CifFile loads files using urlopen, which fails for Windows-style paths.

    filename -- path to be fixed

    Return fixed URL when run on Windows, otherwise return filename.
    """
    rv = filename
    if filename[:1].isalpha() and filename[1:3] == ':\\':
        from urllib.request import pathname2url
        rv = pathname2url(filename)
    return rv


def set_with_path(d, path, value):
    """In a nested dict/list data structure, set the entry at path.

    In a data structure composed of dicts, lists and tuples, apply each
    key in sequence, then set the resulting entry of the tree to value.
    This is done in-place!

    Args:
        d: Dict/list/tuple data structure
        path: List of keys
        value: Value to set

    """
    my_d = d
    for key in path[:-1]:
        my_d = my_d[key]
    my_d[path[-1]] = value


def removekwd(header, kwd):
    """ Helper function for removing keywords from FITS headers after first
        testing that they exist in the header

    Parameters:
    -----------
    header (pyfits.Header) : header object from a FITS file
    kwd (string) : name of the keyword to be removed

    Returns:
    --------
    None (header is modified in place)
    """
    if kwd in header.keys():
        header.remove(kwd)
    return


def not_filter(filter_predicate):
    """Negate a filter predicate with the logical NOT."""
    return lambda properties: not filter_predicate(properties)


def get_subcity(city, nodelist):
    """
    Returns (copied) subgraph of city object, only holding building nodes
    within nodelist building.
    Important: Returned subgraph is copy of (sub)graph!

    Raises assertion error, if nodes in nodelist are not
    building nodes. Does not include network or street nodes.

    Parameters
    ----------
    city : city object
        City object of pycity
    nodelist : list
        List of building node ids, which should be extracted

    Returns
    -------
    subcity : city object
        City object (only including chosen building nodes)
    """
    for node in nodelist:
        assert node in city.nodelist_building
    subcity = city.subgraph(nodelist).copy()
    subcity.environment = city.environment
    subcity.nodelist_building = nodelist
    return subcity


@classmethod
def check_token(cls, db, token):
    """Check if a token is acceptable"""
    if len(token) < cls.min_length:
        raise ValueError('Tokens must be at least %i characters, got %r' %
            (cls.min_length, token))
    found = cls.find(db, token)
    if found:
        raise ValueError('Collision on token: %s...' % token[:cls.
            prefix_length])


def uninstall(context):
    """Uninstall script"""


def face_map_deselect():
    """Deselect faces belonging to a face map

    """
    pass


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


def accuracy(output, target, topk=(1,)):
    """ Computes the precision@k for the specified values of k """
    maxk = max(topk)
    batch_size = target.size(0)
    _, pred = output.topk(maxk, 1, True, True)
    pred = pred.t()
    if target.ndimension() > 1:
        target = target.max(1)[1]
    correct = pred.eq(target.view(1, -1).expand_as(pred))
    res = []
    for k in topk:
        correct_k = correct[:k].view(-1).float().sum(0)
        res.append(correct_k.mul_(1.0 / batch_size))
    return res


def _lowess_wt_standardize(weights, new_entries, x_copy_i, width):
    """
    The initial phase of creating the weights.
    Subtract the current x_i and divide by the width.

    Parameters
    ----------
    weights : ndarray
        The memory where (new_entries - x_copy_i)/width will be placed
    new_entries : ndarray
        The x-values of the k closest points to x[i]
    x_copy_i : float
        x[i], the i'th point in the (sorted) x values
    width : float
        The maximum distance between x[i] and any point in new_entries

    Returns
    -------
    Nothing. The modifications are made to weight in place.
    """
    weights[:] = new_entries
    weights -= x_copy_i
    weights /= width


def get_content(obj):
    """ Works arround (sometimes) non predictible results of pythonzimbra

    Sometime, the content of an XML tag is wrapped in {'_content': foo},
    sometime it is accessible directly.
    """
    if isinstance(obj, dict):
        return obj['_content']
    else:
        return obj


def game_data_filter(game_data, season):
    """
  A function that fixes a problem with the 2012 game data
  ----------
  Parameters
  ----------
    game_data: DataFrame
    season: int
  """
    if season == 2012:
        army_temple = game_data[(game_data.home_team == 'Army') & (
            game_data.away_team == 'Temple')]
        if len(army_temple) > 1:
            game_data = game_data.drop(index=army_temple.index[0]).reset_index(
                drop=True)
    return game_data