def translate_per_build_anti_features(apps, apks):
    """Grab the anti-features list from the build metadata

    For most Anti-Features, they are really most applicable per-APK,
    not for an app.  An app can fix a vulnerability, add/remove
    tracking, etc.  This reads the 'antifeatures' list from the Build
    entries in the fdroiddata metadata file, then transforms it into
    the 'antiFeatures' list of unique items for the index.

    The field key is all lower case in the metadata file to match the
    rest of the Build fields.  It is 'antiFeatures' camel case in the
    implementation, index, and fdroidclient since it is translated
    from the build 'antifeatures' field, not directly included.

    """
    antiFeatures = dict()
    for packageName, app in apps.items():
        d = dict()
        for build in app['builds']:
            afl = build.get('antifeatures')
            if afl:
                d[int(build.versionCode)] = afl
        if len(d) > 0:
            antiFeatures[packageName] = d
    for apk in apks:
        d = antiFeatures.get(apk['packageName'])
        if d:
            afl = d.get(apk['versionCode'])
            if afl:
                apk['antiFeatures'].update(afl)


def adjust_boxes(line_wave, box_widths, left_edge, right_edge, max_iter=
    1000, adjust_factor=0.35, factor_decrement=3.0, fd_p=0.75):
    """Ajdust given boxes so that they don't overlap.

    Parameters
    ----------
    line_wave: list or array of floats
        Line wave lengths. These are assumed to be the initial y (wave
        length) location of the boxes.
    box_widths: list or array of floats
        Width of box containing labels for each line identification.
    left_edge: float
        Left edge of valid data i.e., wave length minimum.
    right_edge: float
        Right edge of valid data i.e., wave lengths maximum.
    max_iter: int
        Maximum number of iterations to attempt.
    adjust_factor: float
        Gap between boxes are reduced or increased by this factor after
        each iteration.
    factor_decrement: float
        The `adjust_factor` itself if reduced by this factor, after
        certain number of iterations. This is useful for crowded
        regions.
    fd_p: float
        Percentage, given as a fraction between 0 and 1, after which
        adjust_factor must be reduced by a factor of
        `factor_decrement`. Default is set to 0.75.

    Returns
    -------
    wlp, niter, changed: (float, float, float)
        The new y (wave length) location of the text boxes, the number
        of iterations used and a flag to indicated whether any changes to
        the input locations were made or not.

    Notes
    -----
    This is a direct translation of the code in lineid_plot.pro file in
    NASA IDLAstro library.

    Positions are returned either when the boxes no longer overlap or
    when `max_iter` number of iterations are completed. So if there are
    many boxes, there is a possibility that the final box locations
    overlap.

    References
    ----------
    + http://idlastro.gsfc.nasa.gov/ftp/pro/plot/lineid_plot.pro
    + http://idlastro.gsfc.nasa.gov/

    """
    niter = 0
    changed = True
    nlines = len(line_wave)
    wlp = line_wave[:]
    while changed:
        changed = False
        for i in range(nlines):
            if i > 0:
                diff1 = wlp[i] - wlp[i - 1]
                separation1 = (box_widths[i] + box_widths[i - 1]) / 2.0
            else:
                diff1 = wlp[i] - left_edge + box_widths[i] * 1.01
                separation1 = box_widths[i]
            if i < nlines - 2:
                diff2 = wlp[i + 1] - wlp[i]
                separation2 = (box_widths[i] + box_widths[i + 1]) / 2.0
            else:
                diff2 = right_edge + box_widths[i] * 1.01 - wlp[i]
                separation2 = box_widths[i]
            if diff1 < separation1 or diff2 < separation2:
                if wlp[i] == left_edge:
                    diff1 = 0
                if wlp[i] == right_edge:
                    diff2 = 0
                if diff2 > diff1:
                    wlp[i] = wlp[i] + separation2 * adjust_factor
                    wlp[i] = wlp[i] if wlp[i] < right_edge else right_edge
                else:
                    wlp[i] = wlp[i] - separation1 * adjust_factor
                    wlp[i] = wlp[i] if wlp[i] > left_edge else left_edge
                changed = True
            niter += 1
        if niter == max_iter * fd_p:
            adjust_factor /= factor_decrement
        if niter >= max_iter:
            break
    return wlp, changed, niter


def regroup(tuples):
    """Tuples is a list of tuples.
    (0, lol), (1, truc), (0, bra) --> {0 : [lol, bra], 1 : [truc]}"""
    group = dict()
    existing = list()
    for t in tuples:
        if t[0] in existing:
            group[t[0]].append(t[1])
        else:
            existing.append(t[0])
            group[t[0]] = list([t[1]])
    return group


def Byte(value):
    """Encode a single byte"""
    return bytes((value,))


@staticmethod
def p_sub_group_optional_list_optional(p):
    """sub_group_optional_list_optional : empty
                                            | sub_group_optional_list"""
    p[0] = tuple() if p[1] is None else p[1]


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

        :param MicrosoftOfficeAddinChangePolicyType val:
        :rtype: EventType
        """
    return cls('microsoft_office_addin_change_policy', val)


def p_jdfile_empty(p):
    """ jdfile : JDFILE LBRACKET global RBRACKET """
    factory = p.parser.factory
    p[0] = factory.getSceneObj([])
    if p[0] is None:
        p.parser.log.info('[%d]: Unable to create Scene' % p.lexer.lineno)


def get_parents(tech_id, model_config):
    """
    Returns the full inheritance tree from which ``tech`` descends,
    ending with its base technology group.

    To get the base technology group,
    use ``get_parents(...)[-1]``.

    Parameters
    ----------
    tech : str
    model_config : AttrDict

    """
    tech = model_config.techs[tech_id].essentials.parent
    parents = [tech]
    while True:
        tech = model_config.tech_groups[tech].essentials.parent
        if tech is None:
            break
        parents.append(tech)
    return parents


def print_vec(text, a):
    """print the contents of a vector to the console"""
    n = a.shape[0]
    print('%s[ = (' % text, end='')
    for i in range(n):
        s = ' %g, ' % a[i]
        print(s, end='')
    print(')')


def __iter__():
    """Iterate over the file.

        Yields a list for each data row in the file. The values are unicode
        strings or `None`.  Date values are `datetime.date` objects or
        `None`.

        The indexes are the indexes of the corresponding field names in
        `getFieldNames`.

        """


def get_text_tag(tag, name, default):
    """Get the text of an XML tag."""
    if tag is None:
        return default
    t = tag.find(name)
    if t is not None and t.text is not None:
        return t.text
    else:
        return default


def view_ndof():
    """Use a 3D mouse device to pan/zoom the view

    """
    pass


def is_cold(G):
    """
    A Game is cold if it is a number.

    Parameters
    ----------
    G : Game
        The Game of interest.

    Returns
    -------
    cold : bool
        Whether the Game is cold or not.
    """
    return G.is_number


def index(relationship):
    """obtains the token for the relationship and indexes (calls
        IInjection.index_doc)"""


def preBuildStatic(static):
    """
    Called before building (copying to the build folder) a static file.

    :param static: The static file about to be built.
    :returns: None
    """
    pass


def anyToken(theGen):
    """A function that always reads one token.
    This can be used as the last registered function to ensure that the token
    stream is read to completion. The kind returned is None."""
    try:
        next(theGen)
    except StopIteration:
        return 0, None, None
    return 1, None, None


@classmethod
def monoclinic(cls, a, b, c, beta, lattice_type='P'):
    """Factory for hexagonal lattices

        :param a: unit cell length
        :param b: unit cell length
        :param c: unit cell length
        :param beta: unit cell angle
        """
    self = cls(float(a), float(b), float(c), 90, float(beta), 90,
        lattice_type=lattice_type, lattice='monoclinic')
    return self


def values(key=None):
    """Return an iterator over the values in the container.

        If ``None`` is passed as `key`, this method behaves as if no argument
        were passed; exactly as required for ``IContainer.values()``.

        If `key` is in the container, the first value provided by the iterator
        will correspond to that key.  Otherwise, the first value will be for
        the key that would come next if `key` were in the container.
        """


def autopower():
    """
    Wrapper around `power1d`, that generates co-spectral
    statistics and whatnot at **successive lags**.

    Warning
    -------
    Not yet implemented.
    """
    raise NotImplementedError


def subbox_remove(data, box, subbox, key, value):
    """
    remove value from list data[box][subbox][key]
    """
    box = str(box)
    subbox = str(subbox)
    key = str(key)
    data[box] = data.get(box, {})
    data[box][subbox] = data[box].get(subbox, {})
    l = data[box][subbox].get(key, [])
    try:
        l.remove(value)
        data[box][subbox][key] = l
    except ValueError:
        pass


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


@staticmethod
def is_applicable(conf):
    """Return whether this promoter is applicable for given conf"""
    return bool(conf.get('url'))


def delete_documentation_part(restApiId=None, documentationPartId=None):
    """
    See also: AWS API Documentation

    :example: response = client.delete_documentation_part(
        restApiId='string',
        documentationPartId='string'
    )

    :type restApiId: string
    :param restApiId: [REQUIRED]
            [Required] Specifies the identifier of an API of the to-be-deleted documentation part.

    :type documentationPartId: string
    :param documentationPartId: [REQUIRED]
            [Required] The identifier of the to-be-deleted documentation part.

    """
    pass


def _encode_identifier(v: int) ->str:
    """Encode identifer value into base-94 string."""
    assert v > 0, 'identifier codes must be > 0'
    encoded = ''
    while v != 0:
        v -= 1
        encoded += chr(v % 94 + 33)
        v //= 94
    return encoded


@staticmethod
def on_change(changed_buttons):
    """
        This handler is called by `process()` whenever state of any button has
        changed since last `process()` call. `changed_buttons` is a list of
        tuples of changed button names and their states.
        """
    pass


def num_bps(paired_region):
    """Return number of base pairs (=Length) of paired_region

    paired_region -- PairedRegion object
    """
    return paired_region.Length


def insert_offset():
    """Automatically offset nodes on insertion

    """
    pass


def normalize_key(key):
    """ Replaces underscores with hyphens in string keys

    Parameters
    ----------
    key : string, int, or float
        Key to assign.
    """
    if isinstance(key, str):
        key = key.replace('_', '-')
    return key


def get_text_fingerprint(text, hash_meth, encoding='utf-8'):
    """
    Use default hash method to return hash value of a piece of string
    default setting use 'utf-8' encoding.
    """
    m = hash_meth()
    m.update(text.encode(encoding))
    return m.hexdigest()


def weight_set(factor: float=1.0):
    """Set the weight of selected keys

    :param factor: Factor, Interpolation factor between current brush weight, and keys’ weights
    :type factor: float
    """
    pass


@staticmethod
def _find_vfc(phyp_vfc_adpt, vio_pfc_adpt):
    """Finds the matching VIOS vfc adpt for a given PHYP adapter

        :param phyp_vfc_adpt: The raw PhypVirtualFCAdpt object.
        :param vio_pfc_adpt: The raw ViosFCPhysAdpt.
        :return: The matching ViosFCVirtAdpt contained within the physical VIOS
                 adapter.  If one can't be found, None will be returned.
        """
    if vio_pfc_adpt.ports is None:
        return None
    for vfc_adpt in vio_pfc_adpt.ports:
        for wwpn in phyp_vfc_adpt.wwpn_pair:
            if wwpn == vfc_adpt.wwpn:
                return vfc_adpt
    return None


@classmethod
def _Vapor_Enthalpy(cls, T):
    """Auxiliary equation for the specific enthalpy for saturated vapor

        Parameters
        ----------
        T : float
            Temperature, [K]

        Returns
        -------
        h : float
            Saturated vapor enthalpy, [kJ/kg]

        References
        ----------
        IAPWS, Revised Supplementary Release on Saturation Properties of
        Ordinary Water Substance September 1992,
        http://www.iapws.org/relguide/Supp-sat.html, Eq.7
        """
    alfa = cls._alfa_sat(T)
    rho = cls._Vapor_Density(T)
    dpdT = cls._dPdT_sat(T)
    h = alfa + T / rho * dpdT * 1000
    return h


def obtenir_data_inici_i_final(dic):
    """Retorna la data inicial i final del diccionari retornat
       per la funció agrupar_lectures_per_data()
    """
    inici_conjunt = None
    final_conjunt = None
    for keys in dic.keys():
        if not inici_conjunt or inici_conjunt > keys[0]:
            inici_conjunt = keys[0]
        if not final_conjunt or final_conjunt < keys[1]:
            final_conjunt = keys[1]
    return inici_conjunt, final_conjunt


def v_ts(defl, f_ts, dt):
    """This function calculates the virial of the interaction.

    A more detailed description of this quantity is given in:
    San Paulo, Alvaro, and Ricardo García. Phys Rev B 64.19 (2001): 193411.

    Parameters
    ----------
    defl : numpy.ndarray
        tip deflection
    f_ts : numpy.ndarray
        tip-sample interacting force
    dt : float
        simulation timestep

    Returns
    -------
    virial_tip_samp/(dt*len(defl)) : float
        virial of the tip-sample interaction
    """
    virial_tip_samp = 0.0
    for i in range(len(defl)):
        virial_tip_samp = virial_tip_samp + f_ts[i] * defl[i] * dt
    return virial_tip_samp / (dt * len(defl))


def duplicate_particle_system(use_duplicate_settings: bool=False):
    """Duplicate particle system within the active object

    :param use_duplicate_settings: Duplicate Settings, Duplicate settings as well, so the new particle system uses its own settings
    :type use_duplicate_settings: bool
    """
    pass


@staticmethod
def is_major_update():
    """add or change a custom stat"""
    return False


def getAllowedGroupsForEdit():
    """
        This method will return a list of groups that are allowed to edit the
        contents of this tile
        """


def quantity_to_tuple(quantity, unit_str):
    """
    Splits a quantity into a tuple of (value,unit) where unit is FITS complient.

    Useful to write FITS header keywords with units in a comment.

    Parameters
    ----------
    quantity : astropy quantity
        The Astropy quantity to split.
    unit_str: str
        Unit string representation readable by astropy.units (e.g. 'm', 'TeV', ...)

    Returns
    -------
    tuple
        A tuple containing the value and the quantity.
    """
    return quantity.to(unit_str).value, quantity.to(unit_str).unit.to_string(
        format='FITS')


@classmethod
def get_serializer_class(cls):
    """gets the serializer class for the model

        :return: `rest_framework.serializers.Serializer`
        """
    from .serializers import TagSerializer
    return TagSerializer


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


@conf
def fc_add_flags(conf):
    """
	Adds FCFLAGS / LDFLAGS / LINKFLAGS from os.environ to conf.env
	"""
    conf.add_os_flags('FCPPFLAGS', dup=False)
    conf.add_os_flags('FCFLAGS', dup=False)
    conf.add_os_flags('LINKFLAGS', dup=False)
    conf.add_os_flags('LDFLAGS', dup=False)


def _create_project_checkers(checklist_builder, checkers):
    """Create project checkers."""
    if isinstance(checkers, str):
        checkers = [checkers]
    for each_checker in checkers:
        checklist_builder.add_project_checker(each_checker)


@classmethod
def by_id(cls, node=None, id=None):
    """Retrieve a trans record by id and create a Transaction instance from it.

        Args:
            node (BaseNode): the node from which to send funds
            id (str): id of the transaction to retrieve

        Returns:
            Transaction: a Transaction instance corresponding to the record
        """
    response = node.user.client.trans.get(node.user.id, node.id, id)
    return cls.from_response(node, response)


def clamp(lower: int, value: int, upper: int) ->int:
    """ Clamp a value between (inclusive) lower and upper """
    return min(max(value, lower), upper)


@classmethod
def arg_qxform(cls, parser):
    """Add an `~argparse.ArgumentGroup` for Q-transform options
        """
    group = parser.add_argument_group('Q-transform options')
    group.add_argument('--plot', nargs='+', type=float, default=[0.5], help
        ='One or more times to plot')
    group.add_argument('--frange', nargs=2, type=float, help=
        'Frequency range to plot')
    group.add_argument('--qrange', nargs=2, type=float, help='Search Q range')
    group.add_argument('--nowhiten', action='store_true', help=
        'do not whiten input before transform')


def get_lexer(text, lang):
    """Return the Pygments lexer for parsing this sourcecode.

    :Parameters:
        text
            The sourcecode to be lexed for highlighting. This is analysed if
            the language is 'guess'.
        lang
            An abbreviation for the programming langauge of the code. Can be
            any 'name' accepted by Pygments, including 'none' (plain text) or
            'guess' (analyse the passed code for clues).

    :Returns:
        A Pygments lexer.

    """
    from pygments.lexers import get_lexer_by_name, TextLexer, guess_lexer
    if lang == 'guess':
        try:
            return guess_lexer(text)
        except ValueError:
            return None
    elif lang == 'none':
        return TextLexer
    else:
        return get_lexer_by_name(lang)


@classmethod
def delete_one(cls, strategy):
    """Deletes a single item in a table.
        You can perform a conditional delete operation that deletes the item if it exists,
        or if it has an expected attribute value.

        see :ref:`doc_delete_one`

        :return: The deleted item
        """
    cls._schema()
    keys, condition = cls._parse_one_strategy(strategy)
    return cls._delete_one(keys, condition)


def cellular_automaton(n, r=1, boundary='periodic'):
    """
    Creates the adjacency matrix for a 1D cellular automaton, with the given number of cells and neighbourhood
    radius.
    :param n: the number of cells in this automaton
    :param r: the neighbourhood radius
    :param boundary: the boundary condition
    :return: an adjacency matrix describing this cellular automaton
    """
    if n < 3:
        raise Exception('There must be at least 3 cells')
    adjacency_matrix = [[(0.0) for j in range(n)] for i in range(n)]
    if boundary == 'periodic':
        for w, row in enumerate(adjacency_matrix):
            for c, _ in enumerate(row):
                if w == c:
                    adjacency_matrix[w][c] = 1.0
                    for i in range(r):
                        adjacency_matrix[w][c - (1 + i)] = 1.0
                        adjacency_matrix[w][(c + (1 + i)) % len(
                            adjacency_matrix[w])] = 1.0
    else:
        raise Exception('unsupported boundary condition: %s' % boundary)
    return adjacency_matrix


def standardize_snps(G):
    """
    Standardize variantes.

    Parameters
    ----------
    G : (`n_inds`, `n_snps`) array
        Genetic data

    Returns
    -------
    G_out : standardized array
    """
    mean = G.mean(0)
    std = G.std(0)
    return (G - mean) / std


def overlay_proportion(row, df, overlay_field, overlay_category):
    """
        calculate the fraction of area covered by an overlay. input df is a
        GeoDataFrame resulting from an intersection of two mutlipolygon data sets.
        """
    ov_frac = 0
    study_area_df = df.loc[df['idx1'] == row.name]
    study_area = study_area_df.geometry.area.sum()
    if study_area > 0:
        overlay_df = study_area_df.loc[study_area_df[overlay_field] ==
            overlay_category]
        overlay_area = overlay_df.geometry.area.sum()
        ov_frac = overlay_area / study_area
    return ov_frac


def unpack_hyperopt_vals(vals):
    """
    Unpack values from a hyperopt return dictionary where values are wrapped in a list.
    :param vals: dict
    :return: dict
        copy of the dictionary with unpacked values
    """
    assert isinstance(vals, dict), 'Parameter must be given as dict.'
    ret = {}
    for k, v in list(vals.items()):
        try:
            ret[k] = v[0]
        except (TypeError, IndexError):
            ret[k] = v
    return ret


def create_receipt_rule(RuleSetName=None, After=None, Rule=None):
    """
    Creates a receipt rule.
    For information about setting up receipt rules, see the Amazon SES Developer Guide .
    This action is throttled at one request per second.
    See also: AWS API Documentation

    Examples
    The following example creates a new receipt rule:
    Expected Output:

    :example: response = client.create_receipt_rule(
        RuleSetName='string',
        After='string',
        Rule={
            'Name': 'string',
            'Enabled': True|False,
            'TlsPolicy': 'Require'|'Optional',
            'Recipients': [
                'string',
            ],
            'Actions': [
                {
                    'S3Action': {
                        'TopicArn': 'string',
                        'BucketName': 'string',
                        'ObjectKeyPrefix': 'string',
                        'KmsKeyArn': 'string'
                    },
                    'BounceAction': {
                        'TopicArn': 'string',
                        'SmtpReplyCode': 'string',
                        'StatusCode': 'string',
                        'Message': 'string',
                        'Sender': 'string'
                    },
                    'WorkmailAction': {
                        'TopicArn': 'string',
                        'OrganizationArn': 'string'
                    },
                    'LambdaAction': {
                        'TopicArn': 'string',
                        'FunctionArn': 'string',
                        'InvocationType': 'Event'|'RequestResponse'
                    },
                    'StopAction': {
                        'Scope': 'RuleSet',
                        'TopicArn': 'string'
                    },
                    'AddHeaderAction': {
                        'HeaderName': 'string',
                        'HeaderValue': 'string'
                    },
                    'SNSAction': {
                        'TopicArn': 'string',
                        'Encoding': 'UTF-8'|'Base64'
                    }
                },
            ],
            'ScanEnabled': True|False
        }
    )

    :type RuleSetName: string
    :param RuleSetName: [REQUIRED]
            The name of the rule set to which to add the rule.

    :type After: string
    :param After: The name of an existing rule after which the new rule will be placed. If this parameter is null, the new rule will be inserted at the beginning of the rule list.

    :type Rule: dict
    :param Rule: [REQUIRED]
            A data structure that contains the specified rule's name, actions, recipients, domains, enabled status, scan status, and TLS policy.
            Name (string) -- [REQUIRED]The name of the receipt rule. The name must:
            Contain only ASCII letters (a-z, A-Z), numbers (0-9), periods (.), underscores (_), or dashes (-).
            Start and end with a letter or number.
            Contain less than 64 characters.
            Enabled (boolean) --If true , the receipt rule is active. The default value is false .
            TlsPolicy (string) --Specifies whether Amazon SES should require that incoming email is delivered over a connection encrypted with Transport Layer Security (TLS). If this parameter is set to Require , Amazon SES will bounce emails that are not received over TLS. The default is Optional .
            Recipients (list) --The recipient domains and email addresses to which the receipt rule applies. If this field is not specified, this rule will match all recipients under all verified domains.
            (string) --
            Actions (list) --An ordered list of actions to perform on messages that match at least one of the recipient email addresses or domains specified in the receipt rule.
            (dict) --An action that Amazon SES can take when it receives an email on behalf of one or more email addresses or domains that you own. An instance of this data type can represent only one action.
            For information about setting up receipt rules, see the Amazon SES Developer Guide .
            S3Action (dict) --Saves the received message to an Amazon Simple Storage Service (Amazon S3) bucket and, optionally, publishes a notification to Amazon SNS.
            TopicArn (string) --The ARN of the Amazon SNS topic to notify when the message is saved to the Amazon S3 bucket. An example of an Amazon SNS topic ARN is arn:aws:sns:us-west-2:123456789012:MyTopic . For more information about Amazon SNS topics, see the Amazon SNS Developer Guide .
            BucketName (string) -- [REQUIRED]The name of the Amazon S3 bucket to which to save the received email.
            ObjectKeyPrefix (string) --The key prefix of the Amazon S3 bucket. The key prefix is similar to a directory name that enables you to store similar data under the same directory in a bucket.
            KmsKeyArn (string) --The customer master key that Amazon SES should use to encrypt your emails before saving them to the Amazon S3 bucket. You can use the default master key or a custom master key you created in AWS KMS as follows:
            To use the default master key, provide an ARN in the form of arn:aws:kms:REGION:ACCOUNT-ID-WITHOUT-HYPHENS:alias/aws/ses . For example, if your AWS account ID is 123456789012 and you want to use the default master key in the US West (Oregon) region, the ARN of the default master key would be arn:aws:kms:us-west-2:123456789012:alias/aws/ses . If you use the default master key, you don't need to perform any extra steps to give Amazon SES permission to use the key.
            To use a custom master key you created in AWS KMS, provide the ARN of the master key and ensure that you add a statement to your key's policy to give Amazon SES permission to use it. For more information about giving permissions, see the Amazon SES Developer Guide .
            For more information about key policies, see the AWS KMS Developer Guide . If you do not specify a master key, Amazon SES will not encrypt your emails.
            Warning
            Your mail is encrypted by Amazon SES using the Amazon S3 encryption client before the mail is submitted to Amazon S3 for storage. It is not encrypted using Amazon S3 server-side encryption. This means that you must use the Amazon S3 encryption client to decrypt the email after retrieving it from Amazon S3, as the service has no access to use your AWS KMS keys for decryption. This encryption client is currently available with the AWS Java SDK and AWS Ruby SDK only. For more information about client-side encryption using AWS KMS master keys, see the Amazon S3 Developer Guide .

            BounceAction (dict) --Rejects the received email by returning a bounce response to the sender and, optionally, publishes a notification to Amazon Simple Notification Service (Amazon SNS).
            TopicArn (string) --The Amazon Resource Name (ARN) of the Amazon SNS topic to notify when the bounce action is taken. An example of an Amazon SNS topic ARN is arn:aws:sns:us-west-2:123456789012:MyTopic . For more information about Amazon SNS topics, see the Amazon SNS Developer Guide .
            SmtpReplyCode (string) -- [REQUIRED]The SMTP reply code, as defined by RFC 5321 .
            StatusCode (string) --The SMTP enhanced status code, as defined by RFC 3463 .
            Message (string) -- [REQUIRED]Human-readable text to include in the bounce message.
            Sender (string) -- [REQUIRED]The email address of the sender of the bounced email. This is the address from which the bounce message will be sent.
            WorkmailAction (dict) --Calls Amazon WorkMail and, optionally, publishes a notification to Amazon SNS.
            TopicArn (string) --The Amazon Resource Name (ARN) of the Amazon SNS topic to notify when the WorkMail action is called. An example of an Amazon SNS topic ARN is arn:aws:sns:us-west-2:123456789012:MyTopic . For more information about Amazon SNS topics, see the Amazon SNS Developer Guide .
            OrganizationArn (string) -- [REQUIRED]The ARN of the Amazon WorkMail organization. An example of an Amazon WorkMail organization ARN is arn:aws:workmail:us-west-2:123456789012:organization/m-68755160c4cb4e29a2b2f8fb58f359d7 . For information about Amazon WorkMail organizations, see the Amazon WorkMail Administrator Guide .
            LambdaAction (dict) --Calls an AWS Lambda function, and optionally, publishes a notification to Amazon SNS.
            TopicArn (string) --The Amazon Resource Name (ARN) of the Amazon SNS topic to notify when the Lambda action is taken. An example of an Amazon SNS topic ARN is arn:aws:sns:us-west-2:123456789012:MyTopic . For more information about Amazon SNS topics, see the Amazon SNS Developer Guide .
            FunctionArn (string) -- [REQUIRED]The Amazon Resource Name (ARN) of the AWS Lambda function. An example of an AWS Lambda function ARN is arn:aws:lambda:us-west-2:account-id:function:MyFunction . For more information about AWS Lambda, see the AWS Lambda Developer Guide .
            InvocationType (string) --The invocation type of the AWS Lambda function. An invocation type of RequestResponse means that the execution of the function will immediately result in a response, and a value of Event means that the function will be invoked asynchronously. The default value is Event . For information about AWS Lambda invocation types, see the AWS Lambda Developer Guide .
            Warning
            There is a 30-second timeout on RequestResponse invocations. You should use Event invocation in most cases. Use RequestResponse only when you want to make a mail flow decision, such as whether to stop the receipt rule or the receipt rule set.

            StopAction (dict) --Terminates the evaluation of the receipt rule set and optionally publishes a notification to Amazon SNS.
            Scope (string) -- [REQUIRED]The scope to which the Stop action applies. That is, what is being stopped.
            TopicArn (string) --The Amazon Resource Name (ARN) of the Amazon SNS topic to notify when the stop action is taken. An example of an Amazon SNS topic ARN is arn:aws:sns:us-west-2:123456789012:MyTopic . For more information about Amazon SNS topics, see the Amazon SNS Developer Guide .
            AddHeaderAction (dict) --Adds a header to the received email.
            HeaderName (string) -- [REQUIRED]The name of the header to add. Must be between 1 and 50 characters, inclusive, and consist of alphanumeric (a-z, A-Z, 0-9) characters and dashes only.
            HeaderValue (string) -- [REQUIRED]Must be less than 2048 characters, and must not contain newline characters ('r' or 'n').
            SNSAction (dict) --Publishes the email content within a notification to Amazon SNS.
            TopicArn (string) -- [REQUIRED]The Amazon Resource Name (ARN) of the Amazon SNS topic to notify. An example of an Amazon SNS topic ARN is arn:aws:sns:us-west-2:123456789012:MyTopic . For more information about Amazon SNS topics, see the Amazon SNS Developer Guide .
            Encoding (string) --The encoding to use for the email within the Amazon SNS notification. UTF-8 is easier to use, but may not preserve all special characters when a message was encoded with a different encoding format. Base64 preserves all special characters. The default value is UTF-8.

            ScanEnabled (boolean) --If true , then messages to which this receipt rule applies are scanned for spam and viruses. The default value is false .

    :rtype: dict
    :return: {}

    """
    pass


def size16(parent=None, new_value=None, **kwargs):
    """
    Size getter for rsa key data where the byte size
    of the integer is (parent.parent.bitlen + 15) // 16
    (the + 15 is to round up to the nearest multiple of 16)

    We dont want to have this be a setter since bitlen
    is used by more than one attribute and while it may
    work for some bigints, it may be too small for others.
    """
    if new_value is None:
        return (parent.parent.bitlen + 15) // 16


def intersect(f, g):
    """Return the intersection of two FSTs

    Both arguments are assumed to be length preserving mappings.
    """
    res = f.copy()
    res.conjunct(g)
    res.minimize()
    return res


def gpusValidate(gpuList, checkSingleGPU=False):
    """
    Validate a gpu list
    """
    if checkSingleGPU and len(gpuList) > 1:
        return ['This protocol can only be run on a single GPU.']
    return []


def generate_to_cover(q, covered_intervals):
    """
    Returns a sorted list {k | 0 <=k < q, [k, (k+1)] is uncovered}
    from coverd_intervals which is a list of componenents.

    EXAMPLES::

        sage: from cutgeneratingfunctionology.igp import *
        sage: covered_intervals = [set([0,2]), set([3,4])]
        sage: generate_to_cover(5, covered_intervals)
        [1]
    """
    to_cover = set(range(q))
    for component in covered_intervals:
        to_cover -= component
    return sorted(list(to_cover))


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

        :param TeamMemberInfo val:
        :rtype: MemberAddResult
        """
    return cls('success', val)


def ceil(attrs, inputs, proto_obj):
    """ Calculate ceil value for input """
    return 'ceil', attrs, inputs


@classmethod
def delete_recorder(cls, client, recorder_id):
    """returns true or raises exception.

        param: recorder_id: number id for a recorder.
            e.g. recorder_id = 2 (corresponding channel_id is 'm2')
        """
    return cls.delete_channel(client, 'm%s' % recorder_id)


def zap_all():
    """
        Remove the cache from disk.
        """


def eps(net_income, preferred_dividends, shares_outstanding):
    """Computes basic earnings per share.

    @params
    -------
    net_income: net income
    preferred_dividends: preferred dividends
    shares_outstanding: weighted average number of ordinary shares outstanding

    returns
    -------
    Earnings per share, int or float

    explanation
    -----------

    """
    return (net_income - preferred_dividends) / shares_outstanding


def with_metaclass(meta, *bases):
    """Create a base class with a metaclass."""
    return meta('NewBase', bases, {})


def test_mulaw():
    """
    basic consistency check:

        >>> codes = range(0, 256)
        >>> all(mulaw.encode(mulaw.decode(codes)) == codes)
        True
    """


def Dot2(a, b):
    """Return the dot product of two 2d vectors, a . b."""
    return a[0] * b[0] + a[1] * b[1]


@classmethod
def dynamallow_validate(cls, obj):
    """
        Given a dictionary representing a blob from dynamo, this method will validate the blob
        given the desired validation library.

        Returns a dictionary representing the sanitized input ``obj``. On validation failure,
        this should raise ``dynamallow.exc.ValidationError``.
        """
    raise NotImplementedError('{0} class must implement dynamallow_validate'
        .format(cls.__name__))


@staticmethod
def _uniquefy_tuples(tuples):
    """Remove redundant tuples.

        :param tuples: list of string of tuples.
        :return: list of string of unique tuples.
        """
    unique_tuples = []
    for tupl in tuples:
        if tupl not in unique_tuples and tupl[0].upper() != 'MEASURES':
            unique_tuples.append(tupl)
    return unique_tuples


def get_api_access_token(handler_input):
    """Return the api access token in the request.

    The method retrieves the ``apiAccessToken`` from the input request,
    which has the encapsulated information of permissions granted by the
    user. This token can be used to call Alexa-specific APIs. More information
    about this can be found here :
    https://developer.amazon.com/docs/custom-skills/request-and-response-json-reference.html#system-object

    The SDK already includes this token in the API calls done through the
    `service_client_factory` in
    :py:class:`ask_sdk_core.handler_input.HandlerInput`.

    :param handler_input: The handler input instance that is generally
        passed in the sdk's request and exception components
    :type handler_input: ask_sdk_core.handler_input.HandlerInput
    :return: Api access token from the input request, which encapsulates any
        permissions consented by the user
    :rtype: str
    """
    return handler_input.request_envelope.context.system.api_access_token


def _polymorph(cls, dct):
    """Just create a proper instance for this dct."""
    if '_id' not in dct or '/' not in dct['_id']:
        raise TypeError('Cannot infer document type!', dct)
    collection, _ = dct['_id'].split('/')
    if collection not in cls.__documents__:
        raise TypeError('Unknown document type!', collection)
    return cls.__documents__[collection](dct)


@classmethod
def create_by_request(cls, request, exception):
    """
        Create error to request

        :param request: request
        :type request: messages.IncomingRequest
        :param exception: exception to send
        :type exception: Exception
        :return: response object
        :rtype: messages.Response
        """
    headers = {'correlation_id': request.correlation_id, 'request_id':
        request.request_id, 'source': str(request.destination),
        'destination': str(request.reply_to or request.source), 'reply_to': ''}
    request_headers = request.headers.copy()
    request_headers.update(headers)
    return cls(request_headers, request.context, exception)


def expo(d: int, n: int) ->int:
    """greatest exponent for a divisor of n

    :param d: divisor
    :type d: int
    :param n: number be divided
    :type n: int
    :returns: number of times a divisor divides n
    :rtype: int

    .. doctest:: python

        >>> expo(100, 2)
        2
        >>> expo(12, 5)
        0
        >>> expo(12, 2)
        2
        >>> expo(160, 4)
        2
        >>> expo(1000, 4)
        1

    """
    if n < d:
        d, n = n, d
    c = n
    divs = 0
    while c % d == 0:
        c //= d
        divs += 1
    return divs


@classmethod
def get_kami(cls, section_number, puzzle_number, check_valid=False):
    """
        Get a puzzle based on the section and puzzle numbers.

        :param section_number: Section of puzzle.
        :param puzzle_number: Number of puzzle in section.
        :param check_valid: Check whether the puzzle is valid before returning.
        :return: New puzzle.
        """
    puzzle_filename = f'kami-{section_number}-{puzzle_number}.json'
    puzzle = cls._load_puzzle_by_filename(puzzle_filename)
    if check_valid:
        puzzle._check_valid()
    return puzzle


def get(obj):
    """
        Get a single object.

        :param IObject obj: A description of which object to get.  The *kind*,
            *namespace*, and *name* address the specific object to retrieve.

        :return Deferred(IObject): A description of the retrieved object.
        """


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

    The ".dev0" means dirty.

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


def askopenfilename(**kwargs):
    """Return file name(s) from Tkinter's file open dialog."""
    try:
        from Tkinter import Tk
        import tkFileDialog as filedialog
    except ImportError:
        from tkinter import Tk, filedialog
    root = Tk()
    root.withdraw()
    root.update()
    filenames = filedialog.askopenfilename(**kwargs)
    root.destroy()
    return filenames


def gather(jobs):
    """Aggregate and collect jobs"""
    for job in jobs:
        for r in job:
            yield r


def User(request):
    """
    Restore user session based on active Session.

    Add `request.user` as LazyUser to fetch used data
    from database only when we access to `request.user`
    first time.
    """
    pass


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


def inner_plaintext_parser(func):
    """
    mark a method as plaintext parser
    """
    func.__plaintext_parser__ = True
    return func


@classmethod
def header_constructor(cls, data_to_print, header_separator='-',
    column_separator=' '):
    """
        Construct header of the table according to template.

        :param list data_to_print:
            The list of data to print into the header of the table.

        :param str header_separator:
            The separator to use between the table header and our data.

        :param str colomn_separator: The separator to use between each colomns.

        :return: The data to print in a list format.
        :rtype: list
        """
    header_data = []
    header_size = ''
    before_size = '%-'
    after_size = 's'
    if header_separator:
        header_separator_data = []
    length_data_to_print = len(data_to_print) - 1
    i = 0
    for data in data_to_print:
        size = data_to_print[data]
        header_data.append(data)
        header_size += before_size + str(size) + after_size
        if i < length_data_to_print:
            header_size += column_separator
        if header_separator:
            header_separator_data.append(header_separator * size)
        i += 1
    if header_separator:
        return [header_size % tuple(header_data), header_size % tuple(
            header_separator_data)]
    return [header_size % tuple(header_data)]


@staticmethod
def _get_item(list_containing_dicts_entries, attribute_value,
    attribute_name='subnet_id'):
    """Searches a list of dicts and returns the first matching entry

        The dict entry returned contains the attribute 'attribute_name' whose
        value equals 'attribute_value'. If no such dict is found in the list
        an empty dict is returned.
        """
    for item in list_containing_dicts_entries:
        if item.get(attribute_name) == attribute_value:
            return item
    return {}


def parse_toc(html_content):
    """
    Parse TOC of HTML content if the SHOW_TOC config is true.

    :param html_content: raw HTML content
    :return: tuple(processed HTML, toc list, toc HTML unordered list)
    """
    from flask import current_app
    from veripress.model.toc import HtmlTocParser
    if current_app.config['SHOW_TOC']:
        toc_parser = HtmlTocParser()
        toc_parser.feed(html_content)
        toc_html = toc_parser.toc_html(depth=current_app.config['TOC_DEPTH'
            ], lowest_level=current_app.config['TOC_LOWEST_LEVEL'])
        toc = toc_parser.toc(depth=current_app.config['TOC_DEPTH'],
            lowest_level=current_app.config['TOC_LOWEST_LEVEL'])
        return toc_parser.html, toc, toc_html
    else:
        return html_content, None, None


@classmethod
def from_comp(cls, xx=0, xy=0, xz=0, yy=0, yz=0, zz=0):
    """
        Return ``Stress`` tensor. Default is zero tensor.

        Note that stress tensor must be symmetrical.

        Keyword Args:
          xx, xy, xz, yy, yz, zz (float): tensor components

        Example:
          >>> S = Stress.from_comp(xx=-5, yy=-2, zz=10, xy=1)
          >>> S
          Stress:
          [[-5  1  0]
           [ 1 -2  0]
           [ 0  0 10]]

        """
    return cls([[xx, xy, xz], [xy, yy, yz], [xz, yz, zz]])


@classmethod
def set_base_url(cls, base_url):
    """Load the base url and its derived urls."""
    cls.base_url = base_url
    cls.base_url_protocol = base_url.split(':')[0]
    cls.base_url_domain = cls.domain(base_url)


def did_lose_device(interactive_name, logger, app_shutdown_token):
    """
    Handles the disappearance of a device by displaying
    a message.
    """
    if not app_shutdown_token.is_set():
        logger.warn('Oh no {} disappeared'.format(interactive_name))


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


def get_feature_names():
    """
	feature names for the fixed peptide length feature vectors
	"""
    aminos = ['A', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'M', 'N', 'P',
        'Q', 'R', 'S', 'T', 'V', 'W', 'Y']
    names = []
    for a in aminos:
        names.append('Ib_' + a)
    names.append('sumIbaG')
    names.append('meanIbwikiG')
    names.append('sumIywaG')
    names.append('meanIywikiG')
    names += ['pmz', 'peplen', 'ionnumber', 'ionnumber_rel']
    for c in ['aG', 'wikiG', 'mz', 'bas', 'heli', 'hydro', 'pI']:
        names.append('sum_' + c)
    for c in ['mz', 'bas', 'heli', 'hydro', 'pI']:
        names.append('mean_' + c)
    for c in ['max_{}', 'min_{}', 'max{}_b', 'min{}_b', 'max{}_y', 'min{}_y']:
        for b in ['bas', 'heli', 'hydro', 'pI']:
            names.append(c.format(b))
    names.append('mz_ion')
    names.append('mz_ion_other')
    names.append('mean_mz_ion')
    names.append('mean_mz_ion_other')
    for c in ['bas', 'heli', 'hydro', 'pI']:
        names.append('{}_ion'.format(c))
        names.append('{}_ion_other'.format(c))
        names.append('{}_ion_minus_ion_other'.format(c))
    for c in ['plus_cleave{}', 'times_cleave{}', 'minus1_cleave{}',
        'minus2_cleave{}', 'bsum{}', 'ysum{}']:
        for b in ['bas', 'heli', 'hydro', 'pI']:
            names.append(c.format(b))
    for pos in ['0', '1', '-2', '-1']:
        for c in ['mz', 'bas', 'heli', 'hydro', 'pI', 'wikiG', 'P', 'D',
            'E', 'K', 'R']:
            names.append('loc_' + pos + '_' + c)
    for pos in ['i', 'i+1']:
        for c in ['wikiG', 'P', 'D', 'E', 'K', 'R']:
            names.append('loc_' + pos + '_' + c)
    for c in ['bas', 'heli', 'hydro', 'pI', 'mz']:
        for pos in ['i', 'i-1', 'i+1', 'i+2']:
            names.append('loc_' + pos + '_' + c)
    names.append('charge')
    return names


def build_option_parser(parser):
    """Hook to add global options"""
    return parser


def discharge_coefficient_to_K(D, Do, C):
    """Converts a discharge coefficient to a standard loss coefficient,
    for use in computation of the actual pressure drop of an orifice or other
    device.

    .. math::
        K = \\left[\\frac{\\sqrt{1-\\beta^4(1-C^2)}}{C\\beta^2} - 1\\right]^2

    Parameters
    ----------
    D : float
        Upstream internal pipe diameter, [m]
    Do : float
        Diameter of orifice at flow conditions, [m]
    C : float
        Coefficient of discharge of the orifice, [-]

    Returns
    -------
    K : float
        Loss coefficient with respect to the velocity and density of the fluid
        just upstream of the orifice, [-]

    Notes
    -----
    If expansibility is used in the orifice calculation, the result will not
    match with the specified pressure drop formula in [1]_; it can almost
    be matched by dividing the calculated mass flow by the expansibility factor
    and using that mass flow with the loss coefficient.

    Examples
    --------
    >>> discharge_coefficient_to_K(D=0.07366, Do=0.05, C=0.61512)
    5.2314291729754

    References
    ----------
    .. [1] American Society of Mechanical Engineers. Mfc-3M-2004 Measurement
       Of Fluid Flow In Pipes Using Orifice, Nozzle, And Venturi. ASME, 2001.
    .. [2] ISO 5167-2:2003 - Measurement of Fluid Flow by Means of Pressure
       Differential Devices Inserted in Circular Cross-Section Conduits Running
       Full -- Part 2: Orifice Plates.
    """
    beta = Do / D
    beta2 = beta * beta
    beta4 = beta2 * beta2
    root_K = (1.0 - beta4 * (1.0 - C * C)) ** 0.5 / (C * beta2) - 1.0
    return root_K * root_K


def iterate(str_or_list):
    """
    Check is the given value is a string or list
    Returns values one by one as if it were a list
    """
    if type(str_or_list) == str:
        if not len(str_or_list.strip()):
            return StopIteration
        yield str_or_list
    elif type(str_or_list) == list:
        for _ in str_or_list:
            yield _
    else:
        raise TypeError(f'"{str_or_list}" is not a string or list')


def _sync_pretty_list(iterable, sep, to_s):
    """
    The actuall pretty list function.
    """
    return sep.join(map(to_s, iterable))


def batch_length():
    """Returns the number of available index in the batch.
        """


def flat_map(iterable, func):
    """func must take an item and return an interable that contains that
    item. this is flatmap in the classic mode"""
    results = []
    for element in iterable:
        result = func(element)
        if len(result) > 0:
            results.extend(result)
    return results


def cdsitem(sizeInGB, mediumType):
    """
    :param sizeInGB: sizeInGB
    :type string
    :param mediumType: mediumType
    :type string ssd, sata, premium_ssd
    :return: cds
    """
    cds = {'sizeInGB': sizeInGB, 'mediumType': mediumType}
    return cds


@staticmethod
def get_quality(input_vector=None, control_params=None):
    """Return quality of stage."""
    raise NotImplementedError


def fix_pyext(mod_path):
    """
    Fix a module filename path extension to always end with the
    modules source file (i.e. strip compiled/optimized .pyc, .pyo
    extension and replace it with .py).

    """
    if mod_path[-4:] in ['.pyo', 'pyc']:
        mod_path = mod_path[:-1]
    return mod_path


def copy_file(stream, target, maxread=-1, buffer_size=2 * 16):
    """ Read from :stream and write to :target until :maxread or EOF. """
    size, read = 0, stream.read
    while 1:
        to_read = buffer_size if maxread < 0 else min(buffer_size, maxread -
            size)
        part = read(to_read)
        if not part:
            return size
        target.write(part)
        size += len(part)


def separate_configs_by_pv(config_lines):
    """
    Take in a pre-parsed pragma such as::

        [{'title': 'pv', 'tag': 'a'},
         {'title': 'io', 'tag': 'io_for_a'},
         {'title': 'pv', 'tag': 'b'},
         {'title': 'io', 'tag': 'io_for_a'},
         ]

    Which was generated from::

        pv: a
        io: io_for_a
        pv: b
        io: io_for_b

    And yield the following::

        ('a', [{'title': 'io', 'tag': 'io_for_a'}])
        ('b', [{'title': 'io', 'tag': 'io_for_b'}])
    """
    pv, config = None, None
    for line in config_lines:
        if line['title'] == 'pv':
            if config is not None:
                yield pv, config
            pv = line['tag']
            config = []
        if config is not None:
            config.append(line)
    if config is not None:
        yield pv, config


def UInt32(value):
    """Encode a 32-bit integer value"""
    return value.to_bytes(4, 'big')


def main():
    """
    Command-line interface.
    """
    import sys
    from gitsweep.cli import CommandLine
    CommandLine(sys.argv).run()


def scan_setup_py():
    """Validate the contents of setup.py against Versioneer's expectations."""
    found = set()
    setters = False
    errors = 0
    with open('setup.py', 'r') as f:
        for line in f.readlines():
            if 'import versioneer' in line:
                found.add('import')
            if 'versioneer.get_cmdclass()' in line:
                found.add('cmdclass')
            if 'versioneer.get_version()' in line:
                found.add('get_version')
            if 'versioneer.VCS' in line:
                setters = True
            if 'versioneer.versionfile_source' in line:
                setters = True
    if len(found) != 3:
        print('')
        print('Your setup.py appears to be missing some important items')
        print('(but I might be wrong). Please make sure it has something')
        print('roughly like the following:')
        print('')
        print(' import versioneer')
        print(' setup( version=versioneer.get_version(),')
        print('        cmdclass=versioneer.get_cmdclass(),  ...)')
        print('')
        errors += 1
    if setters:
        print("You should remove lines like 'versioneer.VCS = ' and")
        print("'versioneer.versionfile_source = ' . This configuration")
        print('now lives in setup.cfg, and should be removed from setup.py')
        print('')
        errors += 1
    return errors


def swap_1d(perm, i, j):
    """
    Swap two elements of a 1-D numpy array in-place.

    Parameters
    ----------
    parm : ndarray
    i : int
    j : int

    Examples
    --------
    >>> perm = np.array([2, 1, 2, 3, 4, 5, 6])
    >>> swap_1d(perm, 2, 6)
    array([2, 1, 6, 3, 4, 5, 2])
    """
    perm[i], perm[j] = perm[j], perm[i]
    return perm


def get_range(offset=None, limit=None, limit_default=None):
    """
    Converts offset/limit params to slice object

    For example, following two expressions are identical:
        some_list[get_range(offset=10, limit=5)]
        some_list[10:15]
    """
    start = offset or 0
    limit = limit or limit_default
    stop = limit and start + limit
    return slice(start, stop)


def _remove_html_comment_tags(html):
    """
    Returns the passed HTML contents with all comment tags removed while
    keeping the contents within the tags.

    Some pages embed the HTML contents in comments. Since the HTML contents are
    valid, removing the content tags (but not the actual code within the
    comments) will return the desired contents.

    Parameters
    ----------
    html : PyQuery object
        A PyQuery object which contains the requested HTML page contents.

    Returns
    -------
    string
        The passed HTML contents with all comment tags removed.
    """
    return str(html).replace('<!--', '').replace('-->', '')


def generar_buckets(tipos, cantidades):
    """
    Genera de elementos repetidos según la lista de nombres de los elementos y
    la lista con las cantidades para cada uno
    :param tipos: lista con nombres de los elementos
    :param cantidades: lista de cantidad para cada nombre
    :return: lista de elementos repetidos
    """
    contador = 0
    acumulador = []
    for cantidad in cantidades:
        acumulador += [tipos[contador]] * cantidad
        contador += 1
    return acumulador


def remove_parameters(url):
    """Remove query parameters from a URL.

    This function looks for a '?' and removes it, together with everything that
    comes after. It also removes the trailing slash in order to keep things
    clean.
    """
    pos = url.find('?')
    if pos > -1:
        url = url[:pos]
    if url[-1] == '/':
        url = url[:-1]
    return url


def _loop_wx(app):
    """Inner-loop for running the Wx eventloop

    Pulled from guisupport.start_event_loop in IPython < 5.2,
    since IPython 5.2 only checks `get_ipython().active_eventloop` is defined,
    rather than if the eventloop is actually running.
    """
    app._in_event_loop = True
    app.MainLoop()
    app._in_event_loop = False


def array_reshape_conv1d(x):
    """Reshapes regulard 2d array for Conv1D layer

    x : numpy array
        A 2-d numpy array to be respahed.
    """
    out = x.reshape(x.shape[0], x.shape[1], 1)
    return out


@classmethod
def get_parameter_names(cls):
    """ Get the names of the parameters of the model

        :rtype: list(str)
        """
    return cls.default_parameters.keys()


@classmethod
def clean_key(cls, key):
    """
        Replace things that look like variables with a '#' so tests aren't
        affected by random variables
        """
    for var_re in cls.VARIABLE_RES:
        key = var_re.sub('#', key)
    return key


def random_node_presence(t_windows, rep, plac, dur):
    """
    Generate the occurrence and the presence of a node given occurrence_law(occurrence_param)
    and presence_law(presence_param).

    :param t_windows: Time window of the Stream Graph
    :param rep: Number of segmented nodes
    :param plac: Emplacement of each segmented node (sorted array)
    :param dur: Length of each interval corresponding to a segmented node
    :return: node presence
    """
    acc = plac[0] + dur[0]
    if acc > t_windows[1]:
        acc = t_windows[1]
        n_presence = [plac[0], acc]
        return n_presence
    n_presence = [plac[0], acc]
    for i in range(1, rep):
        acc = plac[i] + dur[i]
        if acc > t_windows[1]:
            acc = t_windows[1]
        if acc <= n_presence[-1]:
            continue
        if plac[i] <= n_presence[-1]:
            n_presence[-1] = acc
        else:
            n_presence += [plac[i], acc]
    return n_presence


def is_subdir(path, directory):
    """
    Returns true if *path* in a subdirectory of *directory*.
    """
    import os
    from os.path import normpath, normcase, sep
    path = normpath(normcase(path))
    directory = normpath(normcase(directory))
    if len(path) > len(directory):
        sep = sep.encode('ascii') if isinstance(directory, bytes) else sep
        if path.startswith(directory.rstrip(sep) + sep):
            return True
    return False


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

        :param SsoChangeSamlIdentityModeDetails val:
        :rtype: EventDetails
        """
    return cls('sso_change_saml_identity_mode_details', val)


def unauthed_report_predicate_inv(context, request):
    """
    This allows the user to access the view if context object public
    flag is NOT True
    """
    if context.public:
        return False
    return True


def enable_stage_transition(pipelineName=None, stageName=None,
    transitionType=None):
    """
    Enables artifacts in a pipeline to transition to a stage in a pipeline.
    See also: AWS API Documentation

    :example: response = client.enable_stage_transition(
        pipelineName='string',
        stageName='string',
        transitionType='Inbound'|'Outbound'
    )

    :type pipelineName: string
    :param pipelineName: [REQUIRED]
            The name of the pipeline in which you want to enable the flow of artifacts from one stage to another.

    :type stageName: string
    :param stageName: [REQUIRED]
            The name of the stage where you want to enable the transition of artifacts, either into the stage (inbound) or from that stage to the next stage (outbound).

    :type transitionType: string
    :param transitionType: [REQUIRED]
            Specifies whether artifacts will be allowed to enter the stage and be processed by the actions in that stage (inbound) or whether already-processed artifacts will be allowed to transition to the next stage (outbound).

    """
    pass


def generate_dashboard_link(uuid: str) ->str:
    """Generate a MythX dashboard link for an analysis job.

    This method will generate a link to an analysis job on the official
    MythX dashboard production setup. Custom deployment locations are currently
    not supported by this function (but available at mythx.io).
    :param uuid: The analysis job's UUID
    :return: The analysis job's dashboard link
    """
    return 'https://dashboard.mythx.io/#/console/analyses/{}'.format(uuid)


def cancel():
    """Cancel loading of selected file

    """
    pass


def __expectString(val):
    """Raises standard Exception message if passed value is not a string"""
    if type(val) != str:
        raise Exception('Expected string, received {}'.format(type(val)))


def move_articles_to_front(sName):
    """Moves articles from the end back to the start as is expected
       in the database.

       Reverses move_articles_to_back.
       Used when importing from various formats."""
    if sName.lower().endswith(', the'):
        sName = 'The ' + sName[:-5]
    elif sName.lower().endswith(', an'):
        sName = 'An ' + sName[:-4]
    elif sName.lower().endswith(', a'):
        sName = 'A ' + sName[:-3]
    return sName


def new(cls, value):
    """
        Initializes a new boolean instance

        Value must be one of the true/false labels or else a True/False literal
        """
    cls.validate(value)
    if value == True or value == cls.trueValue:
        return int.__new__(cls, True)
    elif value == False or value == cls.falseValue:
        return int.__new__(cls, False)
    else:
        raise ValueError('Invalid Bool value: %r' % value)


def default_filter(src, dst):
    """The default progress/filter callback; returns True for all files"""
    return dst


def write_fasta(read_id, sequence, fd):
    """
    Write a read into a fastq format
    """
    fd.write('>%s\n' % read_id)
    fd.write('%s\n' % sequence)


def equals(s1, s2):
    """Equals 2 string parameters is true or false

    :param s1:
    :param s2:
    :return:
    """
    return s2 is None if s1 is None else s1 == s2


@staticmethod
def ring_list_to_json_bbox(bbox):
    """If a bbox has been returned without all the trimmings, as in the case of
        the cloud func microservices we add some extra structure and return it.
        """
    tmp = [[bbox[0], bbox[1]], [bbox[0], bbox[3]], [bbox[2], bbox[3]], [
        bbox[2], bbox[1]], [bbox[0], bbox[1]]]
    return {'geometry': {'coordinates': tmp, 'type': 'Polygon'}}


@classmethod
def from_raw_data(cls, raw_data):
    """Create a new model using raw API response."""
    content = cls.process_raw_data(raw_data)
    return cls(**content)


@classmethod
def _clean_attr(cls):
    """Overwrite cause Meta is mandatory."""
    attributs = super()._clean_attr()
    if 'Meta' not in attributs:
        raise NotImplementedError(
            'You must define a Meta with a model attribut!')
    else:
        attributs.remove('Meta')
    return attributs


def _idivup(a, b):
    """
    return the integer division, plus one if `a` is not a multiple of `b`
    """
    return (a + (b - 1)) // b


def analyse_RmpRiTau_trace(time, soma_voltage, stim_start, stim_end,
    current_amplitude):
    """Analyse the output of the RmpRiTau protocol"""
    import efel
    trace = {}
    trace['T'] = time
    trace['V'] = soma_voltage
    trace['stim_start'] = [stim_start]
    trace['stim_end'] = [stim_end]
    efel_results = efel.getFeatureValues([trace], ['voltage_base',
        'steady_state_voltage_stimend', 'decay_time_constant_after_stim'])
    voltage_base = efel_results[0]['voltage_base'][0]
    ss_voltage = efel_results[0]['steady_state_voltage_stimend'][0]
    dct = efel_results[0]['decay_time_constant_after_stim'][0]
    input_resistance = float(ss_voltage - voltage_base) / current_amplitude
    rmpritau_dict = {}
    rmpritau_dict['Rmp'] = '%.6g' % voltage_base
    rmpritau_dict['Rmp_Units'] = 'mV'
    rmpritau_dict['Rin'] = '%.6g' % input_resistance
    rmpritau_dict['Rin_Units'] = 'MOhm'
    rmpritau_dict['Tau'] = '%.6g' % dct
    rmpritau_dict['Tau_Units'] = 'ms'
    print('Resting membrane potential is %s %s' % (rmpritau_dict['Rmp'],
        rmpritau_dict['Rmp_Units']))
    print('Input resistance is %s %s' % (rmpritau_dict['Rin'],
        rmpritau_dict['Rin_Units']))
    print('Time constant is %s %s' % (rmpritau_dict['Tau'], rmpritau_dict[
        'Tau_Units']))
    import json
    with open('rmp_ri_tau.json', 'w') as rmpritau_json_file:
        json.dump(rmpritau_dict, rmpritau_json_file, sort_keys=True, indent
            =4, separators=(',', ': '))


@classmethod
def build_ixarr(cls, iarr, jarr):
    """
        Build an array of indexes. Each value represent a pair of letters.
        :param iarr: a 1d array representing a string
        :param jarr: a 1d array representing a string
        :return: a 2d array
        """
    iarr = iarr.astype('uint16') << 8
    jarr = jarr.astype('uint16')
    iarr[0] = 0
    jarr[0] = 0
    iarr.shape = -1, 1
    jarr.shape = 1, -1
    return iarr | jarr


def finish(status):
    """Call this when the operation is done, successful or not. The
        Monitor's lifetime is influenced by the completion of the operation
        it is monitoring. The Monitor's 'status' value will be set with the
        'status' argument, just as if it had been passed to set_status().
        This value will be used to fire the Deferreds that are returned by
        when_done().

        Operations that fire a Deferred when they finish should trigger this
        with d.addBoth(monitor.finish)"""


def per_device_batch_size(batch_size, num_gpus):
    """For multi-gpu, batch-size must be a multiple of the number of GPUs.
  Note that this should eventually be handled by DistributionStrategies
  directly. Multi-GPU support is currently experimental, however,
  so doing the work here until that feature is in place.
  Args:
    batch_size: Global batch size to be divided among devices. This should be
      equal to num_gpus times the single-GPU batch_size for multi-gpu training.
    num_gpus: How many GPUs are used with DistributionStrategies.
  Returns:
    Batch size per device.
  Raises:
    ValueError: if batch_size is not divisible by number of devices
  """
    if num_gpus <= 1:
        return batch_size
    remainder = batch_size % num_gpus
    if remainder:
        err = (
            'When running with multiple GPUs, batch size must be a multiple of the number of available GPUs. Found {} GPUs with a batch size of {}; try --batch_size={} instead.'
            .format(num_gpus, batch_size, batch_size - remainder))
        raise ValueError(err)
    return int(batch_size / num_gpus)


def demo(cls):
    """Lance une demo amusante de la classe"""
    from film.demo import demo
    demo()


def close_event(event):
    """
    Closes an event retrieved from psana at LCLS.

    Psana events do not need to be closed, so this function actually does nothing.

    NOTE: This function is designed to be injected as a member function into an
    :class:`~onda.utils.data_event.DataEvent` object.

    Arguments:

        event (:class:`~onda.utils.data_event.DataEvent`): an object storing the event
            data.
    """
    del event


def __getitem__(index):
    """Return item at index in the current batch view.
        """


def remove_column(table, name):
    """Remove a specified columns from a create table."""
    for h in table:
        if table[h]['col'] > table[name]['col']:
            table[h]['col'] -= 1
    del table[name]
    return table


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


@classmethod
def handle_cursor(cls, cursor, query, session):
    """Handle a live cursor between the execute and fetchall calls

        The flow works without this method doing anything, but it allows
        for handling the cursor and updating progress information in the
        query object"""
    pass


@staticmethod
def validate_mime_type(mimetype):
    """Validate the mimetype string."""
    valid_prefixes = ['application', 'audio', 'font', 'example', 'image',
        'message', 'model', 'mulitpart', 'text', 'video']
    validated = False
    for prefix in valid_prefixes:
        if prefix + '/' == mimetype[:len(prefix) + 1]:
            validated = True
    return validated


def handler(func):
    """
    Use this decorator to mark a method on a class as being its jsonweb
    encode handler. It will be called any time your class is serialized to a
    JSON string. ::

        >>> from jsonweb import encode
        >>> @encode.to_object()
        ... class Person(object):
        ...     def __init__(self, first_name, last_name):
        ...         self.first_name = first_name
        ...         self.last_name = last_name
        ...     @encode.handler
        ...     def to_obj(self):
        ...         return {"FirstName": person.first_name,
        ...             "LastName": person.last_name}
        ...
        >>> @encode.to_list()
        ... class People(object):
        ...     def __init__(self, *persons):
        ...         self.persons = persons
        ...     @encode.handler
        ...     def to_list(self):
        ...         return self.persons
        ...
        >>> people = People(
        ...     Person("Luke", "Skywalker"),
        ...     Person("Darth", "Vader"),
        ...     Person("Obi-Wan" "Kenobi")
        ... )
        ...
        >>> print dumper(people, indent=2)
        [
          {
            "FirstName": "Luke",
            "LastName": "Skywalker"
          },
          {
            "FirstName": "Darth",
            "LastName": "Vader"
          },
          {
            "FirstName": "Obi-Wan",
            "LastName": "Kenobi"
          }
        ]

    """
    func._jsonweb_encode_handler = True
    return func


@classmethod
def POST(cls, *n, **kw):
    """Perform a POST request using :meth:`RESTClient.request()`."""
    return cls.IMPL.POST(*n, **kw)


@classmethod
def get_preview_data(cls, request):
    """
        Get the preview data.

        You should use this in the preview view to get the
        data for the preview.

        You normally do not override this. If you want to manage
        serialization yourself, see :meth:`.serialize_preview`.
        """
    serialized = request.session.pop(cls.get_preview_sessionkey())
    return cls.deserialize_preview(serialized)


@classmethod
def get_from_string(cls, msgctxt):
    """
        Looks for the SegmentTranslationContext that the given string represents.
        """
    object_id, path = msgctxt.split(':')
    path_id = cls.get_path_id(path)
    return cls.objects.get(object_id=object_id, path_id=path_id)


def _file_has_previous(planner, resource):
    """Returns true if the task has seen the file before."""
    history = planner.history.get(planner.task.hash, {}).get('inputs', {})
    return resource.ref() in history


def handle_code(code):
    """Handle to just prints the received code."""
    print(code)


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


def convert_data(data):
    """ Helper function to convert data to the right shape. """
    shape = data.shape
    d = len(shape)
    if d == 2:
        m = shape[0]
        n = shape[1]
        data = data.reshape(1, m, n)
    elif d == 3:
        m = shape[1]
        n = shape[2]
    else:
        raise ValueError(
            'Could not bring data with shape {} into right                          form.'
            .format(shape))
    return data, d, m, n


def selectmode_toggle(mode: int=0):
    """Set selection mode for Grease Pencil strokes

    :param mode: Select mode, Select mode
    :type mode: int
    """
    pass


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

    Like 'git describe --tags --dirty --always -long'.
    The distance/hash is unconditional.

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


@classmethod
def factory(cls, *args, **kw):
    """
        A class function which simply calls the constructor. Useful for explicity stating that
        this is a factory.
        All arguments are forwarded to the constructor.
        """
    return cls(*args, **kw)


def bugname(rowhead):
    """make bug names look nicer"""
    if 's__' in rowhead:
        return rowhead.split('.')[1].replace('s__', '').replace('_', ' ')
    elif 'g__' in rowhead:
        return rowhead.replace('g__', '').replace('_', ' ')
    else:
        return rowhead


def find_complete_days(daily_groups):
    """
    Create a dictionary to give trip information summarized for a given day as to
    whether it contains any trips and whether the day is complete (i.e., no missing trips)
    """
    daily_summaries = {}
    for date, group in daily_groups.sorted_by_date():
        if not group.has_trips:
            daily_summaries[date] = {'has_trips': False, 'is_complete': False}
        elif group.contains_missing_trips:
            daily_summaries[date] = {'has_trips': True, 'is_complete': False}
        else:
            daily_summaries[date] = {'has_trips': True, 'is_complete': True}
        daily_summaries[date]['start_point'] = group.start_point
        daily_summaries[date]['end_point'] = group.end_point
    return daily_summaries


def uint256_from_compact(c):
    """Convert compact encoding to uint256

    Used for the nBits compact encoding of the target in the block header.
    """
    nbytes = c >> 24 & 255
    if nbytes <= 3:
        v = (c & 16777215) >> 8 * (3 - nbytes)
    else:
        v = (c & 16777215) << 8 * (nbytes - 3)
    return v


def _layer(ufo, idx):
    """UFO has a global set of layers.

    Each layer then has glyphs. For an N-layer COLR glyph we
    write the glyph into global layers 0..N-1. The UFO will end up with
    as many global layers as the "deepest" glyph.

    The only real significance is z-order so name on that basis.
    """
    name = f'z_{idx}'
    if name not in ufo.layers:
        ufo.newLayer(name)
    return ufo.layers[name]


@staticmethod
def worker(remote, parent_remote, env_fn_wrapper):
    """ A worker process. """
    parent_remote.close()
    env = env_fn_wrapper.env_fn
    while True:
        command, data = remote.recv()
        if command == 'step':
            ob, reward, done, info = env.step(data)
            if done:
                ob = env.reset()
            remote.send((ob, reward, done, info))
        elif command == 'reset':
            ob = env.reset()
            remote.send(ob)
        elif command == 'reset_task':
            ob = env.reset_task()
            remote.send(ob)
        elif command == 'close':
            remote.close()
            break
        elif command == 'get_spaces':
            remote.send((env.observation_space, env.action_space))
        else:
            raise NotImplementedError


def startListening():
    """
        Start listening on this port.

        @raise CannotListenError: If it cannot listen on this port (e.g., it is
                                  a TCP port and it cannot bind to the required
                                  port number).
        """


def pv(cash_flow, period, cost_of_capital):
    """
    Input: cash_flow, year, cost_of_capital
    Output: present value of cash_flow
    """
    return cash_flow / (1.0 + cost_of_capital) ** period


@staticmethod
def get_image_keys():
    """Return an iterable containing all image-keys"""
    return []


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 render_pep440_old(pieces):
    """TAG[.postDISTANCE[.dev0]] .

    The ".dev0" means dirty.

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


def getModule(root, name):
    """Retrieve a specific module from the directory root, bypassing the usual paths"""
    import imp
    fp, pathname, description = imp.find_module(name, [root])
    try:
        return imp.load_module(name, fp, pathname, description)
    finally:
        if fp:
            fp.close()
    return


def reorder_receipt_rule_set(RuleSetName=None, RuleNames=None):
    """
    Reorders the receipt rules within a receipt rule set.
    For information about managing receipt rule sets, see the Amazon SES Developer Guide .
    This action is throttled at one request per second.
    See also: AWS API Documentation

    Examples
    The following example reorders the receipt rules within a receipt rule set:
    Expected Output:

    :example: response = client.reorder_receipt_rule_set(
        RuleSetName='string',
        RuleNames=[
            'string',
        ]
    )

    :type RuleSetName: string
    :param RuleSetName: [REQUIRED]
            The name of the receipt rule set to reorder.

    :type RuleNames: list
    :param RuleNames: [REQUIRED]
            A list of the specified receipt rule set's receipt rules in the order that you want to put them.
            (string) --

    :rtype: dict
    :return: {}

    """
    pass


def getSize():
    """
        Return the size in bytes.
        """


def generate_perfdata_string(value='U', warning='', critical=''):
    """Generate a valid perfdata string based on `value`, `warning` and
    `critical`."""
    perfdata_string = "|'Percentage delayed'=" + str(value) + '%;' + str(
        warning) + ';' + str(critical)
    return perfdata_string


@classmethod
def get(cls, project_id, feature_name):
    """Retrieve a single feature

        Parameters
        ----------
        project_id : str
            The ID of the project the feature is associated with.
        feature_name : str
            The name of the feature to retrieve

        Returns
        -------
        feature : Feature
            The queried instance
        """
    path = cls._build_url(project_id, feature_name)
    return cls.from_location(path)


def convert_lists(varmap, listnames=('classifiers', 'requires', 'provides',
    'obsoletes')):
    """Convert long strings to lists of strings.

    Allows variable names in ``listnames`` to be specified as
    long strings instead of lists, for easier typing. The
    ``license_map`` and ``devstatus_trove`` strings below give
    examples of the kind of long strings that can be used.
    """
    listnames = varmap.get('listnames', listnames)
    for listname in listnames:
        try:
            var = varmap[listname]
        except KeyError:
            pass
        else:
            if isinstance(var, str):
                varmap[listname] = var.strip().splitlines()


def copy_plugins_to(plugin_list, to_placeholder, to_language=None,
    parent_plugin_id=None):
    """
    Copies a list of plugins to a placeholder to a language.
    """
    old_parent_cache = {}
    plugins_ziplist = []
    first = True
    for old_plugin in plugin_list:
        if first:
            old_plugin.parent = None
            old_plugin.parent_id = None
        if to_language:
            plugin_language = to_language
        else:
            plugin_language = old_plugin.language
        new_plugin = old_plugin.copy_plugin(to_placeholder, plugin_language,
            old_parent_cache)
        if first:
            first = False
            if parent_plugin_id:
                from cms.models import CMSPlugin
                if parent_plugin_id:
                    new_plugin.move_to(target=CMSPlugin.objects.get(pk=
                        parent_plugin_id))
        plugins_ziplist.append((new_plugin, old_plugin))
    for new_plugin, old_plugin in plugins_ziplist:
        new_instance = new_plugin.get_plugin_instance()[0]
        if new_instance:
            new_instance.post_copy(old_plugin, plugins_ziplist)
    return plugins_ziplist


def GetTimestamp(header):
    """

    gets the timestamp of when the header was created

    """
    pass


def _get_groups(seq_table, group_by):
    """Return a dictionary of indicate groups of samples

    Args:
        seq_table:
        group_by:

    Returns:

    """
    groups = {}
    if isinstance(group_by, list):
        for ix, group in enumerate(group_by):
            if not isinstance(group, list):
                raise Exception(
                    'Error: if use list, group by should be a 2-D list of sample names'
                    )
            else:
                groups['Set_{}'.format(ix)] = group
    elif isinstance(group_by, dict):
        for group in group_by.values():
            if not isinstance(group, list):
                raise Exception(
                    'Error: if use dict, all values should be a 1-D list of sample names'
                    )
        groups = group_by
    elif isinstance(group_by, str):
        groups = {}
        for sample, content in seq_table.sample_info.items():
            if group_by not in content['metadata'].keys():
                raise Exception('Error: sample {} does not have attribute {}'
                    .format(sample.name, group_by))
            elif content['metadata'][group_by] in groups:
                groups[content['metadata'][group_by]].append(sample)
            else:
                groups[content['metadata'][group_by]] = [sample]
    return groups


def D50():
    """Return D50 illuminant as an (X,Y,Z) triple."""
    return 0.9642, 1.0, 0.8249


def kg_to_lbs(kg):
    """
    Convert kilograms to pounds
    """
    return kg * 2.204623


@classmethod
def info(cls):
    """Display information about API."""
    return cls.call('version.info')


def append_link(link):
    """Add a new chain link to the end of this chain.

        :param link: The chain link to add.
        """


def gravity_wmg(weight, mass):
    """Usage: gravity_wmg(weight of object, mass of object)"""
    return weight / mass


def remove_head_id(ref, hyp):
    """Assumes that the ID is the begin token of the string which is common
    in Kaldi but not in Sphinx."""
    ref_id = ref[0]
    hyp_id = hyp[0]
    if ref_id != hyp_id:
        print(
            """Reference and hypothesis IDs do not match! ref="{}" hyp="{}"
File lines in hyp file should match those in the ref file."""
            .format(ref_id, hyp_id))
        exit(-1)
    ref = ref[1:]
    hyp = hyp[1:]
    return ref, hyp


def private(func):
    """
    Decorator to declare which methods are privately accessible as HTTP
    requests with an ``X-Backend-Allow-Private-Methods: True`` override

    :param func: function to make private
    """
    func.privately_accessible = True
    return func


def check_domain_state(conn, guestname, logger):
    """ if a guest with the same name exists, remove it """
    running_guests = []
    ids = conn.listDomainsID()
    for id in ids:
        obj = conn.lookupByID(id)
        running_guests.append(obj.name())
    if guestname in running_guests:
        logger.info('A guest with the same name %s is running!' % guestname)
        logger.info('destroy it...')
        domobj = conn.lookupByName(guestname)
        domobj.destroy()
    defined_guests = conn.listDefinedDomains()
    if guestname in defined_guests:
        logger.info('undefine the guest with the same name %s' % guestname)
        domobj = conn.lookupByName(guestname)
        domobj.undefine()
    return 0


def update_traffic_policy_instance(Id=None, TTL=None, TrafficPolicyId=None,
    TrafficPolicyVersion=None):
    """
    Updates the resource record sets in a specified hosted zone that were created based on the settings in a specified traffic policy version.
    When you update a traffic policy instance, Amazon Route 53 continues to respond to DNS queries for the root resource record set name (such as example.com) while it replaces one group of resource record sets with another. Amazon Route 53 performs the following operations:
    See also: AWS API Documentation

    :example: response = client.update_traffic_policy_instance(
        Id='string',
        TTL=123,
        TrafficPolicyId='string',
        TrafficPolicyVersion=123
    )

    :type Id: string
    :param Id: [REQUIRED]
            The ID of the traffic policy instance that you want to update.

    :type TTL: integer
    :param TTL: [REQUIRED]
            The TTL that you want Amazon Route 53 to assign to all of the updated resource record sets.

    :type TrafficPolicyId: string
    :param TrafficPolicyId: [REQUIRED]
            The ID of the traffic policy that you want Amazon Route 53 to use to update resource record sets for the specified traffic policy instance.

    :type TrafficPolicyVersion: integer
    :param TrafficPolicyVersion: [REQUIRED]
            The version of the traffic policy that you want Amazon Route 53 to use to update resource record sets for the specified traffic policy instance.

    :rtype: dict
    :return: {
        'TrafficPolicyInstance': {
            'Id': 'string',
            'HostedZoneId': 'string',
            'Name': 'string',
            'TTL': 123,
            'State': 'string',
            'Message': 'string',
            'TrafficPolicyId': 'string',
            'TrafficPolicyVersion': 123,
            'TrafficPolicyType': 'SOA'|'A'|'TXT'|'NS'|'CNAME'|'MX'|'NAPTR'|'PTR'|'SRV'|'SPF'|'AAAA'
        }
    }

    :returns:
    Id (string) -- [REQUIRED]
    The ID of the traffic policy instance that you want to update.

    TTL (integer) -- [REQUIRED]
    The TTL that you want Amazon Route 53 to assign to all of the updated resource record sets.

    TrafficPolicyId (string) -- [REQUIRED]
    The ID of the traffic policy that you want Amazon Route 53 to use to update resource record sets for the specified traffic policy instance.

    TrafficPolicyVersion (integer) -- [REQUIRED]
    The version of the traffic policy that you want Amazon Route 53 to use to update resource record sets for the specified traffic policy instance.

    """
    pass


def within_delta(dt1, dt2, delta):
    """
    Useful for comparing two datetimes that may a negilible difference
    to be considered equal.
    """
    delta = abs(delta)
    difference = dt1 - dt2
    return -delta <= difference <= delta


def pl_true_int_repr(clause, model={}):
    """Lightweight version of pl_true.

    Argument clause represents the set of args of an Or clause. This is used
    inside dpll, it is not meant to be used directly.

    >>> pl_true_int_repr({1, 2}, {1: False})
    >>> pl_true_int_repr({1, 2}, {1: False, 2: False})
    False

    """
    result = False
    for lit in clause:
        if lit < 0:
            p = model.get(-lit)
            if p is not None:
                p = not p
        else:
            p = model.get(lit)
        if p is True:
            return True
        elif p is None:
            result = None
    return result


@classmethod
def delete_auth_token(cls, user_id, token):
    """Deletes a given authorization token.

        :param user_id:
            User unique ID.
        :param token:
            A string with the authorization token.
        """


taqdir-2.1.3//تقدیر/کوائف.pyclass:کوائف/ماہانہ

def ماہانہ(خود):
    """
        ماہانہ کی ظرز پر کوائف ۔

        Returns
        -------
        pd.DataFrame
            کوائف کی ماہانہ اوسط۔
        """
    return خود.اعداد.resample('M').mean()


@classmethod
def p_quoting(cls, p):
    """unary_expression : PHRASE"""
    p[0] = p[1]


def getMixedCaseName(name):
    """
    Return the name of the variable used for exporting - camelCase
    """
    return name


@staticmethod
def getJavaPackage():
    """ Returns package name String. """
    return 'org.apache.spark.ml.PipelineModel'


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

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

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


def __init__(creator, owner, depth=0, timeout='Infinity', locktype='write',
    lockscope='exclusive', token=None):
    """        If any of the  following are untrue, a **ValueError** exception
        will be raised.

         - **creator** MUST be a Zope user object or string to find a
           valid user object.

         - **owner** MUST be a nonempty string, or type that can be converted
           to a nonempty string.

         - **depth** MUST be in the set {0,'infinity'}

         - **timeout** MUST either be an integer, or a string in the form
           of 'Seconds-nnn' where nnn is an integer.  The timeout value
           MUST be less than (2^32)-1.  *IF* timeout is the string value
           'Infinite', the timeout value will be set to 1800 (30 minutes).
           (Timeout is the value in seconds from creation/modification
           time until the lock MAY time out).

         - **locktype** not in set {'write'} *this may expand later*

         - **lockscope** not in set {'exclusive'} *this may expand later*

        If the value passed in to 'token' is 'None', the a new locktoken
        will be generated during the construction process.

        __init__ must generate the opaquelocktoken uri used to identify the
        lock (if 'token' is 'None')and set all of the above attributes on
        the object.
        """


def null_padded(string, length):
    """
    Force a string to a given length by right-padding it with zero-bytes,
    clipping the initial string if neccessary.
    """
    return bytes(string[:length] + '\x00' * (length - len(string)), 'latin1')


def distribute(transport, recipients, event):
    """Distribute the notification event.

        :param transport: the name of a supported transport
        :param recipients: a list of (sid, authenticated, address, format)
                           tuples, where either `sid` or `address` can be
                           `None`
        :param event: a `NotificationEvent`
        """


def do_set_audio(clip, audio):
    """ Set the audio of a video clip.

        clip  - clip in which to set the audio
        audio - audio clip to use as audio
    """
    result = clip.set_audio(audio)
    return result


def format_span(fmt, yearfrom, yearto, fromnchars, tonchars):
    """Return a span string representation.
    """
    args = str(yearfrom)[-fromnchars:]
    if tonchars:
        args = str(yearfrom)[-fromnchars:], str(yearto)[-tonchars:]
    return fmt % args


def getProcessingStatus(identifier):
    """Returns True if user has consented, False if they've objected and None if
        there is no data"""
    NotImplemented


@staticmethod
def sizeTreeEditor(c, editor):
    """Size a QLineEdit in a tree headline so scrolling occurs"""
    space = c.frame.tree.treeWidget.size().width()
    used = editor.geometry().x() + 4
    editor.resize(space - used, editor.size().height())


def gwei_to_ether(wei):
    """
    Convert gwei to ether
    """
    return 1.0 * wei / 10 ** 9


def get_pStyle(p, doc):
    """
    Get the referenced style element for a paragraph with a p.pPr.pStyle
    """
    if p.pPr is not None and p.pPr.pStyle is not None:
        return doc.styles.element.find("w:style[@w:styleId='%s']" % p.pPr.
            pStyle.val, doc.styles.element.nsmap)
    return None


@staticmethod
def read_generics(generics_file):
    """Read generic token set from given file"""
    gen_set = set()
    with open(generics_file) as gen_fd:
        for line in gen_fd:
            if line.startswith('#') or line == '\n':
                continue
            gen_set.add(line.strip())
    return gen_set


def list_team_members(projectId=None, nextToken=None, maxResults=None):
    """
    Lists all team members associated with a project.
    See also: AWS API Documentation

    :example: response = client.list_team_members(
        projectId='string',
        nextToken='string',
        maxResults=123
    )

    :type projectId: string
    :param projectId: [REQUIRED]
            The ID of the project for which you want to list team members.

    :type nextToken: string
    :param nextToken: The continuation token for the next set of results, if the results cannot be returned in one response.

    :type maxResults: integer
    :param maxResults: The maximum number of team members you want returned in a response.

    :rtype: dict
    :return: {
        'teamMembers': [
            {
                'userArn': 'string',
                'projectRole': 'string',
                'remoteAccessAllowed': True|False
            },
        ],
        'nextToken': 'string'
    }

    """
    pass


def ignore_event():
    """
    function that does nothing. it can be used as a handler to ignore events.
    """
    pass


def safe_decode_utf8(s):
    """Safe decode a str from UTF.

    :param s: The str to decode.
    :returns: The decoded str.
    """
    if isinstance(s, bytes):
        return s.decode('utf-8', 'surrogateescape')
    return s


def guess_contains_libcrypt(lines):
    """Tries to determine if a file includes libgcrypt
    """
    for line in lines:
        if 'fork detection failed' in line:
            return 1
        if 'too many random bits requested' in line:
            return 1
        if 'severe error getting random' in line:
            return 1
    return 0


def get_nofile_limit(pid):
    """Returns the NOFILE limit for a given PID

    :param int pid: The PID of the process
    :returns: (*int*) The NOFILE limit
    """
    with open('/proc/%s/limits' % pid, 'r') as f:
        for line in f:
            if line.startswith('Max open files'):
                return int(line.split()[4])
    raise RuntimeError('Could not find "Max open files" limit')


def reverse_key(key):
    """
    Tenant aware function to reverse a cache key.

    Required for django-redis REVERSE_KEY_FUNCTION setting.
    """
    return key.split(':', 3)[3]


def _wrap_impl(f, args, kwargs, task):
    """
    Helper method, needs to be at the top level
    """
    return f(task, *args, **kwargs)


def fastdelta(base, changes):
    """Obtain a delta between this manifest and another given changes.

        ``base`` in the raw data representation for another manifest.

        ``changes`` is an iterable of ``(path, to_delete)``.

        Returns a 2-tuple containing ``bytearray(self.text())`` and the
        delta between ``base`` and this manifest.

        If this manifest implementation can't support ``fastdelta()``,
        raise ``mercurial.manifest.FastdeltaUnavailable``.
        """


def LID(val):
    """LocationIdentifier"""
    return val


def p_allow_deny_ignore_in_scope_decls(p):
    """ allow_deny_ignore_in_scope_decls : allow_deny_ignore_in_scope_decl
                                         | allow_deny_ignore_in_scope_decl allow_deny_ignore_in_scope_decls
    """
    p[0] = {'allow': [], 'deny': [], 'ignore': []}
    if 'allow' in p[1]:
        p[0]['allow'].append(p[1]['allow'])
    if 'deny' in p[1]:
        p[0]['deny'].append(p[1]['deny'])
    if 'ignore' in p[1]:
        p[0]['ignore'].append(p[1]['ignore'])
    if len(p) > 2:
        p[0]['allow'] = p[0]['allow'] + p[2]['allow']
        p[0]['deny'] = p[0]['deny'] + p[2]['deny']
        p[0]['ignore'] = p[0]['ignore'] + p[2]['ignore']


def clean_minmax(dic):
    """
    Clean (set to zero) the MAX/MIN dictionary keys.
    """
    dic['FDMAX'] = 0.0
    dic['FDDISPMAX'] = 0.0
    dic['FDMIN'] = 0.0
    dic['FDDISPMIN'] = 0.0
    dic['FDSCALEFLAG'] = 0.0
    return dic


def _match_first_key(skip_first_axis=None, feature=''):
    """Helper function to match and remove skip_first_axis from feature

    :param skip_first_axis: True or string. if set, ignore first axis of input histogram(s)
    :param feature: input feature
    :return: match and (rest of) feature
    """
    assert isinstance(feature, str)
    karr = feature.split(':')
    begin = karr[0]
    rest_key = ':'.join(karr[1:])
    if isinstance(skip_first_axis, bool):
        return skip_first_axis, rest_key if skip_first_axis else feature
    elif isinstance(skip_first_axis, str) and len(skip_first_axis) > 0:
        match = begin == skip_first_axis
        return match, rest_key if match else feature
    return False, feature


@classmethod
def register_action(cls, action_name, action_fn):
    """
            Registers a function to `registered_actions`.
        """
    cls.registered_actions[action_name] = action_fn


@staticmethod
def _drop_keys(obj, keys):
    """
        Drop unwanted dict keys

        :param obj:
        :param keys:
        :return:
        """
    for k in keys:
        obj.pop(k, None)


@staticmethod
def set_epoch_field():
    """
        sets number mapping values
        :return dictionary:
        """
    return {'type': 'date', 'format': 'epoch_millis'}


def cep(crossing_strand):
    """
    Returns the CrossingEntryPoint corresponding to the given
    CrossingStrand in the same crossing; that is, it orients the
    CrossingStrand without changing the crossing.
    """
    if crossing_strand == crossing_strand.oriented():
        return crossing_strand
    else:
        return crossing_strand.rotate(2)