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

        :param SfFbInviteType val:
        :rtype: EventType
        """
    return cls('sf_fb_invite', val)


def kde_statsmodels_u(x, x_grid, bandwidth=0.2, **kwargs):
    """Univariate Kernel Density Estimation with Statsmodels"""
    from statsmodels.nonparametric.kde import KDEUnivariate
    kde = KDEUnivariate(x)
    kde.fit(bw=bandwidth, **kwargs)
    return kde.evaluate(x_grid)


def get_iam_objects(iam_client_function, object_key, f_args=dict()):
    """
    users = get_iam_objects(iam_client.list_users, 'Users')
    """
    iam_objects = []
    response = iam_client_function(**f_args)
    iam_objects += response[object_key]
    if 'IsTruncated' in response:
        while response['IsTruncated']:
            response = iam_client_function(Marker=response['Marker'], **f_args)
            iam_objects += response[object_key]
    return iam_objects


def string_from_array(arr):
    """Encode an array as a string code.

    Parameters
    ----------
    arr : (N, k) array_like
        *Numpy* array.

    Returns
    -------
    str
        String code of an array.

    Examples
    --------
    >>> string_from_array(np.array([1, 0, 0]))
    '100'
    >>> string_from_array(np.array([[1,0], [3,4]]))
    '1034'
    """
    return ''.join(map(str, arr.flat))


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


def sid(s):
    """Ensure s is a valid UC Berkeley SID"""
    student_sid = s.strip()
    if len(student_sid) != 8:
        raise ValueError('SID must be 8 digits long')
    for digit in student_sid:
        if digit not in '0123456789':
            raise ValueError('Non-numeric digit in SID: %s' % digit)
    else:
        return student_sid


@classmethod
def _make(cls, iterable, new=tuple.__new__, len=len):
    """Make a new Literal object from a sequence or iterable"""
    result = new(cls, iterable)
    if len(result) != 3:
        raise TypeError('Expected 3 arguments, got %d' % len(result))
    return result


def is_transform_generator(fn):
    """Return true of the function has been marked with @transform_generator"""
    try:
        return fn.__dict__.get('is_transform_generator', False)
    except AttributeError:
        return False


def uptime():
    """Returns the uptime in seconds (float)"""
    file_obj = open('/proc/uptime', 'r')
    uptime = float(file_obj.readline().split()[0])
    file_obj.close()
    return uptime


def create_none_dataset(py_obj, h_group, call_id=0, **kwargs):
    """ Dump None type to file

    Args:
        py_obj: python object to dump; must be None object
        h_group (h5.File.group): group to dump data into.
        call_id (int): index to identify object's relative location in the iterable.
    """
    d = h_group.create_dataset('data_%i' % call_id, data=[0], **kwargs)
    d.attrs['type'] = [b'none']


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

        :param UserSelectorArg val:
        :rtype: RemoveCustomQuotaResult
        """
    return cls('invalid_user', val)


def _setval(key, val, dict_=None, delim=':'):
    """
    Set a value under the dictionary hierarchy identified
    under the key. The target 'foo:bar:baz' returns the
    dictionary hierarchy {'foo': {'bar': {'baz': {}}}}.
    """
    if not dict_:
        dict_ = {}
    prev_hier = dict_
    dict_hier = key.split(delim)
    for each in dict_hier[:-1]:
        if isinstance(each, str):
            if each not in prev_hier:
                prev_hier[each] = {}
            prev_hier = prev_hier[each]
        else:
            prev_hier[each] = [{}]
            prev_hier = prev_hier[each]
    prev_hier[dict_hier[-1]] = val
    return dict_


def viz_td(body, port=None, align='CENTER'):
    """Create HTML td for graphviz"""
    port_text = '' if port is None else 'PORT="{}"'.format(port)
    return '<TD {port_text} ALIGN="{align}">{body}</TD>'.format(**locals())


def dis_to_nearest_gene(region, genes, distance_cutoff=10000):
    """Compute the distance of  a specified region to the nearest gene TSS.

    Parameters
    ----------
    region : GenomicRegion
        GenomicRegion object.
    genes : list
        List of genes on that chromosome.
    distance_cutoff : int
        Maximal distance cutoff.

    Returns
    -------
    int or None
        A signed distance, positive if the region is located at the downstream
        of the nearest gene and vice versa. Or None if the distance is beyond
        the distance cutoff.
    """
    dis_min = distance_cutoff
    target_gene = None
    for gene in genes:
        tmp_dis = region.start - gene.tss
        if abs(tmp_dis) < dis_min:
            dis_min = tmp_dis
            target_gene = gene
    if target_gene is None:
        return None
    else:
        if target_gene.strand == '-':
            dis_min = -dis_min
        return dis_min


def project(batch, *args):
    """Projection onto the first argument.

       Needed to create a postprocessing pipeline that implements the identity.
    """
    return batch


def get_documentation_version(restApiId=None, documentationVersion=None):
    """
    See also: AWS API Documentation

    :example: response = client.get_documentation_version(
        restApiId='string',
        documentationVersion='string'
    )

    :type restApiId: string
    :param restApiId: [REQUIRED]
            [Required] The identifier of the API of the to-be-retrieved documentation snapshot.

    :type documentationVersion: string
    :param documentationVersion: [REQUIRED]
            [Required] The version identifier of the to-be-retrieved documentation snapshot.

    :rtype: dict
    :return: {
        'version': 'string',
        'createdDate': datetime(2015, 1, 1),
        'description': 'string'
    }

    """
    pass


def merge_dictionaries(first, *others):
    """
    Merge multiple dictionaries in one.

    When multiple dictionaries have the same key, then the value of the latest (right most) will be selected.
    :param Dict first: The first dictionary
    :param List[Dict] others: The rest of dictionaries to be merged in one.
    :return: One new dictionary with the union of all keys
    :rtype: Dict
    """
    out = first.copy()
    for other in others:
        out.update(other)
    return out


def deriv_v_φ_func(*, Z_2, deriv_v_r, dderiv_B_φ, norm_kepler, v_r, X, B_θ):
    """
    Compute the derivative of v_φ
    """
    return Z_2 - deriv_v_r * v_r / (2 * norm_kepler) + dderiv_B_φ * B_θ * X / (
        2 * norm_kepler)


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


@staticmethod
def __cleanse_postal_address(home_address):
    """
        Cleanse a home address.

        :param home_address: A string representing the address of a person or
            business.

        :return: A string which the leading, trailing, and duplicated space
            characters were removed.
        """
    return ' '.join(home_address.split())


def _is_section_key(key):
    """Is a Config key a section name (does it start with a capital)?"""
    if key and key[0].upper() == key[0] and not key.startswith('_'):
        return True
    else:
        return False


@classmethod
def FromPartition(cls, partition, **kwargs):
    """ Create a new partition from an existing partition.

    Parameters
    ----------
    partition
      The :class:`~VertexPartition.MutableVertexPartition` to replicate.

    **kwargs
      Any remaining keyword arguments will be passed on to the constructor of
      the new partition.

    Notes
    -----
    This may for example come in handy when determining the quality of a
    partition using a different method. Suppose that we already have a
    partition ``p`` and that we want to determine the Significance of that
    partition. We can then simply use

    >>> p = louvain.find_partition(ig.Graph.Famous('Zachary'),
    ...                            louvain.ModularityVertexPartition)
    >>> sig = louvain.SignificanceVertexPartition.FromPartition(p).quality()
    """
    new_partition = cls(partition.graph, partition.membership, **kwargs)
    return new_partition


def lerp(start, end, alpha):
    """
    Computes a linear interpolation between two values
    :param start: start value to interpolate from
    :param end:  end value to interpolate to
    :param alpha: how far we want to interpolate (0=start, 1=end)
    :return: float, result of the linear interpolation
    """
    return start + alpha * (end - start)


def load_from_disk(fname, **load_opts):
    """Load an object form disk using joblib.load.
    """
    import joblib
    return joblib.load(fname, **load_opts)


def suppress_output_after_render(app, out_text):
    """
    This is a ``post_render`` hook that suppresses console output again after
    rendering, only if the ``YamlOutputHandler`` is triggered via command
    line.

    :param app: The application object.

    """
    if not hasattr(app.pargs, 'output_handler_override'):
        return
    elif app.pargs.output_handler_override == 'yaml':
        app._suppress_output()


def sweep_log(start, stop, step=10):
    """Generator function to be used in sweeps.
Advantages towards the range python built-in functions_
    - Supports floating point arguments
    - Supports both up and down sweeps
    - Less memory footprint for large sweeps"""
    stp = abs(step)
    if start < stop:
        while start <= stop:
            yield start
            start *= stp
    elif start > stop:
        while start >= stop:
            yield start
            start /= stp


def __call__(context):
    """The *context* provides a location that the vocabulary can make use of.
        """


def get_level():
    """Return a string representation of the log level."""


def create_color_name(c):
    """
    Checks if the color name is a proper color name. If not it will convert the name to a proper style.
    :param c: The input color name
    :type c: str
    :return: The input color name in a proper style
    :rtype: str
    """
    if 'mag' not in c:
        c = c.split('-')
        c = '{}mag - {}mag'.format(c[0].replace(' ', ''), c[1].replace(' ', '')
            )
    return c


def flatten(lst):
    """For an iterable of sub-iterables, generate each member of each
    sub-iterable in turn, i.e. a flattened version of that super-iterable.

    Example: Turn [[a,b,c],[d,e,f]] into [a,b,c,d,e,f].
    """
    for sublist in lst:
        for j in sublist:
            yield j


def editsource():
    """Edit UI source code of the active button

    """
    pass


def build_signature(function_name, function_parameters):
    """
    Given the function name and function parameters, returns the signature line

    :param function_name: the name of the function
    :param function_parameters: the parameters of the function (whatever would be
      within the brackets)
    """
    return 'def {}({}):'.format(function_name, function_parameters)


def gen_folder(posix_path_folder):
    """Yield immediate subdirectories inside a folder."""
    for posix_path in posix_path_folder.iterdir():
        if posix_path.is_dir():
            yield posix_path


@staticmethod
def filtered_id(pair_ids_with_ems):
    """return the pair_id if there is at least one not None value, else returns None"""
    pair_id = None
    for id_ in pair_ids_with_ems:
        if id_ is not None:
            pair_id = id_
    return pair_id


def get_blue(pix):
    """Return the blue value of Pixel pix."""
    return pix.get_blue()


def create_indexes(table, columns):
    """Create all of the necessary indexes for the given table name."""
    for column in columns:
        table.create_index(column)


def no_none(s):
    """ Template helper: prevent None from appearing in output.
    @param s: the input value
    @returns: a string version of the value, or "" if None
    """
    return str(s) if s is not None else ''


def t_INTEGER64(t):
    """[-+]?[0-9]+L(L)?"""
    t.value = int(t.value[:-1])
    return t


@classmethod
def get_tunable(cls, what, default):
    """
        Returns either an overridden tunable, or the default value.
        The result will be casted to the type of default.

        :param what: tunable to look up
        :type what: str
        :param default: default value
        :return: either the overridden tunable or the default value

        >>> tunable('my.tunable', 3.1415)
        3.1415
        """
    cls.defaults[what] = default
    if cls.force_default or what not in cls.current:
        result = default
        if cls.force_default:
            cls.logger.debug('Getting tunable "%s", forcing default: %s',
                what, repr(result))
        else:
            cls.logger.debug('Getting tunable "%s", using default: %s',
                what, repr(result))
    else:
        result = type(default)(cls.current[what])
        cls.logger.debug('Getting tunable "%s", using override: %s', what,
            repr(result))
    return result


def get_rms_bq(var):
    """
    Return the RMS base quality at this position
    """
    return var.INFO.get('BQ')


@classmethod
def get_sensor_thermal_rel(cls, session, server_key, relationship):
    """Get thermal details about thermal relationship
        Args:e
            session: database session
            server_key(int): key of the server sensor(s) belong to
            relationship(dict): source, target and event
        """
    query = []
    query.append(
        'MATCH (:ServerWithBMC {{ key: {} }})-[:HAS_SENSOR]->(source:Sensor {{ name: "{}" }})'
        .format(server_key, relationship['source']))
    query.append(
        'MATCH (source)<-[rel :COOLED_BY|:HEATED_BY]-(target {{ {}: {} }})'
        .format(relationship['target']['attribute'], relationship['target']
        ['value']))
    query.extend(['WHERE rel.event = "{}"'.format(relationship['event']),
        'RETURN source, target, rel'])
    results = session.run('\n'.join(query))
    record = results.single()
    return {'source': dict(record.get('source')), 'target': dict(record.get
        ('target')), 'rel': dict(record.get('rel'))} if record else None


def array_has_real_numbers(array):
    """ Uses the dtype kind of the numpy array to determine if it represents real numbers.

        That is, the array kind should be one of: i u f

        Possible dtype.kind values.
            b 	boolean
            i 	signed integer
            u 	unsigned integer
            f 	floating-point
            c 	complex floating-point
            m 	timedelta
            M 	datetime
            O 	object
            S 	(byte-)string
            U 	Unicode
            V 	void
    """
    kind = array.dtype.kind
    assert kind in 'biufcmMOSUV', 'Unexpected array kind: {}'.format(kind)
    return kind in 'iuf'


def addMessage(msgid, msg, language, mod_time=None):
    """Add a message to the translation domain.

        If `mod_time` is ``None``, then the current time should be inserted.
        """


def print_issues_by_uri(uri_dict, save_fp=''):
    """Print a tab-delimited list of uris with the issues connected to them.
    URI     Issue number    Issue label

    Args:
        uri_dict (dict): key: uri,
                         value: list of github issues related to this uri

    Returns:
        None
    """
    s = '{}\t{}\t{}\t{}\n'.format('URI', 'Issue number', 'Issue label',
        'Issue state')
    for uri, issues in sorted(uri_dict.items()):
        for issue in issues:
            for label in issue.labels:
                s += '{}\t{}\t{}\t{}\n'.format(uri, issue.number, label.
                    name, issue.state)
    if save_fp:
        print('Saved list of issues to', save_fp)
        with open(save_fp, mode='w', encoding='utf-8') as file:
            file.write(s)
    else:
        print(s)


def metric(series, category):
    """Return value for the given metric"""


def get_text():
    """Return the text content of the file or TypesError is it's
        not a text file.
        """


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


@staticmethod
def generate_queue_endpoint(region, accountid, queue_name):
    """
            @type region: string
            @param region: the region of queue, such as: cn-hangzhou

            @type accountid: string
            @param accountid: the accountid of queue's owner

            @type queue_name: string
            @param queue_name
        """
    return 'acs:mns:%s:%s:queues/%s' % (region, accountid, queue_name)


def url_match(url1: str, url2: str) ->bool:
    """
    This function takes two urls and check if they are the same modulo '/' at the end
    :param url1: mandatory, the first url
    :type url1: str

    :param url2: mandatory, the second url
    :type url2: str

    :rtype: Boolean
    """
    return url1 == url2 or url1[:-1] == url2 or url1 == url2[:-1]


def days(days, zero_allowed=False):
    """
    Makes sure our argument is valid.
    0-28
    Keep in mind that 0 days implies no expiration and is
    only allowed if override_code is set.

    0 is invalid unless zero_allowed is True.
    """
    if not isinstance(days, int):
        raise TypeError('days must be an integer type')
    if zero_allowed is True:
        minimum_days = 0
    else:
        minimum_days = 1
    if days < minimum_days or days > 28:
        raise ValueError('days must be {}-28'.format(minimum_days))
    return True


def tuples2ids(tuples, ids):
    """Update `ids` according to `tuples`, e.g. (3, 0, X), (4, 0, X)..."""
    for value in tuples:
        if value[0] == 6 and value[2]:
            ids = value[2]
        elif value[0] == 5:
            ids[:] = []
        elif value[0] == 4 and value[1] and value[1] not in ids:
            ids.append(value[1])
        elif value[0] == 3 and value[1] and value[1] in ids:
            ids.remove(value[1])
    return ids


def get_targeted_value(value, target):
    """ Given a value that may be scoped by one or more targets, the unscoped
    value is returned if it is being targeted by the given architecture.  If it
    isn't then None is returned.
    """
    parts = value.split('#', maxsplit=1)
    if len(parts) == 2:
        scope, value = parts
        if not target.is_targeted(scope):
            value = None
    return value


@staticmethod
def _rearrange_ode(x, y, coeff_b, fx):
    """Rearrange coefficients for scipy solver.

        Parameters
        ----------
        x : np.ndarray(N,)
            Points from desired domain
        y : np.ndarray(order, N)
            Initial guess for the function values and its derivatives
        coeff_b : list[number] or np.ndarray(Order + 1)
            Coefficients for each differential part on ODE
        fx : np.ndarray(N,)
            Non-homogeneous term at given x

        Returns
        -------
        np.ndarray(N,)
            proper expr for the right side of the ODE equation
        """
    result = fx
    for i, b in enumerate(coeff_b[:-1]):
        result -= b * y[i]
    return result / coeff_b[-1]


@classmethod
def match_header(cls, header):
    """
        This is an abstract HDU type for HDUs that contain table-like data.
        This is even more abstract than _TableBaseHDU which is specifically for
        the standard ASCII and Binary Table types.
        """
    raise NotImplementedError


def get_user_by_email(email):
    """ Return an IUser object or ``None`` if no such user exists. The
        ``email`` argument is the *email address* of the user."""


def Terfous(Re):
    """Calculates drag coefficient of a smooth sphere using the method in
    [1]_ as described in [2]_.

    .. math::
        C_D = 2.689 + \\frac{21.683}{Re} + \\frac{0.131}{Re^2}
        - \\frac{10.616}{Re^{0.1}} + \\frac{12.216}{Re^{0.2}}

    Parameters
    ----------
    Re : float
        Particle Reynolds number of the sphere using the surrounding fluid
        density and viscosity, [-]

    Returns
    -------
    Cd : float
        Drag coefficient [-]

    Notes
    -----
    Range is 0.1 < Re <= 5E4

    Examples
    --------
    >>> Terfous(200.)
    0.7814651149769638

    References
    ----------
    .. [1] Terfous, A., A. Hazzab, and A. Ghenaim. "Predicting the Drag
       Coefficient and Settling Velocity of Spherical Particles." Powder
       Technology 239 (May 2013): 12-20. doi:10.1016/j.powtec.2013.01.052.
    .. [2] Barati, Reza, Seyed Ali Akbar Salehi Neyshabouri, and Goodarz
       Ahmadi. "Development of Empirical Models with High Accuracy for
       Estimation of Drag Coefficient of Flow around a Smooth Sphere: An
       Evolutionary Approach." Powder Technology 257 (May 2014): 11-19.
       doi:10.1016/j.powtec.2014.02.045.
    """
    return (2.689 + 21.683 / Re + 0.131 / Re ** 2 - 10.616 / Re ** 0.1 +
        12.216 / Re ** 0.2)


@classmethod
def map_size(cls, level_of_detail):
    """
        确定指定级别上的地图宽度和高度（以像素为单位）

        :param level_of_detail: 地图级别
        :return: 地图边长（像素）
        """
    return 256 << level_of_detail


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

        :returns: this backend supports items archive
        """
    return True


def smooth(x, window_len=11, window='hanning'):
    """smooth the data using a window with requested size.

    This method is based on the convolution of a scaled window with the signal.
    The signal is prepared by introducing reflected copies of the signal
    (with the window size) in both ends so that transient parts are minimized
    in the begining and end part of the output signal.

    input:
        x: the input signal
        window_len: the dimension of the smoothing window; should be an odd integer
        window: the type of window from 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'
            flat window will produce a moving average smoothing.

    output:
        the smoothed signal

    example:

    t=linspace(-2,2,0.1)
    x=sin(t)+randn(len(t))*0.1
    y=smooth(x)

    see also:

    numpy.hanning, numpy.hamming, numpy.bartlett, numpy.blackman, numpy.convolve
    scipy.signal.lfilter

    TODO: the window parameter could be the window itself if an array instead of a string
    """
    from numpy.core.numeric import ones
    import numpy
    x = numpy.array(x)
    if x.ndim != 1:
        raise ValueError('smooth only accepts 1 dimension arrays.')
    if x.size < window_len:
        raise ValueError('Input vector needs to be bigger than window size.')
    if window_len < 3:
        return x
    if not window in ['flat', 'hanning', 'hamming', 'bartlett', 'blackman']:
        raise ValueError(
            "Window is on of 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'"
            )
    s = numpy.r_[2 * x[0] - x[window_len:1:-1], x, 2 * x[-1] - x[-1:-
        window_len:-1]]
    if window == 'flat':
        w = ones(window_len, 'd')
    else:
        w = eval('numpy.' + window + '(window_len)')
    y = numpy.convolve(w / w.sum(), s, mode='same')
    return y[window_len - 1:-window_len + 1]


def display_dict_dropdown(dict_to_display):
    """Display the model_params dictionary as a dropdown menu."""
    from ipywidgets import interact
    from IPython.display import display
    from pprint import pprint
    dash = '---'
    print(f'{dash * 4} Dictionary Contents {dash * 4}')

    @interact(dict_to_display=dict_to_display)
    def display_params(dict_to_display):
        pprint(dict_to_display)
        return


def p_class_name_static(p):
    """class_name : STATIC"""
    p[0] = p[1].lower()


def importUrllib():
    """Imports the urllib2 module in a Python2/3 agnostic way."""
    try:
        import urllib2 as urllib_req
    except ModuleNotFoundError:
        import urllib.request as urllib_req
    return urllib_req


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

        :param FileGetCopyReferenceDetails val:
        :rtype: EventDetails
        """
    return cls('file_get_copy_reference_details', val)


def register_resource_views(config, resource):
    """Register a resource and it's views.

    :param config:
        The pyramid configuration object that will be populated.
    :param resource:
        The resource class containing the definitions
    """
    services = resource._services
    for service in services.values():
        config.add_cornice_service(service)


def print_bold(msg, end='\n'):
    """Convenience function to print a message in bold style

    Optionally you can also specify how the bold text should end. By default
    it ends with a new line character.

    :arg msg: Message to be converted to bold style
    :arg end: Tell how the printed string should end (newline, space etc)
    """
    print('\x1b[1m' + msg + '\x1b[0m', end=end)


def parselist(environ, key, sep=':', cls=tuple):
    """Parses the environment variable into an iterable,
    using `sep` as a separator e.g.::

    >>> from unimatrix.lib.environ import parselist
    >>> parselist({'foo': '1:2'}, 'foo')
    ('1', '2')
    """
    values = environ.get(key) or ''
    return cls(filter(bool, str.split(values, sep)))


@classmethod
def _get_pdi(cls, df, windows):
    """ +DI, positive directional moving index

        :param df: data
        :param windows: range
        :return:
        """
    window = cls.get_only_one_positive_int(windows)
    pdm_column = 'pdm_{}'.format(window)
    tr_column = 'atr_{}'.format(window)
    pdi_column = 'pdi_{}'.format(window)
    df[pdi_column] = df[pdm_column] / df[tr_column] * 100
    return df[pdi_column]


def str_len(s):
    """
    获取占用等宽字体终端实际宽度，适用`Monaco`等其他等宽字体字体
    :param s:
    :return:
    """
    length = 0
    for i in s:
        if 3105 <= ord(i) <= 65535:
            length += 2
        else:
            length += 1
    return length


@staticmethod
def db_serialize(value):
    """ Трансформирование объекта в БД. Необходимо для преобразования сложных типов данных. """
    if value is None:
        return None
    else:
        return str(value)


def add_basic_layout(p):
    """Add basic layout to certain plot
    Parameters
    ----------
    p : bokeh object
        defines plot where line and scatter should be added
    """
    p.title.align = 'left'
    p.title.text_color = '#c85108'
    p.title.text_font_size = '25px'
    p.background_fill_color = '#efefef'
    p.xaxis.axis_label_text_font_size = '14pt'
    p.xaxis.axis_label_text_color = '#2D353C'
    p.yaxis.axis_label_text_font_size = '14pt'
    p.yaxis.axis_label_text_color = '#2D353C'
    p.xaxis.major_tick_line_color = 'firebrick'
    p.xaxis.major_tick_line_width = 2
    p.xaxis.minor_tick_line_color = '#c85108'


def drop_column(table_name, column_name, conn, schema=None):
    """Drops a column of a table.

    Parameters
    ----------
    table_name : str
        table name
    column_name : str
        column name
    conn : sqlalchemy.engine.base.Engine
        an sqlalchemy connection engine created by function `create_engine()`
    schema : str or None
        schema name
    """
    column_name = column_name.replace('%', '%%')
    if schema is None:
        query_str = 'ALTER TABLE "{}" DROP COLUMN "{}";'.format(table_name,
            column_name)
    else:
        query_str = 'ALTER TABLE "{}"."{}" DROP COLUMN "{}";'.format(schema,
            table_name, column_name)
    conn.execute(query_str)


@classmethod
def from_existing_session(cls, session: object, driver_options: str=None
    ) ->'Core':
    """Creates a new Core object with the entered 'session' reused."""
    return cls(None, False, False, driver_options, None, session)


@staticmethod
def _sanitize_input(minvals, maxvals):
    """Normalizes the input of minvals and maxvals.

        Parameters
        ----------
        minvals : float or int or list of float or list of int
            the minimum value(s) for the interface set
        maxvals : float or int or list of float or list of int
            the maximum value(s) for the interface set

        Returns
        -------
        minvals : list
            minimum values as a list
        maxvals : list
            maximum values as a list
        direction : 1, -1, or 0
            whether the maximum value are increasing (1), the minimum values
            are decreasing (-1), or it is unclear (0). "Unclear" can happen
            if both are changing or if neither are changing.
        """
    direction = 0
    try:
        len_min = len(minvals)
    except TypeError:
        len_min = 1
        minvals = [minvals]
    try:
        len_max = len(maxvals)
    except TypeError:
        len_max = 1
        maxvals = [maxvals]
    if len_min == len_max:
        if minvals.count(minvals[0]) == len_min:
            direction += 1
        if maxvals.count(maxvals[0]) == len_max:
            direction += -1
    elif len_max > len_min == 1:
        direction = 1
    elif len_min > len_max == 1:
        direction = -1
    else:
        raise RuntimeError("Can't reconcile array lengths: " + str(minvals) +
            ', ' + str(maxvals))
    minvs = minvals
    maxvs = maxvals
    if len_min == 1:
        minvs = minvs * len(maxvs)
    if len_max == 1:
        maxvs = maxvs * len(minvs)
    return minvs, maxvs, direction


def import_module(module):
    """Returns a module.

    For example, if you do import_module('foo.bar.baz'), it returns
    the 'baz' module instead of 'foo'.
    """
    m = __import__(module)
    for x in module.split('.'):
        m = getattr(m, x)
    return m


def time_for_json(value):
    """
    Return a Python ``datetime``, and rely on the JSON encoder in
    :mod:`da.protocols.ser_json` to do the appropriate conversion.
    """
    return value


def append_if_not_exists(lst, item):
    """
        Append to the list only if item does not exist yet
    """
    if item not in lst:
        lst.append(item)


def serie_spreads(prices1: list, prices2: list) ->list:
    """Retorna serie dos spreads entre duas séries de preços."""
    res = []
    for i in range(len(prices1)):
        spread = abs(prices2[i] - prices1[i])
        res.append(spread)
    return res


def is_valid(email):
    """Check if an email address if valid.

        :param email: A text email address.
        :type email: str
        :return: A flag indicating whether the email address is okay or not.
        :rtype: bool
        """


@classmethod
def get_by_uuid(cls, context, uuid):
    """Find a portgroup by UUID and return a :class:`Portgroup` object.

        :param cls: the :class:`Portgroup`
        :param context: Security context
        :param uuid: The UUID of a portgroup.
        :returns: A :class:`Portgroup` object.
        :raises: PortgroupNotFound

        """
    db_portgroup = cls.dbapi.get_portgroup_by_uuid(uuid)
    portgroup = cls._from_db_object(context, cls(), db_portgroup)
    return portgroup


@classmethod
def get_polymorphic_serializer_for_instance(cls, instance):
    """
        Return the polymorphic serializer associated with the given instance/model.
        Raise `NotImplementedError` if no serializer is found for the given model. This usually
        means that a serializer is missing in the class's `polymorphic_serializers` attribute.
        """
    try:
        return cls._poly_model_serializer_map[instance._meta.model]
    except KeyError:
        raise NotImplementedError(
            'No polymorphic serializer has been found for model {}'.format(
            instance._meta.model.__name__))


def gini(distances):
    """Calculate an approximation of the Gini coefficient for a set of values.

    The Gini coefficient represents the evenness of a set of values, and is in
    the range [0,1], where 0 is perfectly even and 1 is perfectly uneven.

    In practice, this means that sets with low Gini coefficients have more even
    binding frequencies and are more likely to not favor highly-repeated regions
    or other aberrations in the target genome.

    :param distances: a vector of primer binding distances (from each other)
    """
    distances.sort()
    height = area = 0
    for value in distances:
        height += value
        area += height - value / 2.0
    fair_area = height * len(distances) / 2
    return (fair_area - area) / fair_area


def create_compound(obj, compound, builder):
    """Add objects to compound using builder.

    Args:
        obj (list): list of objects to be added to compound
        compound (obj): the compound
        builder (obj): BREP builder
    """
    for solid in obj:
        builder.Add(compound, solid)


def encode(obj):
    """Return an object encoded to its DAP representation."""
    try:
        return '%.6g' % obj
    except:
        return '"{0}"'.format(obj)


def _head(title):
    """Returns the "head" section of HTML"""
    return (
        '<!DOCTYPE html>\n<html>\n<head>\n  <title>%s</title>\n</head>\n' %
        title)


@staticmethod
def vertical_length_carryover_start(sub_matrix):
    """
        Start index of the sub matrix specific segment within the global vertical length carryover array.

        :param sub_matrix: Sub matrix.
        :return: Vertical length carryover start.
        """
    return sub_matrix.start_x


@classmethod
def reset_meters(cls):
    """Reset the Summary meter."""
    for meter in cls.meters:
        from tamarco.resources.basic.metrics.meters import Summary
        if isinstance(meter, Summary):
            meter._reset()


@classmethod
def get(cls, descriptors, config=None):
    """Get a connection from the registry based on the descriptor"""
    primary, secondary = descriptors
    if primary:
        cls.current = cls.connections.get(primary)
        if not cls.current:
            cls.currernt = cls._get_connection(primary, secondary, config)
        elif secondary:
            cls._replace_alias(cls.current, secondary)
    elif not cls.current:
        cls.current = cls._get_connection(config.uri, None, config)
    return cls.current


def is_abstract_model(model):
    """
    Checks model whether it abstract or not.
    """
    is_instantiated_table = hasattr(model, '__table__')
    has_specified_abstract_attribute = getattr(model, '__abstract__', False)
    return not is_instantiated_table and has_specified_abstract_attribute


def to_unicode(s, encoding='utf-8'):
    """Convert to `unicode` string.

    :param s: String to convert.
    :param str encoding: Encoding codec.
    :return: `unicode` string, it's `unicode` in Python 2.x, `str` or `unicode` in Python 3.x.
    :rtype: unicode

    * In Python 2, convert `s` to `unicode` if it's `str` or `bytes`.
    * In Python 2, return original `s` if it's neither `str` or `bytes`.
    * In Python 3, convert `s` to `str` or `unicode` if it's `bytes`.
    * In Python 3, return original `s` if it's not `bytes`.
    * In Python 3, it equals to :func:`to_str`.
    """
    if isinstance(s, bytes):
        return s.decode(encoding)
    else:
        return s


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


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

        :param SfTeamUninviteDetails val:
        :rtype: EventDetails
        """
    return cls('sf_team_uninvite_details', val)


@classmethod
def WriteSerializedDict(cls, attribute_container):
    """Writes an attribute container to serialized form.

    Args:
      attribute_container (AttributeContainer): attribute container.

    Returns:
      dict[str, object]: JSON serialized objects.
    """
    return cls._ConvertAttributeContainerToDict(attribute_container)


@classmethod
def program_name(cls):
    """Return the name of the program that this main window represents"""
    return cls.__name__


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

        :param MemberAddNameType val:
        :rtype: EventType
        """
    return cls('member_add_name', val)


def k2c(k):
    """Converts Kelvin to Celsius."""
    return k - 273.15


def describe_reserved_nodes(ReservedNodeId=None, MaxRecords=None, Marker=None):
    """
    Returns the descriptions of the reserved nodes.
    See also: AWS API Documentation

    :example: response = client.describe_reserved_nodes(
        ReservedNodeId='string',
        MaxRecords=123,
        Marker='string'
    )

    :type ReservedNodeId: string
    :param ReservedNodeId: Identifier for the node reservation.

    :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 DescribeReservedNodes 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.

    :rtype: dict
    :return: {
        'Marker': 'string',
        'ReservedNodes': [
            {
                'ReservedNodeId': 'string',
                'ReservedNodeOfferingId': 'string',
                'NodeType': 'string',
                'StartTime': datetime(2015, 1, 1),
                'Duration': 123,
                'FixedPrice': 123.0,
                'UsagePrice': 123.0,
                'CurrencyCode': 'string',
                'NodeCount': 123,
                'State': 'string',
                'OfferingType': 'string',
                'RecurringCharges': [
                    {
                        'RecurringChargeAmount': 123.0,
                        'RecurringChargeFrequency': 'string'
                    },
                ]
            },
        ]
    }

    :returns:
    pending-payment-This reserved node has recently been purchased, and the sale has been approved, but payment has not yet been confirmed.
    active-This reserved node is owned by the caller and is available for use.
    payment-failed-Payment failed for the purchase attempt.

    """
    pass


def _get_all_edges(bsp_nodes):
    """
    Get all possible straight edges between rooms in leaf nodes of BSP-tree.
    """
    all_edges = []
    for n1 in bsp_nodes:
        for n2 in bsp_nodes:
            if n1.uid == n2.uid:
                continue
            n1_x2 = n1.x + n1.w
            n1_y2 = n1.y + n1.h
            n2_x2 = n2.x + n2.w
            n2_y2 = n2.y + n2.h
            max_rx1 = max(n1.room_x1, n2.room_x1)
            max_ry1 = max(n1.room_y1, n2.room_y1)
            min_rx2 = min(n1.room_x2, n2.room_x2)
            min_ry2 = min(n1.room_y2, n2.room_y2)
            if (n1.y == n2_y2 or n1_y2 == n2.y) and max_rx1 < min_rx2 and min(
                n1_x2, n2_x2) - max(n1.x, n2.x) > 0.6 * min(n1.w, n2.w):
                all_edges.append((n1.uid, n2.uid))
            elif (n1.x == n2_x2 or n1_x2 == n2.x
                ) and max_ry1 < min_ry2 and min(n1_y2, n2_y2) - max(n1.y, n2.y
                ) > 0.6 * min(n1.h, n2.h):
                all_edges.append((n1.uid, n2.uid))
    return all_edges


def remap_fields(dct, *include, **mapping):
    """Remap certain fields of a dict by yielding (key, value)."""
    for k, v in dct.iteritems():
        if include and k not in include:
            continue
        yield mapping.get(k, k), v


@staticmethod
def __get_service_url(base_url, service_name):
    """Get the URI for a given StackInABoxService.

        Note: this is an internal function

        :param base_url: base URL to use
        :param service_name: name of the service the URI is for

        """
    return '{0}/{1}'.format(base_url, service_name)


def delete(resource_id: str) ->None:
    """
        Delete a copy of a resource from this adapter.
        Delete the corresponding entry in the `copies` table.

        :param r_id - the resource to retrieve's UUID
        """
    pass


def getBLvalues(BLtables, ifList=False):
    """Needs a doc string"""
    if ifList:
        BLvals = []
        for El in BLtables:
            if 'BW-LS' in El:
                BLvals.append(BLtables[El][1]['BW-LS'][0])
            else:
                BLvals.append(BLtables[El][1]['SL'][0])
    else:
        BLvals = {}
        for El in BLtables:
            if 'BW-LS' in El:
                BLvals[El] = BLtables[El][1]['BW-LS'][0]
            else:
                BLvals[El] = BLtables[El][1]['SL'][0]
    return BLvals


def is_requirement(line):
    """
    Return True if the requirement line is a package requirement;
    that is, it is not blank, a comment, or editable.
    """
    line = line.strip()
    return not (line == '' or line.startswith('-r') or line.startswith('#') or
        line.startswith('-e') or line.startswith('git+'))


def available_gpu(*args, **kwargs):
    """This function is an alias for ``GPUtil.getAvailable``. If
    ``GPUtil`` is not installed, it returns 0 as a default GPU ID."""
    return 0


@classmethod
def __toString(cls, lst):
    """ converts list to string

        :param lst: given list
        :type lst: :obj:`list` <:obj:`str`>
        :returns: list in string representation
        :rtype: :obj:`str`
        """
    res = []
    for it in lst:
        res.append(it or '*')
    return str(res)


@staticmethod
def p_if_data_frame_parameter_optional_list(p):
    """if_data_frame_optional_list : if_data_frame_optional
                                       | if_data_frame_optional if_data_frame_optional_list"""
    try:
        p[0] = [p[1]] + p[2]
    except IndexError:
        p[0] = [p[1]]


@classmethod
def green(cls, s):
    """Wrap text in green."""
    return cls._wrap_colour(s, cls.GREEN)


def calculate_motif_distribution(eventgraph, normalize=True):
    """
    Calculate the motif distribution of an event graph

    Input:
        eventgraph (EventGraph):
        normalize (bool): [default=True]

    Returns:
        motifs (pd.Series):
    """
    return eventgraph.eg_edges.motif.value_counts(normalize=normalize)


def first(iterable, default=None, key=None):
    """
    Return first element of `iterable` that evaluates true, else return None
    (or an optional default value).

    >>> first([0, False, None, [], (), 42])
    42

    >>> first([0, False, None, [], ()]) is None
    True

    >>> first([0, False, None, [], ()], default='ohai')
    'ohai'

    >>> import re
    >>> m = first(re.match(regex, 'abc') for regex in ['b.*', 'a(.*)'])
    >>> m.group(1)
    'bc'

    The optional `key` argument specifies a one-argument predicate function
    like that used for `filter()`.  The `key` argument, if supplied, must be
    in keyword form.  For example:

    >>> first([1, 1, 3, 4, 5], key=lambda x: x % 2 == 0)
    4

    """
    if key is None:
        for el in iterable:
            if el:
                return el
    else:
        for el in iterable:
            if key(el):
                return el
    return default


def group_by(keyfunc, iterable):
    """Returns a dict of the elements from given iterable keyed by result
    of keyfunc on each element. The value at each key will be a list of
    the corresponding elements, in the order they appeared in the iterable.
    """
    grouped = {}
    for item in iterable:
        grouped.setdefault(keyfunc(item), []).append(item)
    return grouped


def SPIN(val):
    """SummaryForPatients"""
    return val


def fill_clusters(clusters, element_i, element_j):
    """
    Fill the list of clusters (sets) with two elements from the same cluster.

    >>> clusters = []
    >>> fill_clusters(clusters, 1, 10)
    [{1, 10}]
    >>> fill_clusters(clusters, 10, 100)
    [{1, 10, 100}]
    >>> fill_clusters(clusters, 20, 30)
    [{1, 10, 100}, {20, 30}]
    """
    if not clusters:
        clusters.append({element_i, element_j})
    else:
        found = False
        for cluster in clusters:
            if element_i in cluster:
                cluster.add(element_j)
                found = True
            elif element_j in cluster:
                cluster.add(element_i)
                found = True
        if not found:
            clusters.append({element_i, element_j})
    return clusters


def calc_centered_grid(cols_list, hpad=0.05, vpad=0.05):
    """Calculates a centered grid of Rectangles and their positions.

    Parameters
    ----------
    cols_list : [int]
        List of ints. Every entry represents a row with as many channels
        as the value.
    hpad : float, optional
        The amount of horizontal padding (default: 0.05).
    vpad : float, optional
        The amount of vertical padding (default: 0.05).

    Returns
    -------
    [[float, float, float, float]]
        A list of all rectangle positions in the form of [xi, xy, width,
        height] sorted from top left to bottom right.

    Examples
    --------
    Calculates a centered grid with 3 rows of 4, 3 and 2 columns

    >>> calc_centered_grid([4, 3, 2])

    Calculates a centered grid with more padding

    >>> calc_centered_grid([5, 4], hpad=.1, vpad=.75)
    """
    h = (1 - (len(cols_list) + 1) * vpad) / len(cols_list)
    w = (1 - (max(cols_list) + 1) * hpad) / max(cols_list)
    grid = []
    row = 1
    for l in cols_list:
        yi = 1 - (row * vpad + row * h)
        for i in range(l):
            m = 0.5 - (l * w + (l - 1) * hpad) / 2
            xi = m + i * hpad + i * w
            grid.append([xi, yi, w, h])
        row += 1
    return grid


def update_query(tablename, objects, condition):
    """
    Function to process the query for update process
    """
    if isinstance(tablename, str):
        pass
    else:
        raise ValueError('Tablename should be a String')
    if condition == None or isinstance(condition, str):
        pass
    else:
        raise ValueError('Condition can only be either None or String')
    if isinstance(objects, dict):
        pass
    else:
        raise ValueError(
            'Object argument must be Dictionary in format {column name : Value}'
            )
    cols = ''
    for i in objects.keys():
        if isinstance(objects[i], str):
            substr = str(i) + " = '" + str(objects[i]) + "',"
        else:
            substr = str(i) + ' = ' + str(objects[i]) + ','
        cols = cols + substr
    cols = cols[:len(cols) - 1]
    if condition == None:
        query = 'Update ' + tablename + ' set ' + cols
    else:
        query = 'Update ' + tablename + ' set ' + cols + ' where ' + condition
    return query


def ec2_instance_test_id(ec2_instance):
    """A getter fn for test ids for EC2 instances"""
    return '{0[InstanceId]}'.format(ec2_instance)


@classmethod
def get_table_names(cls, inspector, schema):
    """Need to disregard the schema for Sqlite"""
    return sorted(inspector.get_table_names())


def extrude(forked: bool=False):
    """Create new bones from the selected joints

    :param forked: Forked
    :type forked: bool
    """
    pass


def _compute_params(t):
    """
    Takes a timeseries and computes the parameters needed for the fast
    lomb scargle algorithm in gatspy
    """
    t_min, t_max, n = t[0], t[-1], len(t)
    dt = (t_max - t_min) / float(n - 1)
    min_freq = 1.0 / (t_max - t_min)
    d_freq = 1.0 / (2 * dt * len(t))
    return min_freq, d_freq, len(t)


def is_data(data):
    """Return ``True`` if passed object is Data and ``False`` otherwise."""
    return type(data).__name__ == 'Data'


def time_slice(G, t_from, t_to=None):
    """Return an iterator for (node, degree) at time t.

                The node degree is the number of edges adjacent to the node.

                Parameters
                ----------

                G : graph
                    A DyNetx graph.

                t_from : snapshot id, mandatory

                t_to : snapshot id, optional (default=None)
                    If None t_to will be set equal to t_from

                Returns
                -------
                H : a DynGraph object
                    the graph described by interactions in [t_from, t_to]

                Examples
                --------
                >>> G = dn.DynGraph()
                >>> G.add_path([0,1,2,3], t=0)
                >>> G.add_path([0,4,5,6], t=1)
                >>> G.add_path([7,1,2,3], t=2)
                >>> H = dn.time_slice(G, 0)
                >>> H.edges()
                [(0, 1), (1, 2), (1, 3)]
                >>> H = dn.time_slice(G, 0, 1)
                >>> H.edges()
                [(0, 1), (1, 2), (1, 3), (0, 4), (4, 5), (5, 6)]
            """
    return G.time_slice(t_from, t_to)


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

        :param int val:
        :rtype: AddFolderMemberError
        """
    return cls('too_many_members', val)


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

        :param SharingFileAccessError val:
        :rtype: GetFileMetadataError
        """
    return cls('access_error', val)


def _extraBits(pid):
    """Return everything beyond the 7th digit, i.e. outside the defined numbering scheme."""
    return abs(pid) // 10000000


@classmethod
def get_affected_assets(cls, session, asset_key):
    """Get information about assets affected by a change in parent's state

        Args:
            session: database session
            asset_key(int): key of the updated asset

        Returns:
            tuple: consisting of 3 (optional) items: 1) child assets that are powered by the updated asset
                                                     2) parent(s) of the updated asset
                                                     3) second parent of the child assets
        """
    results = session.run(
        """
            OPTIONAL MATCH  (parentAsset:Asset)<-[:POWERED_BY]-(updatedAsset { key: $key })
            OPTIONAL MATCH (nextAsset:Asset)-[:POWERED_BY]->({ key: $key })
            OPTIONAL MATCH (nextAsset2ndParent)<-[:POWERED_BY]-(nextAsset)
            WHERE updatedAsset.key <> nextAsset2ndParent.key
            RETURN collect(nextAsset) as childAssets, collect(parentAsset) as parentAsset, nextAsset2ndParent
            """
        , key=asset_key)
    list_of_dicts = lambda r: list(map(dict, list(r)))
    record = results.single()
    return list_of_dicts(record['childAssets']) if record['childAssets'
        ] else list(), list_of_dicts(record['parentAsset']) if record[
        'parentAsset'] else list(), dict(record['nextAsset2ndParent']
        ) if record['nextAsset2ndParent'] else None


def ceildiv(dividend, divisor):
    """ integer ceiling division """
    return (dividend + divisor - 1) // divisor


def evaluate_PDF(rv, x=4):
    """Input: a random variable object, standard deviation
    output : x and y values for the normal distribution
    """
    import numpy as np
    import scipy.stats as stats
    import scipy
    mean = rv.mean()
    std = rv.std()
    xs = np.linspace(mean - x * std, mean + x * std, 100)
    ys = rv.pdf(xs)
    return xs, ys


def validate_args(args_d):
    """
  Validate that the user has passed in required arguments
  """
    if not args_d or not args_d.get('input_glob'):
        raise Exception(
            """Please provide an input_glob argument to get_embeddings
      e.g. get_embeddings({input_glob: "cropped/data/*.jpg"})"""
            )


def quarter_count(lst):
    """
	count number of beta values falling into each quarter
	Note: beta >= 0 and beta <=1
	"""
    q1 = 0
    q2 = 0
    q3 = 0
    q4 = 0
    for i in lst:
        try:
            j = float(i)
        except:
            continue
        if not isinstance(j, float):
            continue
        if j < 0:
            continue
        elif j <= 0.25:
            q1 += 1
        elif j <= 0.5:
            q2 += 1
        elif j <= 0.75:
            q3 += 1
        elif j <= 1:
            q4 += 1
        else:
            continue
    return [q1, q2, q3, q4]


def get_text_sparsity(bbox, mentions):
    """
    computes text area coverage
    :param mentions:
    :return:
    """
    b = bbox[-4:]
    bbox_area = (b[2] - b[0]) * (b[3] - b[1])
    text_area = 0
    for m in mentions:
        text_area += (m.x1 - m.x0) * (m.y1 - m.y0)
    try:
        return 1.0 * text_area / bbox_area
    except ZeroDivisionError:
        return 0.0


def first(l):
    """Return the first item of a list, or None if it's empty"""
    return l[0] if l else None


@classmethod
def DeregisterHelper(cls, analyzer_helper):
    """Deregisters a format analyzer helper.

    Args:
      analyzer_helper (AnalyzerHelper): analyzer helper.

    Raises:
      KeyError: if analyzer helper object is not set for the corresponding
          type indicator.
    """
    if analyzer_helper.type_indicator not in cls._analyzer_helpers:
        raise KeyError(
            'Analyzer helper object not set for type indicator: {0:s}.'.
            format(analyzer_helper.type_indicator))
    analyzer_helper = cls._analyzer_helpers[analyzer_helper.type_indicator]
    cls._FlushCache(analyzer_helper.format_categories)
    del cls._analyzer_helpers[analyzer_helper.type_indicator]


def comment():
    """Convert selected text to comment

    """
    pass


@staticmethod
def reorder_genes(x, genes, first_genes):
    """
        In case the order of the genes needs to be changed:
        puts the gene present in ordered_genes first, conserving
        the same order.
        """
    new_order_first = []
    for ordered_gene in range(len(first_genes)):
        for gene in range(len(genes)):
            if first_genes[ordered_gene].lower() == genes[gene].lower():
                new_order_first.append(gene)
    new_order_second = [x for x in range(len(genes)) if x not in
        new_order_first]
    new_order = new_order_first + new_order_second
    return x[:, (new_order)], genes[new_order]


def update_project(name=None, description=None, source=None, artifacts=None,
    environment=None, serviceRole=None, timeoutInMinutes=None,
    encryptionKey=None, tags=None):
    """
    Changes the settings of a build project.
    See also: AWS API Documentation

    :example: response = client.update_project(
        name='string',
        description='string',
        source={
            'type': 'CODECOMMIT'|'CODEPIPELINE'|'GITHUB'|'S3',
            'location': 'string',
            'buildspec': 'string',
            'auth': {
                'type': 'OAUTH',
                'resource': 'string'
            }
        },
        artifacts={
            'type': 'CODEPIPELINE'|'S3'|'NO_ARTIFACTS',
            'location': 'string',
            'path': 'string',
            'namespaceType': 'NONE'|'BUILD_ID',
            'name': 'string',
            'packaging': 'NONE'|'ZIP'
        },
        environment={
            'type': 'LINUX_CONTAINER',
            'image': 'string',
            'computeType': 'BUILD_GENERAL1_SMALL'|'BUILD_GENERAL1_MEDIUM'|'BUILD_GENERAL1_LARGE',
            'environmentVariables': [
                {
                    'name': 'string',
                    'value': 'string'
                },
            ]
        },
        serviceRole='string',
        timeoutInMinutes=123,
        encryptionKey='string',
        tags=[
            {
                'key': 'string',
                'value': 'string'
            },
        ]
    )

    :type name: string
    :param name: [REQUIRED]
            The name of the build project.
            Note
            You cannot change a build project's name.

    :type description: string
    :param description: A new or replacement description of the build project.

    :type source: dict
    :param source: Information to be changed about the build input source code for the build project.
            type (string) -- [REQUIRED]The type of repository that contains the source code to be built. Valid values include:
            CODECOMMIT : The source code is in an AWS CodeCommit repository.
            CODEPIPELINE : The source code settings are specified in the source action of a pipeline in AWS CodePipeline.
            GITHUB : The source code is in a GitHub repository.
            S3 : The source code is in an Amazon Simple Storage Service (Amazon S3) input bucket.
            location (string) --Information about the location of the source code to be built. Valid values include:
            For source code settings that are specified in the source action of a pipeline in AWS CodePipeline, location should not be specified. If it is specified, AWS CodePipeline will ignore it. This is because AWS CodePipeline uses the settings in a pipeline's source action instead of this value.
            For source code in an AWS CodeCommit repository, the HTTPS clone URL to the repository that contains the source code and the build spec (for example, ``https://git-codecommit.*region-ID* .amazonaws.com/v1/repos/repo-name `` ).
            For source code in an Amazon Simple Storage Service (Amazon S3) input bucket, the path to the ZIP file that contains the source code (for example, `` bucket-name /path /to /object-name .zip`` )
            For source code in a GitHub repository, the HTTPS clone URL to the repository that contains the source and the build spec. Also, you must connect your AWS account to your GitHub account. To do this, use the AWS CodeBuild console to begin creating a build project, and follow the on-screen instructions to complete the connection. (After you have connected to your GitHub account, you do not need to finish creating the build project, and you may then leave the AWS CodeBuild console.) To instruct AWS CodeBuild to then use this connection, in the source object, set the auth object's type value to OAUTH .
            buildspec (string) --The build spec declaration to use for the builds in this build project.
            If this value is not specified, a build spec must be included along with the source code to be built.
            auth (dict) --Information about the authorization settings for AWS CodeBuild to access the source code to be built.
            This information is for the AWS CodeBuild console's use only. Your code should not get or set this information directly (unless the build project's source type value is GITHUB ).
            type (string) -- [REQUIRED]The authorization type to use. The only valid value is OAUTH , which represents the OAuth authorization type.
            resource (string) --The resource value that applies to the specified authorization type.

    :type artifacts: dict
    :param artifacts: Information to be changed about the build output artifacts for the build project.
            type (string) -- [REQUIRED]The type of build output artifact. Valid values include:
            CODEPIPELINE : The build project will have build output generated through AWS CodePipeline.
            NO_ARTIFACTS : The build project will not produce any build output.
            S3 : The build project will store build output in Amazon Simple Storage Service (Amazon S3).
            location (string) --Information about the build output artifact location, as follows:
            If type is set to CODEPIPELINE , then AWS CodePipeline will ignore this value if specified. This is because AWS CodePipeline manages its build output locations instead of AWS CodeBuild.
            If type is set to NO_ARTIFACTS , then this value will be ignored if specified, because no build output will be produced.
            If type is set to S3 , this is the name of the output bucket.
            path (string) --Along with namespaceType and name , the pattern that AWS CodeBuild will use to name and store the output artifact, as follows:
            If type is set to CODEPIPELINE , then AWS CodePipeline will ignore this value if specified. This is because AWS CodePipeline manages its build output names instead of AWS CodeBuild.
            If type is set to NO_ARTIFACTS , then this value will be ignored if specified, because no build output will be produced.
            If type is set to S3 , this is the path to the output artifact. If path is not specified, then path will not be used.
            For example, if path is set to MyArtifacts , namespaceType is set to NONE , and name is set to MyArtifact.zip , then the output artifact would be stored in the output bucket at MyArtifacts/MyArtifact.zip .
            namespaceType (string) --Along with path and name , the pattern that AWS CodeBuild will use to determine the name and location to store the output artifact, as follows:
            If type is set to CODEPIPELINE , then AWS CodePipeline will ignore this value if specified. This is because AWS CodePipeline manages its build output names instead of AWS CodeBuild.
            If type is set to NO_ARTIFACTS , then this value will be ignored if specified, because no build output will be produced.
            If type is set to S3 , then valid values include:
            BUILD_ID : Include the build ID in the location of the build output artifact.
            NONE : Do not include the build ID. This is the default if namespaceType is not specified.
            For example, if path is set to MyArtifacts , namespaceType is set to BUILD_ID , and name is set to MyArtifact.zip , then the output artifact would be stored in MyArtifacts/*build-ID* /MyArtifact.zip .
            name (string) --Along with path and namespaceType , the pattern that AWS CodeBuild will use to name and store the output artifact, as follows:
            If type is set to CODEPIPELINE , then AWS CodePipeline will ignore this value if specified. This is because AWS CodePipeline manages its build output names instead of AWS CodeBuild.
            If type is set to NO_ARTIFACTS , then this value will be ignored if specified, because no build output will be produced.
            If type is set to S3 , this is the name of the output artifact object.
            For example, if path is set to MyArtifacts , namespaceType is set to BUILD_ID , and name is set to MyArtifact.zip , then the output artifact would be stored in MyArtifacts/*build-ID* /MyArtifact.zip .
            packaging (string) --The type of build output artifact to create, as follows:
            If type is set to CODEPIPELINE , then AWS CodePipeline will ignore this value if specified. This is because AWS CodePipeline manages its build output artifacts instead of AWS CodeBuild.
            If type is set to NO_ARTIFACTS , then this value will be ignored if specified, because no build output will be produced.
            If type is set to S3 , valid values include:
            NONE : AWS CodeBuild will create in the output bucket a folder containing the build output. This is the default if packaging is not specified.
            ZIP : AWS CodeBuild will create in the output bucket a ZIP file containing the build output.

    :type environment: dict
    :param environment: Information to be changed about the build environment for the build project.
            type (string) -- [REQUIRED]The type of build environment to use for related builds.
            image (string) -- [REQUIRED]The ID of the Docker image to use for this build project.
            computeType (string) -- [REQUIRED]Information about the compute resources the build project will use. Available values include:
            BUILD_GENERAL1_SMALL : Use up to 3 GB memory and 2 vCPUs for builds.
            BUILD_GENERAL1_MEDIUM : Use up to 7 GB memory and 4 vCPUs for builds.
            BUILD_GENERAL1_LARGE : Use up to 15 GB memory and 8 vCPUs for builds.
            environmentVariables (list) --A set of environment variables to make available to builds for this build project.
            (dict) --Information about an environment variable for a build project or a build.
            name (string) -- [REQUIRED]The name or key of the environment variable.
            value (string) -- [REQUIRED]The value of the environment variable.

    :type serviceRole: string
    :param serviceRole: The replacement ARN of the AWS Identity and Access Management (IAM) role that enables AWS CodeBuild to interact with dependent AWS services on behalf of the AWS account.

    :type timeoutInMinutes: integer
    :param timeoutInMinutes: The replacement value in minutes, from 5 to 480 (8 hours), for AWS CodeBuild to wait before timing out any related build that did not get marked as completed.

    :type encryptionKey: string
    :param encryptionKey: The replacement AWS Key Management Service (AWS KMS) customer master key (CMK) to be used for encrypting the build output artifacts.
            You can specify either the CMK's Amazon Resource Name (ARN) or, if available, the CMK's alias (using the format ``alias/alias-name `` ).

    :type tags: list
    :param tags: The replacement set of tags for this build project.
            These tags are available for use by AWS services that support AWS CodeBuild build project tags.
            (dict) --A tag, consisting of a key and a value.
            This tag is available for use by AWS services that support tags in AWS CodeBuild.
            key (string) --The tag's key.
            value (string) --The tag's value.

    :rtype: dict
    :return: {
        'project': {
            'name': 'string',
            'arn': 'string',
            'description': 'string',
            'source': {
                'type': 'CODECOMMIT'|'CODEPIPELINE'|'GITHUB'|'S3',
                'location': 'string',
                'buildspec': 'string',
                'auth': {
                    'type': 'OAUTH',
                    'resource': 'string'
                }
            },
            'artifacts': {
                'type': 'CODEPIPELINE'|'S3'|'NO_ARTIFACTS',
                'location': 'string',
                'path': 'string',
                'namespaceType': 'NONE'|'BUILD_ID',
                'name': 'string',
                'packaging': 'NONE'|'ZIP'
            },
            'environment': {
                'type': 'LINUX_CONTAINER',
                'image': 'string',
                'computeType': 'BUILD_GENERAL1_SMALL'|'BUILD_GENERAL1_MEDIUM'|'BUILD_GENERAL1_LARGE',
                'environmentVariables': [
                    {
                        'name': 'string',
                        'value': 'string'
                    },
                ]
            },
            'serviceRole': 'string',
            'timeoutInMinutes': 123,
            'encryptionKey': 'string',
            'tags': [
                {
                    'key': 'string',
                    'value': 'string'
                },
            ],
            'created': datetime(2015, 1, 1),
            'lastModified': datetime(2015, 1, 1)
        }
    }

    :returns:
    CODECOMMIT : The source code is in an AWS CodeCommit repository.
    CODEPIPELINE : The source code settings are specified in the source action of a pipeline in AWS CodePipeline.
    GITHUB : The source code is in a GitHub repository.
    S3 : The source code is in an Amazon Simple Storage Service (Amazon S3) input bucket.

    """
    pass


def palettecolor_add():
    """Add new Grease Pencil palette color for the active Grease Pencil data-block

    """
    pass


@staticmethod
def _hot_prop_def_from_prop(name, schema):
    """Return a provider template property definition for a property."""
    return {'get_param': name}


@classmethod
def from_dict(cls, data_dict):
    """
		Create a Button object from a string

		:param data_dict:
		:type data_dict: dict

		:return:
		:rtype: Button
		"""
    return cls(**data_dict)


@staticmethod
def parse_revision(string):
    """Parse a revision |string| such as "r300"."""
    if not string.startswith('r'):
        raise ValueError('invalid revision: ' + string)
    string = string[1:]
    return int(string)


def play_rendered_anim():
    """Play back rendered frames/movies using an external player

    """
    pass


def plos_paper_doi(paper):
    """Given a soupified PLOS XML paper, returns that paper's DOI."""
    paper_doi = paper.find('article-id', attrs={'pub-id-type': 'doi'}).text
    return paper_doi


def check_int(_, candidate):
    """Checks whether candidate is <int>."""
    try:
        int(candidate)
        return True
    except:
        return False


def get_vcf_header_lines(top_lines=[], info_dict={}, formats=[], contigs=[],
    samples=[]):
    """ info_dict - values of ('number', 'type', 'description')
        contigs - tuples of (contig, length, assembly)
    """
    header_lines = ['##fileformat=VCFv4.1']
    header_lines.extend(top_lines)
    for info_id, data in info_dict.items():
        data['id'] = info_id
        line_template = (
            '##INFO=<ID=%(id)s,Number=%(number)s,Type=%(type)s,Description="%(description)s">'
            )
        line = line_template % data
        header_lines.append(line)
    use_format = samples and formats
    if use_format:
        header_lines.extend(formats)
    for contig, length, assembly in contigs:
        line = '##contig=<ID=%s,length=%d,assembly=%s>' % (contig, length,
            assembly)
        header_lines.append(line)
    colnames = ['CHROM', 'POS', 'ID', 'REF', 'ALT', 'QUAL', 'FILTER', 'INFO']
    if use_format:
        colnames += ['FORMAT'] + samples
    header_lines.append('#' + '\t'.join(colnames))
    return header_lines


@classmethod
def registerExtraObject(cls, name, jsObject):
    """
        Class method to register extra JavaScript objects.

        @param name name for the object
        @type str
        @param jsObject reference to the JavaScript object to be registered
        @type QObject
        """
    cls.extraObjects[id] = jsObject


def validate_inferred_freq(freq, inferred_freq, freq_infer):
    """
    If the user passes a freq and another freq is inferred from passed data,
    require that they match.

    Parameters
    ----------
    freq : DateOffset or None
    inferred_freq : DateOffset or None
    freq_infer : bool

    Returns
    -------
    freq : DateOffset or None
    freq_infer : bool

    Notes
    -----
    We assume at this point that `maybe_infer_freq` has been called, so
    `freq` is either a DateOffset object or None.
    """
    if inferred_freq is not None:
        if freq is not None and freq != inferred_freq:
            raise ValueError(
                f'Inferred frequency {inferred_freq} from passed values does not conform to passed frequency {freq.freqstr}'
                )
        elif freq is None:
            freq = inferred_freq
        freq_infer = False
    return freq, freq_infer


def check_fulltext(record):
    """
    Checks several fields and returns True, if there is probably a link to fulltext.
    """
    try:
        type = record['024']['2']
    except:
        type = ''
    try:
        urls = record.get_fields('856')
    except:
        urls = ''
    for url in urls:
        description = url.get_subfields('3')
        if (not description or 'kostenfrei' in description or
            'Digitalisierung' in description or 'zugänglich' in description):
            has_fulltext_url = True
            break
    else:
        has_fulltext_url = False
    if urls and has_fulltext_url or urls and (format == 'doi' or format ==
        'urn'):
        return True
    else:
        return False


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 sign(x):
    """Get the sign of a numeric type"""
    if x < 0:
        return -1
    if x > 0:
        return 1
    if x == 0:
        return 0


def outputMarkdown(markdown_cont, output_file):
    """
    Writes to an output file if `outfile` is a valid path.

    """
    if output_file:
        with open(output_file, 'w') as out:
            out.write(markdown_cont)


def autolookup_logger(record, out):
    """
    Write autolookup results to file.

    :param record: The file to log to.
    :type record: str

    :param out: Output block.
    :type out: str
    """
    with open(record, 'a') as rec:
        rec.write('{0}\n'.format(out))


def escape_to_codepoint(match):
    """ Turn escape into codepoint
    """
    hex_codepoint = match.group(1)[1:]
    return chr(int(hex_codepoint, base=16))


def ROOM(model, refflux, reactions=None, delta=0, tol=0, IncZeroes=False,
    AsMtx=False, f=None, reset_state=True):
    """ refflux = {reac_name:flux} """
    if reset_state:
        state = model.GetState()
    model.ZeroObjective()
    if not reactions:
        reactions = model.Reactions()
    else:
        reactions = model.GetReactionNames(reactions)
    for reac in reactions:
        lb, ub = model.GetConstraint(reac)
        if reac in refflux:
            val = refflux[reac]
        else:
            val = 0.0
        hival = val + delta * abs(val) + tol
        loval = val - delta * abs(val) - tol
        model.AddMetabolite(reac + '_ROOMVarhi')
        model.SetMetBounds(reac + '_ROOMVarhi', -model.bounds * 2, hival)
        model.AddMetabolite(reac + '_ROOMVarlo')
        model.SetMetBounds(reac + '_ROOMVarlo', loval, model.bounds * 2)
        model.GetReaction(reac).add_metabolites({model.GetMetabolite(reac +
            '_ROOMVarhi'): 1, model.GetMetabolite(reac + '_ROOMVarlo'): 1})
        model.AddReaction(reac + '_ROOMVar', {model.GetMetabolite(reac +
            '_ROOMVarhi'): -(ub - hival), model.GetMetabolite(reac +
            '_ROOMVarlo'): -(lb - loval)}, bounds=(0, 1))
        model.GetReaction(reac + '_ROOMVar').variable_kind = 'integer'
        model.SetObjective({(reac + '_ROOMVar'): 1})
    model.SetObjDirec('Min')
    model.Solve(False)
    model.CleanUpTempVar('_ROOMVar')
    rv = model.GetSol(IncZeroes=IncZeroes, AsMtx=AsMtx, f=f)
    if reset_state:
        model.SetState(state, IncSol=False)
    return rv


def removePolicyFromContentType(content_type, policy):
    """Sets a content type to use a specific policy"""


def F(*args):
    """
    Always returns false
    @sig F :: _ -> Bool
    """
    return False


def change_rate_extractor(change_rates, initial_currency, final_currency):
    """ Function which tests directions of exchange factors and returns the
    appropriate conversion factor.

    Example
    -------
    >>> change_rate_extractor(
    ...     change_rates     = {'EUR/USD': .8771929824561404},
    ...     initial_currency = 'EUR',
    ...     final_currency   = 'USD',
    ... )
    1.14

    >>> change_rate_extractor(
    ...     change_rates     = {'USD/EUR': 1.14},
    ...     initial_currency = 'EUR',
    ...     final_currency   = 'USD',
    ... )
    1.14

    """
    ACR_1 = '%s/%s' % (initial_currency, final_currency)
    ACR_2 = '%s/%s' % (final_currency, initial_currency)
    if ACR_1 in change_rates:
        return pow(change_rates[ACR_1], -1.0)
    if ACR_2 in change_rates:
        return change_rates[ACR_2]


def _string_literal_to_string(string_literal_token):
    """Converts the StringLiteral token to a plain string: get text content,
    removes quote characters, and unescapes it.

    :param string_literal_token: The string literal
    :return:
    """
    token_text = string_literal_token.getText()
    return token_text[1:-1].replace(u"\\'", u"'").replace(u'\\\\', u'\\')


def deserialize_date(string):
    """
    Deserializes string to date.

    :param string: str.
    :type string: str
    :return: date.
    :rtype: date
    """
    try:
        from dateutil.parser import parse
        return parse(string).date()
    except ImportError:
        return string


@classmethod
def delete_option(cls, option):
    """
        deleted browser options from default
        :param str option: for example --verbose
        :return: list[str]
        """
    cls.default_options.remove(option)
    return cls.default_options


def caselessSort(alist):
    """Return a sorted copy of a list. If there are only strings
	in the list, it will not consider case.
	"""
    try:
        return sorted(alist, key=lambda a: (a.lower(), a))
    except TypeError:
        return sorted(alist)


def copy_obj(from_obj, to_obj, check_primary_key=False, check_related=False,
    exclude=[], copy_related_id=False, check_many_to_many=False):
    """
    モデルインスタンスのフィールドの内容をコピーする
    """
    for field in from_obj._meta.fields:
        if field.primary_key and not check_primary_key:
            continue
        if field.remote_field and not check_related:
            continue
        if field.name in exclude:
            continue
        if field.remote_field and copy_related_id:
            v = getattr(from_obj, field.name + '_id')
            setattr(to_obj, field.name + '_id', v)
        else:
            v = getattr(from_obj, field.name)
            setattr(to_obj, field.name, v)
    if check_many_to_many:
        to_obj.save()
        for field in from_obj._meta.many_to_many:
            if field.name in exclude:
                continue
            m1 = getattr(from_obj, field.name)
            m2 = getattr(to_obj, field.name)
            ids1 = list(m1.values_list('id', flat=True))
            ids2 = list(m2.values_list('id', flat=True))
            if len(ids1) == len(ids2) == len(set(ids1 + ids2)):
                continue
            m2.clear()
            m2_model = m2.model
            for obj in m1.all():
                m2.add(m2_model.objects.get(pk=obj.pk))


def join_models(model1, model2):
    """ Concatenate two SDD models. Assumes that both dictionaries do not share keys.
    """
    model = model1.copy()
    model.update(model2)
    return model


def compile(query):
    """Return a function for generating the row id's from the given query."""


def _get_docstring_var_description(var_doc):
    """
    Get a description of argument or return value from docstring.

    Parameters
    ----------
    var_doc : str
        Docstring's part of argument or return value.

    Returns
    -------
    description : str
        Description of argument or return value.
    """
    var_doc = var_doc.rstrip()
    splitted_list = var_doc.split('\n')
    if len(splitted_list) < 2:
        return ''
    description = '\n'.join(splitted_list[1:])
    description = description.rstrip()
    return description


def apply(hub, subs, low):
    """
    Look up the transparetn requisites as defined in state modules and apply
    them to the respective low chunks
    """
    treq = hub.idem.treq.gather(subs, low)
    refs = {}
    for ind, chunk in enumerate(low):
        path = f"{chunk['state']}.{chunk['fun']}"
        if path not in refs:
            refs[path] = []
        if ind not in refs[path]:
            refs[path].append(ind)
    for chunk in low:
        if not chunk['state'] in treq:
            continue
        if not chunk['fun'] in treq[chunk['state']]:
            continue
        rule = treq[chunk['state']][chunk['fun']]
        for req, r_refs in rule.items():
            for ref in r_refs:
                if ref not in refs:
                    continue
                for rind in refs[path]:
                    req_chunk = low[rind]
                    if req not in chunk:
                        chunk[req] = []
                    chunk[req].append({req_chunk['state']: req_chunk['__id__']}
                        )
    return low


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

        :param ShowcaseFileViewDetails val:
        :rtype: EventDetails
        """
    return cls('showcase_file_view_details', val)


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


def break_line_html(text):
    '\n    Helper function to convert text with \n to html with
. This function are \n    used for example on the textarea to add message to be sent by email.\n    \n    @param text:\n    @return: text with
 instead of \n or \r\n\n    '
    return text.replace('\r\n', '
').replace('\n', '
')


def get_roles_and_permissions():
    """Return a sequence of (permission_id, role_id, setting) here.

        The settings are returned as a sequence of permission, role,
        setting tuples.

        If no principal/role assertions have been made here, then the empty
        list is returned.
        """


def atse_delField(schema_id, schema_template, name, RESPONSE=None):
    """ remove a field from the  schema"""


def partition(pred, iterable):
    """Partition an iterable.

    Arguments
    ---------
    pred     : function
               A function that takes an element of the iterable and returns
               a boolen indicating to which partition it belongs
    iterable : iterable

    Returns
    -------
    A two-tuple of lists with the first list containing the elements on which
    the predicate indicated False and the second list containing the elements
    on which the predicate indicated True.

    Note that, unlike the recipe which returns generators, this version
    returns lists.
    """
    pos, neg = [], []
    pos_append, neg_append = pos.append, neg.append
    for elem in iterable:
        if pred(elem):
            pos_append(elem)
        else:
            neg_append(elem)
    return neg, pos


def count_to_read(link_counters):
    """Find the to_read count in the counters returned by a CommunicationLink."""
    for processor in link_counters.values():
        if 'to_read' in processor:
            return processor['to_read']


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 delete():
    """
        Remove the list of groups that are allowed to add content to the tile
        """


def extract_session_details(request_headers, session_header, secret_key):
    """
        a method to extract and validate jwt session token from request headers

    :param request_headers: dictionary with header fields from request
    :param session_header: string with name of session token header key
    :param secret_key: string with secret key to json web token encryption
    :return: dictionary with request details with session details or error coding
    """
    session_details = {'error': '', 'code': 200, 'session': {}}
    if not session_header in request_headers.keys():
        session_details['error'] = '%s is missing.' % session_header
        session_details['code'] = 400
    else:
        import jwt
        session_token = request_headers[session_header]
        try:
            session_details['session'] = jwt.decode(session_token, secret_key)
        except jwt.DecodeError as err:
            session_details['error'] = 'Session token decoding error.'
            session_details['code'] = 400
        except jwt.ExpiredSignatureError as err:
            session_details['error'] = 'Session token has expired.'
            session_details['code'] = 400
        except Exception:
            session_details['error'] = 'Session token is invalid.'
            session_details['code'] = 400
    return session_details


def _extractRawDictCore(this, items, splitItemBy, dict=None):
    """Constructs and sends a :class:`Request <Request>`.

        :param method: method for the new :class:`Request` object.
        :param url: URL for the new :class:`Request` object.
        :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.
        :param data: (optional) Dictionary or list of tuples ``[(key, value)]`` (will be form-encoded), bytes, or file-like object to send in the body of the :class:`Request`.
        :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.
        :type timeout: float or tuple
        :param allow_redirects: (optional) Boolean. Enable/disable GET/OPTIONS/POST/PUT/PATCH/DELETE/HEAD redirection. Defaults to ``True``.
        :type allow_redirects: bool
        :return: :class:`Response <Response>` object
        :rtype: requests.Response

        Usage::

          >>> import NorrisUtils.RawUtil
          >>> rawutil = NorrisUtils.RawUtil.RawUtil()
          >>> rawutil._extractRawDict('asdf=a,adfasf=33as,zcxv=a123')
          <Response [200]>
        """
    try:
        if items == None or items == [] or items == {}:
            return {}
        if dict == None:
            dict = {}
        for kv in items:
            split = kv.split(splitItemBy)
            if len(split) == 2:
                if dict.get(split[0], -1) == -1:
                    dict[split[0].strip()] = split[1].strip()
                else:
                    pass
            else:
                pass
        return dict
    except:
        return dict


def distance_to_end(file_obj):
    """
    For an open file object how far is it to the end

    Parameters
    ------------
    file_obj: open file-like object

    Returns
    ----------
    distance: int, bytes to end of file
    """
    position_current = file_obj.tell()
    file_obj.seek(0, 2)
    position_end = file_obj.tell()
    file_obj.seek(position_current)
    distance = position_end - position_current
    return distance


@classmethod
def from_data(cls, data, filename='', path=None, allow_import=True):
    """Return a new StyleSheet adding Rules and Conditions from a bytes string.

        The ``filename`` argument is used to handle @import rules
        correctly. The ``path`` argument is currently unused. If
        ``allow_import`` is False, the @import atrule is ignored.

        """
    tree = cls.load_from_data(data)
    return cls.from_tree(tree, filename, path, allow_import)


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

    The ".dev0" means dirty.

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


@classmethod
def match_project_from_log_name(cls, log_name):
    """Parses the project from a log resource.

        Args:
          log_name (string): A fully-qualified path representing a log
            resource.

        Returns:
          A string representing the project.
        """
    return cls._LOG_PATH_TEMPLATE.match(log_name).get('project')


def get_sn_fraction(sn_type):
    """Return SN rates for specific types. These are taken from
    https://arxiv.org/pdf/1509.06574.pdf, and are assumed to be fixed
    fractions of the overall SN rate. Acceptable types are:
        SNIIn
        SNIIP
        SNIb
        SNIc
        SNIbc (equal to Ib + Ic)

    :param sn_type: Type of SN
    :return: fraction represented by that subtype
    """
    if sn_type == 'IIn':
        return 0.064
    elif sn_type == 'IIp':
        return 0.52
    elif sn_type == 'Ib':
        return 0.069
    elif sn_type == 'Ic':
        return 0.176
    elif sn_type == 'Ibc':
        return 0.069 + 0.176
    else:
        raise Exception('SN sn_type ' + str(sn_type) + ' not recognised!')


def _base_ordering(base, degree):
    """
    Order `\\{0, 1, ..., n-1\\}` so that base points come first and in order.

    Parameters
    ==========

    ``base`` - the base
    ``degree`` - the degree of the associated permutation group

    Returns
    =======

    A list ``base_ordering`` such that ``base_ordering[point]`` is the
    number of ``point`` in the ordering.

    Examples
    ========

    >>> from sympy.combinatorics.named_groups import SymmetricGroup
    >>> from sympy.combinatorics.util import _base_ordering
    >>> S = SymmetricGroup(4)
    >>> S.schreier_sims()
    >>> _base_ordering(S.base, S.degree)
    [0, 1, 2, 3]

    Notes
    =====

    This is used in backtrack searches, when we define a relation `<<` on
    the underlying set for a permutation group of degree `n`,
    `\\{0, 1, ..., n-1\\}`, so that if `(b_1, b_2, ..., b_k)` is a base we
    have `b_i << b_j` whenever `i<j` and `b_i << a` for all
    `i\\in\\{1,2, ..., k\\}` and `a` is not in the base. The idea is developed
    and applied to backtracking algorithms in [1], pp.108-132. The points
    that are not in the base are taken in increasing order.

    References
    ==========

    .. [1] Holt, D., Eick, B., O'Brien, E.
           "Handbook of computational group theory"

    """
    base_len = len(base)
    ordering = [0] * degree
    for i in range(base_len):
        ordering[base[i]] = i
    current = base_len
    for i in range(degree):
        if i not in base:
            ordering[i] = current
            current += 1
    return ordering


def do_we_have_enough_cookies(cj, class_name):
    """
    Check whether we have all the required cookies
    to authenticate on class.coursera.org.
    """
    domain = 'class.coursera.org'
    path = '/' + class_name
    return cj.get('csrf_token', domain=domain, path=path) is not None


def todo_view(tlist, index):
    """
    View a specific todo of given index
    """
    try:
        print(tlist[index])
    except IndexError:
        print("ERROR: The given index doesn't exist")


def rotation(fontid: int, angle: float):
    """Set the text rotation angle, enable/disable using ROTATION.

    :param fontid: The id of the typeface as returned by blf.load(), for default font use 0.
    :type fontid: int
    :param angle: The angle for text drawing to use.
    :type angle: float
    """
    pass


def RemoveMultiLineCommentsFromRange(lines, begin, end):
    """Clears a range of lines for multi-line comments."""
    for i in range(begin, end):
        lines[i] = '/**/'


@classmethod
def create(cls, client=None, email=None, phone_number=None, legal_name=None,
    **kwargs):
    """Create a user record in API and corresponding User instance.

        Args:
            client (Client): an instance of the API Client
            email (str): user's login email
            password (str): (opt) password (only if users log in via web portal)
            read_only (bool): (opt) False if admin user (default)
            phone_number (str): user's phone number
            legal_name (str): user's legal name
            base_doc (dict): (opt) user's basedocs
            note (str): (opt) note to SynapsePay
            supp_id (str): (opt) supplemental id
            is_business (bool): (opt) False if personal user (default)
            cip_tag (int): (opt) determined by your cip flow (default=1)

        Returns:
            User: a new User instance
        """
    payload = cls.payload_for_create(email, phone_number, legal_name, **kwargs)
    response = client.users.create(payload)
    return cls.from_response(client, response)


def make_batcher(cursor, row_limit):
    """Return an object to be used for batch store operations.

        *row_limit* is the maximum number of rows to queue before
        calling the database.
        """


def _fix_peer_id(peer_id):
    """
    Fixes the peer ID for chats and channels, in case the users
    mix marking the ID with the :tl:`Peer` constructors.
    """
    peer_id = abs(peer_id)
    if str(peer_id).startswith('100'):
        peer_id = str(peer_id)[3:]
    return int(peer_id)


def histogram_lengths(length, name_prefix):
    """Create a histogram of read counts per length."""
    counts = length.value_counts().to_frame(name='readCount')
    counts.index.rename('readLen', inplace=True)
    counts.sort_index(inplace=True)
    counts.to_csv('{}.hist.csv'.format(name_prefix), index=True)


def describe_cluster_security_groups(ClusterSecurityGroupName=None,
    MaxRecords=None, Marker=None, TagKeys=None, TagValues=None):
    """
    Returns information about Amazon Redshift security groups. If the name of a security group is specified, the response will contain only information about only that security group.
    For information about managing security groups, go to Amazon Redshift Cluster Security Groups in the Amazon Redshift Cluster Management Guide .
    If you specify both tag keys and tag values in the same request, Amazon Redshift returns all security groups that match any combination of the specified keys and values. For example, if you have owner and environment for tag keys, and admin and test for tag values, all security groups that have any combination of those values are returned.
    If both tag keys and values are omitted from the request, security groups are returned regardless of whether they have tag keys or values associated with them.
    See also: AWS API Documentation

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

    :type ClusterSecurityGroupName: string
    :param ClusterSecurityGroupName: The name of a cluster security group for which you are requesting details. You can specify either the Marker parameter or a ClusterSecurityGroupName parameter, but not both.
            Example: securitygroup1

    :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 DescribeClusterSecurityGroups 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 ClusterSecurityGroupName 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 cluster security groups that are associated with the specified key or keys. For example, suppose that you have security groups that are tagged with keys called owner and environment . If you specify both of these tag keys in the request, Amazon Redshift returns a response with the security groups 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 cluster security groups that are associated with the specified tag value or values. For example, suppose that you have security groups that are tagged with values called admin and test . If you specify both of these tag values in the request, Amazon Redshift returns a response with the security groups that have either or both of these tag values associated with them.
            (string) --

    :rtype: dict
    :return: {
        'Marker': 'string',
        'ClusterSecurityGroups': [
            {
                'ClusterSecurityGroupName': 'string',
                'Description': 'string',
                'EC2SecurityGroups': [
                    {
                        'Status': 'string',
                        'EC2SecurityGroupName': 'string',
                        'EC2SecurityGroupOwnerId': 'string',
                        'Tags': [
                            {
                                'Key': 'string',
                                'Value': 'string'
                            },
                        ]
                    },
                ],
                'IPRanges': [
                    {
                        'Status': 'string',
                        'CIDRIP': 'string',
                        'Tags': [
                            {
                                'Key': 'string',
                                'Value': 'string'
                            },
                        ]
                    },
                ],
                'Tags': [
                    {
                        'Key': 'string',
                        'Value': 'string'
                    },
                ]
            },
        ]
    }

    """
    pass


def preprocess_git_version_tag(tag: str):
    """Remove a prefix from a version tag."""
    if tag.startswith('ver'):
        return tag[3:]
    if tag.startswith('v'):
        return tag[1:]
    if tag and tag[0] in ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'):
        return tag
    raise ValueError(f'given tag "{tag}" does not appear to be a version tag')


def p_OptionalLong_true(p):
    """OptionalLong : long"""
    p[0] = True