def describe_fleet_utilization(FleetIds=None, Limit=None, NextToken=None):
    """
    Retrieves utilization statistics for one or more fleets. You can request utilization data for all fleets, or specify a list of one or more fleet IDs. When requesting multiple fleets, use the pagination parameters to retrieve results as a set of sequential pages. If successful, a  FleetUtilization object is returned for each requested fleet ID. When specifying a list of fleet IDs, utilization objects are returned only for fleets that currently exist.
    See also: AWS API Documentation

    :example: response = client.describe_fleet_utilization(
        FleetIds=[
            'string',
        ],
        Limit=123,
        NextToken='string'
    )

    :type FleetIds: list
    :param FleetIds: Unique identifier for a fleet(s) to retrieve utilization data for. To request utilization data for all fleets, leave this parameter empty.
            (string) --

    :type Limit: integer
    :param Limit: Maximum number of results to return. Use this parameter with NextToken to get results as a set of sequential pages. This parameter is ignored when the request specifies one or a list of fleet IDs.

    :type NextToken: string
    :param NextToken: Token that indicates the start of the next sequential page of results. Use the token that is returned with a previous call to this action. To specify the start of the result set, do not specify a value. This parameter is ignored when the request specifies one or a list of fleet IDs.

    :rtype: dict
    :return: {
        'FleetUtilization': [
            {
                'FleetId': 'string',
                'ActiveServerProcessCount': 123,
                'ActiveGameSessionCount': 123,
                'CurrentPlayerSessionCount': 123,
                'MaximumPlayerSessionCount': 123
            },
        ],
        'NextToken': 'string'
    }

    """
    pass


@staticmethod
def update_aliases(entry):
    """ Given an entry, checks its aliases (if any), and updates
        it's back pointers (aliased_by array).
        """
    for symbol in entry.aliased_by:
        symbol.alias = entry


def getRawInput(display):
    """
    Wrapper around raw_input; put into separate function so that it
    can be easily mocked for tests.
    """
    return input(display)


def _extract_braces_expression(line: str, starting_braces_re,
    open_braces_re, closing_braces_re):
    """ This function is taken from Plim package: https://pypi.python.org/pypi/Plim/

    :param line: may be empty
    :param starting_braces_re:
    :param open_braces_re:
    :param closing_braces_re:
    """
    match = starting_braces_re.match(line)
    if not match:
        return None
    open_brace = match.group('start_brace')
    buf = [open_brace]
    tail = line[len(open_brace):]
    braces_counter = 1
    while tail:
        current_char = tail[0]
        if closing_braces_re.match(current_char):
            braces_counter -= 1
            buf.append(current_char)
            if braces_counter:
                tail = tail[1:]
                continue
            return ''.join(buf), tail[1:]
        if open_braces_re.match(current_char):
            braces_counter += 1
            buf.append(current_char)
            tail = tail[1:]
            continue
        buf.append(current_char)
        tail = tail[1:]
    raise Exception(f'Unexpected end of a route pattern: {line}')


def remove_cookie_by_name(cookiejar, name, domain=None, path=None):
    """Unsets a cookie by name, by default over all domains and paths.

    Wraps CookieJar.clear(), is O(n).
    """
    clearables = []
    for cookie in cookiejar:
        if cookie.name != name:
            continue
        if domain is not None and domain != cookie.domain:
            continue
        if path is not None and path != cookie.path:
            continue
        clearables.append((cookie.domain, cookie.path, cookie.name))
    for domain, path, name in clearables:
        cookiejar.clear(domain, path, name)


def _mail_format_message(mail_message_tmpl, company, kwds):
    """
    Return the message to be sent to a single company
    :param str mail_message_tmpl: Template for the mail message
    :param obj company: The company object
    :param dict kwds: Additionnal keywords to pass to the string.format method
    """
    kwds['company'] = company
    message = mail_message_tmpl.format(**kwds)
    return message


def register(restorator):
    """Register L{IRestorer}"""


def p_macro_def(p):
    """macro_def : MAC macro_def_arg_list LBRACE statement_list RBRACE"""
    p[0] = 'macro_def', p[2], p[4]


def get_delegate_pattern(name, trait):
    """ Returns the correct 'delegate' listener pattern for a specified name and
        delegate trait.
    """
    prefix = trait._prefix
    if prefix == '':
        prefix = name
    elif len(prefix) > 1 and prefix[-1] == '*':
        prefix = prefix[:-1] + name
    return ' %s:%s' % (trait._delegate, prefix)


def put(this, msg):
    """
        Put something on the outgoing (response) stream
        """
    this.respQ.put(msg)


def get_state_css(unit):
    """Return state flags."""
    flags = []
    if unit.fuzzy:
        flags.append('state-need-edit')
    elif not unit.translated:
        flags.append('state-empty')
    elif unit.readonly:
        flags.append('state-readonly')
    elif unit.approved:
        flags.append('state-approved')
    elif unit.translated:
        flags.append('state-translated')
    if unit.has_failing_check:
        flags.append('state-alert')
    if unit.has_comment:
        flags.append('state-comment')
    if unit.has_suggestion:
        flags.append('state-suggest')
    return flags


def make_color_tuple(color):
    """
    turn something like "#000000" into 0,0,0
    or "#FFFFFF into "255,255,255"
    """
    R = color[1:3]
    G = color[3:5]
    B = color[5:7]
    R = int(R, 16)
    G = int(G, 16)
    B = int(B, 16)
    return R, G, B


def _to_unsigned_64_int(num: int) ->bytes:
    """Convert an integer to unsigned 64 bit bytes.

    See https://stackoverflow.com/a/45434265.

    :param num: The integer to be converted
    """
    return int(num).to_bytes(8, byteorder='big', signed=False)


def add_animate_arguments(parser):
    """ add common options for animating, you may want to make sure parser was
    constructed with conflict_handler='resolve' """
    anim = parser.add_argument_group('Options for creating animations')
    anim.add_argument('-a', '--animate', default=None, help='animate results')
    anim.add_argument('--prefix', default=None, help=
        'Prefix of the output image filenames')
    anim.add_argument('-r', '--rate', dest='framerate', type=int, default=5,
        help='animation frame rate (default 5).')
    anim.add_argument('--qscale', dest='qscale', default='2', help=
        'animation quality flag (default 2).')
    anim.add_argument('-k', dest='keep', action='store_true', help=
        'keep temporary files.')
    return parser


@classmethod
def select_mask(cls, dataset, selection):
    """
        Given a Dataset object and a dictionary with dimension keys and
        selection keys (i.e tuple ranges, slices, sets, lists or literals)
        return a boolean mask over the rows in the Dataset object that
        have been selected.
        """
    select_mask = None
    for dim, k in selection.items():
        if isinstance(k, tuple):
            k = slice(*k)
        masks = []
        alias = dataset.get_dimension(dim).name
        series = dataset.data[alias]
        if isinstance(k, slice):
            if k.start is not None:
                masks.append(k.start <= series)
            if k.stop is not None:
                masks.append(series < k.stop)
        elif isinstance(k, (set, list)):
            iter_slc = None
            for ik in k:
                mask = series == ik
                if iter_slc is None:
                    iter_slc = mask
                else:
                    iter_slc |= mask
            masks.append(iter_slc)
        elif callable(k):
            masks.append(k(series))
        else:
            masks.append(series == k)
        for mask in masks:
            if select_mask:
                select_mask &= mask
            else:
                select_mask = mask
    return select_mask


def float_range(start=0, stop=None, step=1):
    """Much like the built-in function range, but accepts floats"""
    while start < stop:
        yield float(start)
        start += step


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

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

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


def queryHistory(obj=None, history_id=None, preserve=(), default=None):
    """Return the history of an object.

        Does the same as ``getHistory`` with the difference of returning
        the value supplied with ``default`` instead of raising an exception.
        """


def hashcombine(*xs):
    """
    Combines multiple hashes using xor
    """
    k = 0
    for x in xs:
        k ^= hash(x)
    k ^= hash(xs)
    return k


def get(project, version=None):
    """Return a tuple (version, file) with the the egg for the specified
        project and version. If version is None, the latest version is
        returned. If no egg is found for the given project/version (None, None)
        should be returned."""


def lookup_tree_dist(tree_dist_dict, sp1, sp2):
    """Fast lookup of tree distance from dict of all guide tree distances."""
    return tree_dist_dict[sp1, sp2]


def to_bigbed(df, chromsizes, outpath, schema='bed6'):
    """
    Save a bedGraph-like dataframe as a binary BigWig track.

    Parameters
    ----------
    df : pandas.DataFrame
        Data frame with columns 'chrom', 'start', 'end' and one or more value
        columns
    chromsizes : pandas.Series
        Series indexed by chromosome name mapping to their lengths in bp
    outpath : str
        The output BigWig file path
    value_field : str, optional
        Select the column label of the data frame to generate the track. Default
        is to use the fourth column.

    """
    import tempfile
    import subprocess
    is_bed6 = True
    for col in ['chrom', 'start', 'end', 'name', 'score', 'strand']:
        if col not in df.columns:
            is_bed6 = False
    if len(df.columns) < 6:
        is_bed6 = False
    if not is_bed6:
        raise ValueError('A bed6-like DataFrame is required, got {}'.format
            (df.columns))
    columns = ['chrom', 'start', 'end', 'name', 'score', 'strand']
    bed = df[columns].copy()
    bed['chrom'] = bed['chrom'].astype(str)
    bed = bed.sort_values(['chrom', 'start', 'end'])
    with tempfile.NamedTemporaryFile(suffix='.bed'
        ) as f, tempfile.NamedTemporaryFile('wt', suffix='.chrom.sizes') as cs:
        chromsizes.to_csv(cs, sep='\t', header=False)
        cs.flush()
        bed.to_csv(f.name, sep='\t', columns=columns, index=False, header=
            False, na_rep='nan')
        p = subprocess.run(['bedToBigBed', '-type={}'.format(schema), f.
            name, cs.name, outpath], stdout=subprocess.PIPE, stderr=
            subprocess.PIPE)
    return p


def write_bed_file(bed_default_dict, output_file):
    """Write default dict to a bed file
    :param bed_default_dict: default dict created from aggregate_methylbeds
    :param output_file: path to output file
    """
    with open(output_file, 'w') as fh:
        for chromosome, strand_dict in bed_default_dict.items():
            for strand, start_dict in strand_dict.items():
                for start, coverage_list in start_dict.items():
                    coverage_total = 0
                    percentage_total = 0
                    max_percentage = 0
                    for x in coverage_list:
                        coverage_total += x[1]
                        percentage_total += x[1] * x[2]
                        max_percentage += x[1] * 100
                    color = x[0]
                    if max_percentage != 0:
                        percentage = int(percentage_total / max_percentage *
                            100)
                        print('\t'.join([chromosome, start, str(int(start) +
                            1), '.', str(coverage_total), strand, start,
                            str(int(start) + 1), color, str(coverage_total),
                            str(percentage)]), file=fh)


def set_verbosity(level):
    """Sets the modules message verbosity level for *all* messages printed.

    :arg level: a positive integer (>0); higher levels including more detail.
    """
    global verbosity
    verbosity = level


def isDirty():
    """Return a bool whether there was any database write since the
        transaction started.

        A SQL write command or any persistent object change will set this flag.

        `transaction.commit` or `transaction.abort` clears this flag.
        """


def put_trace(f, trace):
    """
    Write a trace to file f.
    """
    f.write(trace.tostring())
    return


def strtobool(val):
    """Convert a string representation of truth to true (1) or false (0).

    True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
    are 'n', 'no', 'f', 'false', 'off', and '0'.  Raises ValueError if
    'val' is anything else.

    This function has been borrowed from distutils.util module in order
    to avoid pulling a dependency on deprecated module "imp".
    """
    val = val.lower()
    if val in ('y', 'yes', 't', 'true', 'on', '1'):
        return 1
    elif val in ('n', 'no', 'f', 'false', 'off', '0'):
        return 0
    else:
        raise ValueError('invalid truth value %r' % (val,))


@classmethod
def add_common_opts(cls, parser):
    """Add options that are common for several plugins.
        """
    for opt in cls.common_opt_names:
        cls._parser_add_opt(parser, opt)


def gt(first=None, second=None):
    """ Checks if first element is greater than the second """
    if first is None or second is None:
        return True
    return first > second


def _get_length_length(_bytes):
    """Returns a count of bytes in an Ion value's `length` field."""
    if _bytes[0] & 15 == 14:
        for i in range(1, len(_bytes)):
            if _bytes[i] & 128 != 0:
                return i
        raise Exception('Problem while reading VarUInt!')
    return 0


@classmethod
def dump(cls, filename):
    """
        Writes the contents of this model's table as JSON to the given filename
        """
    with open(filename, 'w') as out:
        out.write(cls.dumps())


@classmethod
def update(cls, status_dir):
    """Update all job statuses and dump to json.

        Parameters
        ----------
        status_dir : str
            Directory containing json status file.
        """
    obj = cls(status_dir)
    for module in obj.data.keys():
        for job_name in obj.data[module].keys():
            if job_name != 'pipeline_index':
                obj._update_job_status(module, job_name)
    obj._check_all_job_files(status_dir)
    obj._dump()


def _check_system_configs(problem, logger):
    """
    Perform any system specific configuration checks.

    Parameters
    ----------
    problem : <Problem>
        The problem being checked.
    logger : object
        The object that manages logging output.
    """
    for system in problem.model.system_iter(include_self=True, recurse=True):
        system.check_config(logger)


def _parse_match_info(match, regex, soccer=False):
    """
    Parse string containing info of a specific match

    :param match: Match data
    :type match: string
    :param regex: Match data pattern
    :type regex: Regex object
    :param soccer: Set to true if match contains soccer data, defaults to False
    :type soccer: bool, optional
    :return: Dictionary containing match information
    :rtype: dict
    """
    match = regex.search(match)
    match_info = {'league': match.group(1), 'home_team': match.group(2),
        'away_team': match.group(3), 'home_score': match.group(4),
        'away_score': match.group(5)}
    if match_info['home_score'] is None:
        match_info['home_score'] = '0'
    if match_info['away_score'] is None:
        match_info['away_score'] = '0'
    if soccer:
        match_info['match_time'] = match[6]
    return match_info


def quaternions_flip():
    """Flip quaternion values to achieve desired rotations, while maintaining the same orientations

    """
    pass


@classmethod
def __call__(cls, inp):
    """Returns whether given input ran this command"""
    match = cls.match(inp)
    if match:
        cls.run(inp)
    return match


@staticmethod
def abberation_correction(R):
    """Calculate the abberation correction (delta_tau, in degrees) given the Earth Heliocentric Radius (in AU)"""
    return -20.4898 / (3600 * R)


def get_sbml_tag(element) ->str:
    """Return tag associated with given SBML element"""
    if element.tag[0] == '{':
        _, tag = element.tag[1:].split('}')
    else:
        tag = element.tag
    return tag


def release_address(DryRun=None, PublicIp=None, AllocationId=None):
    """
    Releases the specified Elastic IP address.
    After releasing an Elastic IP address, it is released to the IP address pool and might be unavailable to you. Be sure to update your DNS records and any servers or devices that communicate with the address. If you attempt to release an Elastic IP address that you already released, you'll get an AuthFailure error if the address is already allocated to another AWS account.
    [EC2-Classic, default VPC] Releasing an Elastic IP address automatically disassociates it from any instance that it's associated with. To disassociate an Elastic IP address without releasing it, use  DisassociateAddress .
    [Nondefault VPC] You must use  DisassociateAddress to disassociate the Elastic IP address before you try to release it. Otherwise, Amazon EC2 returns an error (InvalidIPAddress.InUse ).
    See also: AWS API Documentation

    Examples
    This example releases an Elastic IP address for use with instances in a VPC.
    Expected Output:
    This example releases an Elastic IP address for use with instances in EC2-Classic.
    Expected Output:

    :example: response = client.release_address(
        DryRun=True|False,
        PublicIp='string',
        AllocationId='string'
    )

    :type DryRun: boolean
    :param DryRun: Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation .

    :type PublicIp: string
    :param PublicIp: [EC2-Classic] The Elastic IP address. Required for EC2-Classic.

    :type AllocationId: string
    :param AllocationId: [EC2-VPC] The allocation ID. Required for EC2-VPC.

    :return: response = client.release_address(
        AllocationId='eipalloc-64d5890a',
    )

    print(response)

    """
    pass


@classmethod
def _get_backend_loader(cls, name):
    """
        subclassed to support legacy 1.6 HasManyBackends api.
        (will be removed in passlib 2.0)
        """
    loader = getattr(cls, '_load_backend_' + name, None)
    if loader is None:

        def loader():
            return cls.__load_legacy_backend(name)
    else:
        assert not hasattr(cls, '_has_backend_' + name
            ), "%s: can't specify both ._load_backend_%s() and ._has_backend_%s" % (
            cls.name, name, name)
    return loader


def save_obj(obj, file_name):
    """
    将对象持久化到本地, 方便直接调试
    :param obj:
    :param file_name:
    :return:
    """
    try:
        import cPickle as pickle
    except ImportError:
        import pickle
    pickle.dump(obj, open(file_name, 'w'))


def add_meta_info_to_all(it, info):
    """Add the info to all RADRead objects in the iterable."""
    for rad_read in it:
        rad_read.add_meta_info(info)


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

        :param FileMoveType val:
        :rtype: EventType
        """
    return cls('file_move', val)


@classmethod
def compose(cls, *args):
    """Return the product of a collection of matrices."""
    return cls.mul(*args)


def read_csv_from_url(url, verbose=False, read_csv_kwds={}):
    """Loading function to load all .csv datasets.
    Args:
        url (str): csv raw link
        verbose (bool): Controls display of loading message and .head()
        read_csv_kwds (dict): dict of commands to feed to pd.read_csv()
    Returns:
        df (DataFrame): the dataset("""
    import pandas as pd
    from IPython.display import display
    if read_csv_kwds is not None:
        df = pd.read_csv(url, **read_csv_kwds)
    else:
        df = pd.read_csv(url)
    if verbose:
        display(df.head())
    return df


def escape(x, lb=False):
    """
    Ensure a string does not contain HTML-reserved characters (including
    double quotes)
    Optionally also insert a linebreak if the string is too long
    """
    if lb:
        l = len(x)
        if l >= 10:
            l >>= 1
            s1 = x.find(' ', l)
            s2 = x.rfind(' ', 0, l)
            if s2 > 0:
                s = s2 if s1 < 0 or l - s1 > s2 - l else s1
                x = x[:s] + '\\n' + x[s + 1:]
            elif s1 > 0:
                x = x[:s1] + '\\n' + x[s1 + 1:]
    return x.replace('&', '&').replace('<', '<').replace('>', '>'
        ).replace('"', '"')


def split_icon_address(address: str) ->(str, str):
    """Split icon address into 2-char prefix and 40-char address body

    :param address: 42-char address string
    :return: prefix, body
    """
    return address[:2], address[2:]


@classmethod
def for_type(cls, tp, hookfn, referencer=None, mode='set'):
    """
        For an object of a given type, apply the hookfn and use the
        specified mode to aggregate the data.

        To allow pickling (or any other defered access) of the target
        object, a referencer (a Reference subclass) may be specified
        to wrap the object as required.

        If mode is 'merge', merge the Layout output by the hook,
        otherwise if 'set', add the output to the path specified by
        the ViewRef.
        """
    cls.type_hooks[tp] = hookfn, mode, referencer


def split(raw_text):
    """Takes a chunk of raw markdown and splits it into blocks.

    :param str raw_text: The raw markdown.
    :rtype: ``list``"""
    return raw_text.replace('\r\n', '\n').split('\n\n')


def agency_api_authentication_default():
    """Default value for the ``agency_api_authentication`` field.

    Other keys are specific to each type:
    - token: "header" and "token"
    - oauth2: "client_id" and "client_secret"
    """
    return {'type': 'none'}


def read_file(css_file_name):
    """Function to read the CSS file"""
    with open(css_file_name, 'r') as file:
        return file.read()


def average(numbers):
    """
    Quick averaging function

    """
    return float(sum(numbers)) / len(numbers)


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

        :param dn: string containing the distinguished name URL
        :return: string containing the name
        """
    name = dn.split('/overlay')[1].split('/')[0]
    return name


def dict_pwys_to_file(dict_pwy, output):
    """
    Create csv file from dict_pwy. dict_pwy is obtained with extract_pwys()

    Parameters
    ----------
    dict_pwy: dict
        dict, k=pathway_id, v=dict: k in [total_rxn, rxn_from_list, ratio
        ex: {pwy-x:{'total_rxn':[a,b,c], rxn_from_list:[a], ratio:1/3}}
    output: str
        path to output file

    """
    with open(output, 'w') as f:
        header = ['pathway_id', 'total_rxn', 'rxn_from_list', 'ratio']
        f.write('\t'.join(header) + '\n')
        for pwy_id, pwy_data in dict_pwy.items():
            total_rxn = pwy_data['total_rxn']
            rxn_from_list = pwy_data['rxn_from_list']
            ratio = pwy_data['ratio']
            line = [pwy_id, ';'.join(total_rxn), ';'.join(rxn_from_list),
                str(ratio)]
            f.write('\t'.join(line) + '\n')


def parse_global_range_dataframe(global_ranges):
    """ Cleans up the global ranges dataframe """
    global_df = global_ranges[global_ranges.columns[:-3]]
    global_df.columns = ['reference_designator', 'parameter_id_r',
        'parameter_id_t', 'global_range_min', 'global_range_max',
        'data_level', 'units']
    return global_df


def racenameanddur(eventname):
    """
    get race name and duration

    :param eventname: eventname from untrasignup.com
    :rtype: racename, duration
    """
    racetext = eventname.strip()
    fields = racetext.split('-')
    racename = racetext
    durfield = fields[-1].strip()
    dur = 0
    startunits = 0
    for digit in durfield:
        if not digit.isdigit():
            break
        dur *= 10
        dur += int(digit)
        startunits += 1
    units = durfield[startunits:]
    if units == 'hrs':
        duration = dur
    else:
        duration = None
    return racename, duration


@classmethod
def get_connection_cls(cls):
    """Return connection class.

        :rtype: :class:`type`
        """
    if cls.__connection_cls is None:
        cls.__connection_cls, _ = cls.from_settings()
    return cls.__connection_cls


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


def get_query_class(method):
    """Get class of query strategy from its name.

    Arguments
    ---------
    method: str
        Name of the query strategy, e.g. 'max', 'uncertainty', 'random.
        A special mixed query strategy is als possible. The mix is denoted
        by an underscore: 'max_random' or 'max_uncertainty'.

    Returns
    -------
    BaseQueryModel:
        Class corresponding to the method name.
    """
    from asreview.query_strategies.cluster import ClusterQuery
    from asreview.query_strategies.max import MaxQuery
    from asreview.query_strategies.uncertainty import UncertaintyQuery
    from asreview.query_strategies.random import RandomQuery
    from asreview.query_strategies.mixed import MixedQuery
    query_models = {'cluster': ClusterQuery, 'max': MaxQuery, 'uncertainty':
        UncertaintyQuery, 'random': RandomQuery}
    try:
        return query_models[method]
    except KeyError:
        mix = method.split('_')
        if len(mix) == 2:
            return MixedQuery
        raise ValueError(f"Error: query method '{method}' is not implemented.")


def getFormulaAtoms(atomS, atomN):
    """
    transform a compound list and number in string
    >>> AtomsToCompound(['H','O'],[2,1])
    'H 2 O 1'
    """
    S = ''
    if len(atomS) == len(atomN):
        for i in range(len(atomS)):
            S = S + ' ' + str(atomS[i]) + ' ' + str(atomN[i])
    return S.strip()


def on_error(ws, error):
    """
    Prints an error, if occurs.

    :param ws: WebSocketApp
    :param error: An error
    """
    print(error)


def list_offering_transactions(nextToken=None):
    """
    Returns a list of all historical purchases, renewals, and system renewal transactions for an AWS account. The list is paginated and ordered by a descending timestamp (most recent transactions are first). The API returns a NotEligible error if the user is not permitted to invoke the operation. Please contact aws-devicefarm-support@amazon.com if you believe that you should be able to invoke this operation.
    See also: AWS API Documentation

    Examples
    The following example returns information about Device Farm offering transactions.
    Expected Output:

    :example: response = client.list_offering_transactions(
        nextToken='string'
    )

    :type nextToken: string
    :param nextToken: An identifier that was returned from the previous call to this operation, which can be used to return the next set of items in the list.

    :rtype: dict
    :return: {
        'offeringTransactions': [
            {
                'offeringStatus': {
                    'type': 'PURCHASE'|'RENEW'|'SYSTEM',
                    'offering': {
                        'id': 'string',
                        'description': 'string',
                        'type': 'RECURRING',
                        'platform': 'ANDROID'|'IOS',
                        'recurringCharges': [
                            {
                                'cost': {
                                    'amount': 123.0,
                                    'currencyCode': 'USD'
                                },
                                'frequency': 'MONTHLY'
                            },
                        ]
                    },
                    'quantity': 123,
                    'effectiveOn': datetime(2015, 1, 1)
                },
                'transactionId': 'string',
                'offeringPromotionId': 'string',
                'createdOn': datetime(2015, 1, 1),
                'cost': {
                    'amount': 123.0,
                    'currencyCode': 'USD'
                }
            },
        ],
        'nextToken': 'string'
    }

    """
    pass


def p_accent(p):
    """
    math_object : ACCENT block
                    | ACCENT symbol
    """
    p[2].accent = p[1]
    p[0] = [p[2]]


def dic2fileheader(dic):
    """
    Convert a Python dictionary into a fileheader list

    Does not repack status from bit flags
    """
    head = [0] * 9
    head[0] = dic['nblocks']
    head[1] = dic['ntraces']
    head[2] = dic['np']
    head[3] = dic['ebytes']
    head[4] = dic['tbytes']
    head[5] = dic['bbytes']
    head[6] = dic['vers_id']
    head[7] = dic['status']
    head[8] = dic['nbheaders']
    return head


def split_extension(filename):
    """
	Splits the extension off the filename and returns a tuple of the
	base filename and the extension (without the dot).

	:param str filename: The base filename string to split.
	:return: A tuple of the head (characters before the last '.') and
			 the extension (characters after the last '.').
	"""
    parts = filename.split('.')
    if len(parts) < 2:
        return parts[0], ''
    ext = parts.pop(-1)
    head = '.'.join(parts)
    return head, ext


def check_str_arg(result, func, cargs):
    """
    This is for the OSRGet[Angular|Linear]Units functions, which
    require that the returned string pointer not be freed.  This
    returns both the double and string values.
    """
    dbl = result
    ptr = cargs[-1]._obj
    return dbl, ptr.value.decode()


def get_user_agent_from_header_meta(request_meta):
    """
    Getting user agent from request meta
    """
    return request_meta.get('HTTP_USER_AGENT', '')


def _get_columns(x):
    """ retrieve the columns of something if it exists """
    if hasattr(x, 'columns'):
        return list(x.columns)
    else:
        return None


def append_to_path(uri, path):
    """
    This is a helper function for appending a path to a URI (i.e, just the path portion
    of a full URL).  The main purpose is to make sure one and only one slash ends up between them.

    :param uri: the URI to append the path to.
    :param path: the path to append.
    :return: the result of the append.
    """
    if uri.endswith('/') and path.startswith('/'):
        uri += path[1:]
    elif not (uri.endswith('/') or path.startswith('/')):
        uri = uri + '/' + path
    else:
        uri += path
    return uri


def change_action_status(action_type, new_status):
    """
        This function changes the status of an action type.
    """
    return '%s.%s' % ('.'.join(action_type.split('.')[:-1]), new_status)


def duration_string_to_seconds(string):
    """ Converts a string representation of duration
        into total seconds in float.

        >>>  duration_string_to_seconds('00:03:16')
        196
    """
    duration = string.split(':')
    return int(duration[0]) * 60 * 60 + int(duration[1]) * 60 + int(duration[2]
        )


def validate_string(value, label):
    """Validates that the given value is a string."""
    if not isinstance(value, str):
        raise ValueError('Invalid type for {0}: {1}.'.format(label, value))
    return value


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

        :param WebSessionsChangeActiveSessionLimitDetails val:
        :rtype: EventDetails
        """
    return cls('web_sessions_change_active_session_limit_details', val)


def leading(value):
    """
    Strip all leading whitespaces.
    :param value: The value
    :type value: str
    :return: The value with all leading whitespaces removed
    :rtype: str
    """
    return value.lstrip()


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

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

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


def strip_fname(name):
    """
    strip wrapper (e.g. F${}, V${}, P${}) from name to get ID.
    :param name: string to strip
    :return: element name without wrapper text
    """
    return name[3:-1]


def _get_zone_letter(latitude):
    """
    Calculate the UTM zone letter from the given latitude. Shamelessly lifted
    from the utm.latitude_to_zone_letter function.

    Parameters
    ----------
    lat : float
        Latitude

    Returns
    -------
    zone_letter : str
        Zone letter

    """
    ZONE_LETTERS = 'CDEFGHJKLMNPQRSTUVWXX'
    if -80 <= latitude <= 84:
        return ZONE_LETTERS[int(latitude + 80) >> 3]
    else:
        return None


def resels2nnodes(resels, fwhm):
    """
	Get the number of field nodes from resel counts based on the FWHM

	:Parameters:

		*resels* --- resel counts

		*fwhm* --- actual or estimated FWHM*element_based* --- element-based sampling (default: node-based sampling)

	:Returns:

		*nNodes* --- number of field nodes

	:Example:

		>>> resels = (1, 10.0)
		>>> nNodes = rft1d.geom.resels2nnodes(resels, 10.0) #yields 101
		>>> resels = (2, 6.9)
		>>> nNodes = rft1d.geom.resels2nnodes(resels, 10.0) #yields 71

	:Note:

		See **rft1d.geom.resel_counts** for details regarding node-based vs. element-based sampling.
	"""
    return int(resels[0] + fwhm * resels[1])


def get_lomb_amplitude(lomb_model, i, j):
    """
    Get the amplitude of the jth harmonic of the ith frequency from a fitted
    Lomb-Scargle model.
    """
    return lomb_model['freq_fits'][i - 1]['amplitude'][j - 1]


def stream_out():
    """Obtain streaming clone data.

        Successful result should be a generator of data chunks.
        """


def PreciseAMPM():
    """Return the time string for the object."""


@staticmethod
def length(session, name):
    """
            Returns the length of the feature

            @param: session - the local session
            @param: name - the name of the feature one wishes to extract

            @return: feature length
        """
    xml = session.fetchxml('/features/%s' % name)
    return int(xml.find('feature/tag[@name="feature_length"]').attrib.get(
        'value'))


def read_counts(sample_labels, counts_files):
    """ Reads the counts from an input file. """
    cpt = {}
    cpt_genome = {}
    for sample_label, filename in zip(sample_labels, counts_files):
        cpt[sample_label] = {}
        with open(filename, 'r') as counts_fh:
            for line in counts_fh:
                if not line.startswith('#'):
                    feature = tuple(line.split('\t')[0].split(','))
                    cpt[sample_label][feature] = float(line.split('\t')[1])
                    cpt_genome[feature] = float(line.rstrip().split('\t')[2])
    return cpt, cpt_genome


@staticmethod
def isVerbose():
    """
        Part of BASE CLIENT API of EKOS

        :return: status of verbose
        """
    return False


def _all_cookie_octets_str():
    """
        %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E;
        US-ASCII characters excluding CTLs,
        whitespace DQUOTE, comma, semicolon,
        and backslash
    """
    all_cookie_octets_str = '!'
    for i in range(35, 44):
        all_cookie_octets_str = all_cookie_octets_str + chr(i)
    for i in range(45, 58):
        all_cookie_octets_str = all_cookie_octets_str + chr(i)
    for i in range(60, 92):
        all_cookie_octets_str = all_cookie_octets_str + chr(i)
    for i in range(93, 126):
        all_cookie_octets_str = all_cookie_octets_str + chr(i)
    return all_cookie_octets_str


def join(iterable, sep=' ', end='\n'):
    """Return a string which is the concatenation of string
    representations of objects in the iterable, separated by sep.

    end is appended to the resulting string.
    """
    return sep.join(map(str, iterable)) + end


@staticmethod
def p_kp_data_parameter_optional(p):
    """kp_data_parameter_optional : NUMERIC
                                      | STRING
                                      | IDENT"""
    p[0] = p[1]


@classmethod
def replace_unsupported_chars(cls, s):
    """
        Given an input string, returns the corresponding string that:
        - is available in the helvetica facetype
        - does not contain any ligature (to allow easy search in the PDF file)
        """
    return s.translate(cls.ligatures)


def set_up_correlation(corr, min_lag=None, max_lag=None, lag_resolution=
    None, alpha=None):
    """ No return type. Applies non-default values to correlator """
    if max_lag is not None:
        corr.max_lag = max_lag
    if min_lag is not None:
        corr.min_lag = min_lag
    if lag_resolution is not None:
        corr.lag_resolution = lag_resolution
    if alpha is not None:
        corr.alpha = alpha


def _caseless_key_in_dict(index: str, dictionary: dict) ->bool:
    """Return True if index is a key of dictionary ignoring casing."""
    for key in dictionary:
        if isinstance(key, str) and index.lower() == key.lower():
            return True
    return False


def without(iterable, remove_indices):
    """
	Returns an iterable for a collection or iterable, which returns all items except the specified indices.
	"""
    if not hasattr(remove_indices, '__iter__'):
        remove_indices = {remove_indices}
    else:
        remove_indices = set(remove_indices)
    for k, item in enumerate(iterable):
        if k in remove_indices:
            continue
        yield item


def text_cut():
    """Cut selected text to clipboard

    """
    pass


def get_dict_by_ids(model, ids):
    """
    Retorna un diccionario con los *ids* pasados como parametro y los objetos
    que pertenecen al modelo *model* y que tienen sus id dentro de *ids*
    """
    objects_dict = {}
    query = model.objects.filter(pk__in=ids)
    for obj in query:
        key = str(obj.id)
        objects_dict[key] = obj
    return objects_dict


@staticmethod
def reverse(string):
    """Reverse string sequence"""
    return string.upper()[::-1]


@classmethod
def read(cls, file):
    """
        Read a GFF3 file.

        Parameters
        ----------
        file : file-like object or str
            The file to be read.
            Alternatively a file path can be supplied.

        Returns
        -------
        file_object : GFFFile
            The parsed file.
        """
    file = super().read(file)
    file._index_entries()
    return file


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

    The ".dev0" means dirty.

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


@classmethod
def in_chain(cls, client, chain_id, expiration_dates=[]):
    """
        fetch all option instruments in an options chain
        - expiration_dates = optionally scope
        """
    request_url = 'https://api.robinhood.com/options/instruments/'
    params = {'chain_id': chain_id, 'expiration_dates': ','.join(
        expiration_dates)}
    data = client.get(request_url, params=params)
    results = data['results']
    while data['next']:
        data = client.get(data['next'])
        results.extend(data['results'])
    return results


@staticmethod
def keep_longest(head, update, down_path):
    """Keep longest field among `head` and `update`.
        """
    if update is None:
        return 'f'
    if head is None:
        return 's'
    return 'f' if len(head) >= len(update) else 's'


def version_cmp(version, version_compare):
    """
    Compares the given version string against a compare string
    that may contain wildcard values.

    This way it's possible to compare it against version ranges
    defined in the form of wildcard values.

    :type version: String
    :param version: The base version string to be verified
    by the comparison.
    :type version_compare: String
    :param version_compare: The compare version string to be used
    as reference in the comparison (may contain wildcard values).
    :rtype: bool
    :return: The result of the version string comparison (includes
    wildcard comparison).
    """
    major, medium, minor = version.split('.')
    major_compare, medium_compare, minor_compare = version_compare.split('.')
    if not major_compare == 'x' and not major == major_compare:
        return False
    if not medium_compare == 'x' and not medium == medium_compare:
        return False
    if not minor_compare == 'x' and not minor == minor_compare:
        return False
    return True


def compare_xforms(lta_list, norm_threshold=15):
    """
    Computes a normalized displacement between two affine transforms as the
    maximum overall displacement of the midpoints of the faces of a cube, when
    each transform is applied to the cube.
    This combines displacement resulting from scaling, translation and rotation.

    Although the norm is in mm, in a scaling context, it is not necessarily
    equivalent to that distance in translation.

    We choose a default threshold of 15mm as a rough heuristic.
    Normalized displacement above 20mm showed clear signs of distortion, while
    "good" BBR refinements were frequently below 10mm displaced from the rigid
    transform.
    The 10-20mm range was more ambiguous, and 15mm chosen as a compromise.
    This is open to revisiting in either direction.

    See discussion in
    `GitHub issue #681`_ <https://github.com/poldracklab/fmriprep/issues/681>`_
    and the `underlying implementation
    <https://github.com/nipy/nipype/blob/56b7c81eedeeae884ba47c80096a5f66bd9f8116/nipype/algorithms/rapidart.py#L108-L159>`_.

    Parameters
    ----------

      lta_list : :obj:`list` or :obj:`tuple` of :obj:`str`
          the two given affines in LTA format
      norm_threshold : :obj:`float`
          the upper bound limit to the normalized displacement caused by the
          second transform relative to the first (default: `15`)

    """
    from niworkflows.interfaces.surf import load_transform
    from nipype.algorithms.rapidart import _calc_norm_affine
    bbr_affine = load_transform(lta_list[0])
    fallback_affine = load_transform(lta_list[1])
    norm, _ = _calc_norm_affine([fallback_affine, bbr_affine],
        use_differences=True)
    return norm[1] > norm_threshold


def SizeBenefitAccHosp(t):
    """Accidental hospitalization benefit per policy"""
    return 0


def process(proc_data):
    """
    Final processing to conform to the schema.

    Parameters:

        proc_data:   (dictionary) raw structured data to process

    Returns:

        List of dictionaries. Structured data with the following schema:

        [
          {
            "name":       string,
            "address":    string,
            "hwtype":     string,
            "hwaddress":  string,
            "flags_mask": string,
            "iface":      string
          }
        ]
    """
    for entry in proc_data:
        if 'name' in entry and entry['name'] == '?':
            entry['name'] = None
    return proc_data


@staticmethod
def ema(x, mu=None, alpha=0.3):
    """
        Exponential moving average: smoothing to give progressively lower
        weights to older values.

        Parameters
        ----------
        x  : float
            New value to include in EMA.
        mu  : float, optional
            Previous EMA value.
        alpha  : float, optional
            Smoothing factor in range [0, 1], [default: 0.3].
            Increase to give more weight to recent values.
            Ranges from 0 (yields mu) to 1 (yields x).
        """
    return x if mu is None else alpha * x + (1 - alpha) * mu


@classmethod
def _find_coeff_for_title_hight(cls, title):
    """Find title hight.

        Count coefficient for annotations coordinate depend on scale.
        """
    if title.split(' ')[1] in ['добыча,', 'масса']:
        coef = 5
    else:
        coef = 0.1
    return coef


def _clip(x, upper_bound):
    """Return x clipped betweed 0 and upper_bound."""
    if x < 0:
        x = 0
    if x > upper_bound:
        x = upper_bound
    return x


def set_solution_scale(distance: float=0.0):
    """Set object solution scale using distance between two selected tracks

    :param distance: Distance, Distance between selected tracks
    :type distance: float
    """
    pass


def update_fleet_port_settings(FleetId=None,
    InboundPermissionAuthorizations=None, InboundPermissionRevocations=None):
    """
    Updates port settings for a fleet. To update settings, specify the fleet ID to be updated and list the permissions you want to update. List the permissions you want to add in InboundPermissionAuthorizations , and permissions you want to remove in InboundPermissionRevocations . Permissions to be removed must match existing fleet permissions. If successful, the fleet ID for the updated fleet is returned.
    See also: AWS API Documentation

    :example: response = client.update_fleet_port_settings(
        FleetId='string',
        InboundPermissionAuthorizations=[
            {
                'FromPort': 123,
                'ToPort': 123,
                'IpRange': 'string',
                'Protocol': 'TCP'|'UDP'
            },
        ],
        InboundPermissionRevocations=[
            {
                'FromPort': 123,
                'ToPort': 123,
                'IpRange': 'string',
                'Protocol': 'TCP'|'UDP'
            },
        ]
    )

    :type FleetId: string
    :param FleetId: [REQUIRED]
            Unique identifier for a fleet to update port settings for.

    :type InboundPermissionAuthorizations: list
    :param InboundPermissionAuthorizations: Collection of port settings to be added to the fleet record.
            (dict) --A range of IP addresses and port settings that allow inbound traffic to connect to server processes on Amazon GameLift. Each game session hosted on a fleet is assigned a unique combination of IP address and port number, which must fall into the fleet's allowed ranges. This combination is included in the GameSession object.
            FromPort (integer) -- [REQUIRED]Starting value for a range of allowed port numbers.
            ToPort (integer) -- [REQUIRED]Ending value for a range of allowed port numbers. Port numbers are end-inclusive. This value must be higher than FromPort .
            IpRange (string) -- [REQUIRED]Range of allowed IP addresses. This value must be expressed in CIDR notation. Example: '000.000.000.000/[subnet mask] ' or optionally the shortened version '0.0.0.0/[subnet mask] '.
            Protocol (string) -- [REQUIRED]Network communication protocol used by the fleet.

    :type InboundPermissionRevocations: list
    :param InboundPermissionRevocations: Collection of port settings to be removed from the fleet record.
            (dict) --A range of IP addresses and port settings that allow inbound traffic to connect to server processes on Amazon GameLift. Each game session hosted on a fleet is assigned a unique combination of IP address and port number, which must fall into the fleet's allowed ranges. This combination is included in the GameSession object.
            FromPort (integer) -- [REQUIRED]Starting value for a range of allowed port numbers.
            ToPort (integer) -- [REQUIRED]Ending value for a range of allowed port numbers. Port numbers are end-inclusive. This value must be higher than FromPort .
            IpRange (string) -- [REQUIRED]Range of allowed IP addresses. This value must be expressed in CIDR notation. Example: '000.000.000.000/[subnet mask] ' or optionally the shortened version '0.0.0.0/[subnet mask] '.
            Protocol (string) -- [REQUIRED]Network communication protocol used by the fleet.

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

    """
    pass


def az_rate(val):
    """Convert an integer value to a floating point angular rate."""
    return val * 90.0 / 2 ** 16


def atom_is_aromatic(atom):
    """Get whether the atom is aromatic.

    Parameters
    ----------
    atom : rdkit.Chem.rdchem.Atom
        RDKit atom instance.

    Returns
    -------
    list
        List containing one bool only.
    """
    return [atom.GetIsAromatic()]


def delete_key_pair(DryRun=None, KeyName=None):
    """
    Deletes the specified key pair, by removing the public key from Amazon EC2.
    See also: AWS API Documentation

    Examples
    This example deletes the specified key pair.
    Expected Output:

    :example: response = client.delete_key_pair(
        DryRun=True|False,
        KeyName='string'
    )

    :type DryRun: boolean
    :param DryRun: Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation .

    :type KeyName: string
    :param KeyName: [REQUIRED]
            The name of the key pair.

    :return: response = client.delete_key_pair(
        KeyName='my-key-pair',
    )

    print(response)

    """
    pass


def immediate_read(f):
    """A PinBank read mode: read() is called automatically whenever a pin value is read.

    Note: this mode is not compatible with interrupts. A warning will
    be issued if interrupts are enabled on a PinBank that is in
    immediate_read mode.
    """
    f()


def generate_boolean(field, factory):
    """Generate a boolean.

    Always returns False.

    :returns: False
    """
    return False


def exclude_device(exclude, data):
    """Remove the *exclude* device from *data*"""
    for device in exclude:
        if device in data:
            del data[device]


def set_master(master: str):
    """ Set the master of the PyGMQL instance. It accepts any master configuration available in Spark.

    :param master: master configuration
    :return: None
    """
    global __master
    __master = master


def sanitize(msg):
    """Sanitizes the existing msg, use before adding color annotations"""
    msg = msg.replace('@', '@@')
    msg = msg.replace('{', '{{')
    msg = msg.replace('}', '}}')
    msg = msg.replace('@@!', '@{atexclimation}')
    msg = msg.replace('@@/', '@{atfwdslash}')
    msg = msg.replace('@@_', '@{atunderscore}')
    msg = msg.replace('@@|', '@{atbar}')
    return msg


@classmethod
def import_set(cls, dset, in_stream):
    """Returns dataset from DataFrame."""
    dset.wipe()
    dset.dict = in_stream.to_dict(orient='records')


def _subgroup_pruning_step(pre_pruning_assembly):
    """
    Removes assemblies which are already all included in a bigger assembly

    Parameters
    ----------
    pre_pruning_assembly : list
        contains the assemblies filtered by the significance value

    Returns
    --------
    final_assembly : list
        contains the assemblies filtered by inclusion

    """
    pre_pruning_assembly_r = list(reversed(pre_pruning_assembly))
    nns = len(pre_pruning_assembly_r)
    selection = [(True) for _ in range(nns)]
    for i in range(nns):
        if selection[i]:
            a = pre_pruning_assembly_r[i]['neurons']
            for j in range(i + 1, nns):
                if selection[j]:
                    b = pre_pruning_assembly_r[j]['neurons']
                    if set(a).issuperset(set(b)):
                        selection[j] = False
                    if set(b).issuperset(set(a)):
                        selection[i] = False
                    if set(a) == set(b):
                        selection[i] = True
                        selection[j] = True
    assembly_r = []
    for i in range(nns):
        if selection[i]:
            assembly_r.append(pre_pruning_assembly_r[i])
    assembly = list(reversed(assembly_r))
    return assembly


def calculate_max_velocity(engine_speed_at_max_power, max_speed_velocity_ratio
    ):
    """
    Calculates max vehicle velocity [km/h].

    :param engine_speed_at_max_power:
        Rated engine speed [RPM].
    :type engine_speed_at_max_power: float

    :param max_speed_velocity_ratio:
        Maximum speed velocity ratio of the gear box [h*RPM/km].
    :type max_speed_velocity_ratio: float

    :return:
        Max vehicle velocity [km/h].
    :rtype: float
    """
    return engine_speed_at_max_power / max_speed_velocity_ratio


def set_matched_surfaces(surface, matched):
    """Set boundary conditions for two adjoining surfaces.

    :param surface: The first surface.
    :param matched: The second surface.
    """
    if str(surface.key).upper() == 'BUILDINGSURFACE:DETAILED' and str(matched
        .key).upper() == 'BUILDINGSURFACE:DETAILED':
        for s in [surface, matched]:
            s.Outside_Boundary_Condition = 'surface'
            s.Sun_Exposure = 'NoSun'
            s.Wind_Exposure = 'NoWind'
        surface.Outside_Boundary_Condition_Object = matched.Name
        matched.Outside_Boundary_Condition_Object = surface.Name
    elif str(surface.key).upper() == 'BUILDINGSURFACE:DETAILED' and str(matched
        .key).upper() in {'SHADING:SITE:DETAILED', 'SHADING:ZONE:DETAILED'}:
        surface.Outside_Boundary_Condition = 'adiabatic'
        surface.Sun_Exposure = 'NoSun'
        surface.Wind_Exposure = 'NoWind'
    elif str(matched.key).upper() == 'BUILDINGSURFACE:DETAILED' and str(surface
        .key).upper() in {'SHADING:SITE:DETAILED', 'SHADING:ZONE:DETAILED'}:
        matched.Outside_Boundary_Condition = 'adiabatic'
        matched.Sun_Exposure = 'NoSun'
        matched.Wind_Exposure = 'NoWind'


def pairwise(iterable):
    """
    break a list (or other iterable) into pairs

    ::

		s -> (s0, s1), (s2, s3), (s4, s5), ...

		In [71]: for item in pairwise("a b c d e fg".split()):
			...:     print(item)
			...:
		('a', 'b')
		('c', 'd')
		('e', 'fg')

    """
    a = iter(iterable)
    return zip(a, a)


def may_change_leading_case(text):
    """
    Checks whether the string `text` can
    change the letter case of its leading letter.
    """
    for c in text:
        if c.isalpha():
            return True
        if c.isspace():
            continue
        return False
    return False


def iter_with(iterable, context_manager):
    """Iterate on `iterable`, `with`ing the context manager on every `next`."""
    while True:
        with context_manager:
            next_item = next(iterable)
        yield next_item


def get_adjusted_aspect(ax, aspect_ratio):
    """Adjust the aspect ratio

    Parameters
    ----------
    ax : :obj:`~matplotlib.axes.Axes`
       A :obj:`~matplotlib.axes.Axes` instance
    aspect_ratio : float
       The desired aspect ratio for :obj:`~matplotlib.axes.Axes`

    Returns
    -------
    float
       The required aspect ratio to achieve the desired one

    Warning
    -------
    This function only works for non-logarithmic axes.

    """
    default_ratio = (ax.get_xlim()[1] - ax.get_xlim()[0]) / (ax.get_ylim()[
        1] - ax.get_ylim()[0])
    return float(default_ratio * aspect_ratio)


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

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

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


def is_optional(sch, value=True):
    """Flag field as optional"""
    sch.is_optional = value
    return sch


def create_variant_to_protein_sequence_read_names_dict(isovar_results):
    """
    Create dictionary from variant to names of alt reads used to create
    mutant protein sequence in an IsovarResult.

    Parameters
    ----------
    isovar_results : list of IsovarResult

    Returns
    -------
    Dictionary from varcode.Variant to set(str) of read names
    """
    variant_to_read_names = {}
    for isovar_result in isovar_results:
        if isovar_result.has_mutant_protein_sequence_from_rna:
            protein_sequence = isovar_result.top_protein_sequence
            read_names = set(protein_sequence.
                read_names_supporting_protein_sequence)
        else:
            read_names = set()
        variant_to_read_names[isovar_result.variant] = read_names
    return variant_to_read_names


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


@staticmethod
def transform(obj):
    """ abstract function for converting value formats """
    raise NotImplementedError


def raw_json(item):
    """
    Returns the raw json output from the API.
    """
    return item


@classmethod
def get_by_pk(cls, pks, pk='id'):
    """ Get objects by primary key. Can return either a list or
            a single instance depending on if it is passed a list or not
            as input.
        """
    field = getattr(cls, pk)
    if isinstance(pks, list):
        result = cls.query.filter(field.in_(pks)).all()
    else:
        result = cls.query.filter(field == pks).one()
    return result


def apply_intersect(query, docids):
    """ Run the query implied by query, and return query results
        intersected with the ``docids`` set that is supplied.  If
        ``docids`` is None, return the bare query results. """


def DarkenBitmap(bmp, caption_colour, new_colour):
    """
    Darkens the input bitmap on wxMAC using the input colour.

    :param wx.Bitmap `bmp`: the bitmap to be manipulated;
    :param wx.Colour `caption_colour`: the colour of the pane caption;
    :param wx.Colour `new_colour`: the colour used to darken the bitmap.
    """
    image = bmp.ConvertToImage()
    red = caption_colour.Red() / float(new_colour.Red())
    green = caption_colour.Green() / float(new_colour.Green())
    blue = caption_colour.Blue() / float(new_colour.Blue())
    image = image.AdjustChannels(red, green, blue)
    return image.ConvertToBitmap()


def message_warning(msg, *a, **kwargs):
    """Ignore everything except the message."""
    return str(msg) + '\n'


def __new__(cls, sha, type, size, stream, *args, **kwargs):
    """Helps with the initialization of subclasses"""
    return tuple.__new__(cls, (sha, type, size, stream))


def make_initiator_target_all2all_map(initiator_wwpns, target_wwpns):
    """Build a simplistic all-to-all mapping."""
    i_t_map = {}
    for i_wwpn in initiator_wwpns:
        i_t_map[str(i_wwpn)] = []
        for t_wwpn in target_wwpns:
            i_t_map[i_wwpn].append(t_wwpn)
    return i_t_map


@staticmethod
def agreement_step(higherprobclass, labels):
    """Returns the agreement between predictions and true labels

        Agreements between predictions and labels are different based on
        different scenarios. This default implementation is the normal case
        where total number of correct predictions are divided by the total
        number of predictions. The function returns two values, one the
        nominator and the other denominator in order to generalise for all
        possible cases. This must be overridden if other kind of agreement
        is desired.

        :param higherprobclass: the predicted class
        :type higherprobclass: :class:`torch.Tensor`
        :param labels: ground truth labels
        :type labels: :class:`torch.Tensor`
        :return: tuple of tensors, nominator and denominator to compute the
            agreement
        """
    num_correct = (higherprobclass == labels).float().sum()
    num_total = labels.shape[0]
    return num_correct, num_total


def get_descendant_ids(cur, node):
    """
    Return an iterator that yields a ``NodeData`` object of each element
    in the nodes subtree. Be careful when converting this iterator to an
    iterable (like list or set) because it could contain billions of
    objects.

    :param node:
    :type node: Node or uuid4
    """
    sql = """
        SELECT
          node
        FROM
          ancestors
        WHERE
          ancestor=%s;
    """
    cur.execute(sql, (str(node),))
    for result in cur:
        yield str(result['node'])


@staticmethod
def _get_container_string(cont_dict, pid):
    """ Returns the nextflow containers string from a dictionary object

        If the dictionary has at least on of the container directives, these
        will be compiled for each process in the dictionary and returned
        as a string read for injection in the nextflow config file template.

        This dictionary should be::

            dict = {"processA": {"container": "asd", "version": "1.0.0"},
                    "processB": {"container": "dsd"}}

        Parameters
        ----------
        cont_dict : dict
            Dictionary with the containers for processes.
        pid : int
            Unique identified of the process

        Returns
        -------
        str
            nextflow config string
        """
    config_str = ''
    for p, directives in cont_dict.items():
        container = ''
        if 'container' in directives:
            container += directives['container']
            if 'version' in directives:
                container += ':{}'.format(directives['version'])
            else:
                container += ':latest'
        config_str += '\n\t${}_{}.container = "{}"'.format(p, pid, container)
    return config_str


def _split_comma_separated(string):
    """Return a set of strings."""
    return set(filter(None, string.split(',')))


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 authorize(token):
    """
    Authorizes the token and returns the object meant to be stored into g.user.

    Returns None if authorization failed, else the user object.

    You must monkey patch this method to make use of the View.
    """
    raise NotImplementedError()


def _np_min(a, axis=None, out=None, keepdims=False):
    """
    Return the minimum of an array or minimum along an axis.

    Parameters
    ----------
    a : ndarray
        Input data.
    axis : int, optional
        Axis along which to operate.  By default, flattened input is used.
    out : ndarray, optional
        Alternative output array in which to place the result.  Must
        be of the same shape and buffer length as the expected output.
        See `doc.ufuncs` (Section "Output arguments") for more details.
    keepdims : bool, optional
        If this is set to True, the axes which are reduced are left
        in the result as dimensions with size one. With this option,
        the result will broadcast correctly against the original `arr`.

    Returns
    -------
    min : ndarray
        Minimum of `a`. If `axis` is None, the result is an array of dimension 1.
        If `axis` is given, the result is an array of dimension
        ``a.ndim - 1``.

    See Also
    --------
    max :
        The maximum value of an array along a given axis, ignoring any nan.
    minimum :
        Element-wise minimum of two arrays, ignoring any nan.

    Notes
    -----
    NaN in the orginal `numpy` is denoted as nan and will be ignored.

    Don't use `min` for element-wise comparison of 2 arrays; when
    ``a.shape[0]`` is 2, ``minimum(a[0], a[1])`` is faster than
    ``min(a, axis=0)``.

    Examples
    --------
    >>> a = np.arange(4).reshape((2,2))
    >>> a
    array([[0., 1.],
        [2., 3.]])
    >>> np.min(a)           # Minimum of the flattened array
    array(0.)
    >>> np.min(a, axis=0)   # Minima along the first axis
    array([0., 1.])
    >>> np.min(a, axis=1)   # Minima along the second axis
    array([0., 2.])
    >>> b = np.arange(5, dtype=np.float32)
    >>> b[2] = np.nan
    >>> np.min(b)
    array(0.) # nan will be ignored
    """
    pass


def uch_yang(xy, d_pipe, gs, rhos, ut):
    """
    Provide functions to solve for voidage and choking velocity based on
    equations from Yang 1975. Requires SciPy fsolve function.

    Parameters
    ----------
    xy
        Solve for ep and uch using SciPy fsolve where
        ep = voidage [-] and uch = choking velocity [m/s]
    d_pipe : float
        Internal pipe diameter [m]
    gs : float
        Solids flux [kg/(s m^2)]
    rhos : float
        Density of particle [kg/m^3]
    ut : float
        Terminal velocity [m/s]

    Returns
    -------
    f1, f2 : fuctions
        Functions to solve for ep and uch

    References
    ----------
    Yang, 1975. A Mathematical Definition of Choking Phenomenon and a
    Mathematical Model for Predicting Choking Velocity and Choking Voidage.
    AIChE Journal, 21, 5, 1013-1015.
    """
    ep, uch = xy
    g = 9.81
    f1 = 2 * g * d_pipe * (ep ** -4.7 - 1) - 0.01 * (uch / ep - ut) ** 2
    f2 = gs - (uch / ep - ut) * rhos * (1 - ep)
    return f1, f2


@classmethod
def get_map(cls) ->dict:
    """
        Returns the map between JSON string and enum values.

        Returns
        -------
        dict
            The map.
        """
    return {'accuracy': cls.ACCURACY, 'f1': cls.F1, 'f1Micro': cls.F1_MICRO,
        'f1Macro': cls.F1_MACRO, 'rocAuc': cls.ROC_AUC, 'rocAucMicro': cls.
        ROC_AUC_MICRO, 'rocAucMacro': cls.ROC_AUC_MACRO, 'meanSquaredError':
        cls.MEAN_SQUARED_ERROR, 'rootMeanSquaredError': cls.
        ROOT_MEAN_SQUARED_ERROR, 'rootMeanSquaredErrorAvg': cls.
        ROOT_MEAN_SQUARED_ERROR_AVG, 'meanAbsoluteError': cls.
        MEAN_ABSOLUTE_ERROR, 'rSquared': cls.R_SQUARED,
        'normalizedMutualInformation': cls.NORMALIZED_MUTUAL_INFORMATION,
        'jaccardSimilarityScore': cls.JACCARD_SIMILARITY_SCORE}


def is_clone(g):
    """
    Return True if the generator `g` is a clone of another generator, otherwise return False.
    """
    return g.parent is not None


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

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


def find_next_path_down(current_path, path_to_reduce, separator):
    """
    Manipulate ``path_to_reduce`` so that it only contains one more level of
    detail than ``current_path``.

    :param current_path: The path used to determine the current level
    :type current_path: :class:`basestring`
    :param path_to_reduce: The path to find the next level down
    :type path_to_reduce: :class:`basestring`
    :param separator: The string used to separate the parts of path
    :type separator: :class:`basestring`
    :return: The path one level deeper than that of ``current_path``
    :rtype: :class:`unicode`

    """
    current_level = current_path.count(separator)
    next_level = current_level + 1
    return u'%s%s' % (separator.join(path_to_reduce.split(separator,
        next_level)[:next_level]), separator)


def check_evals_initialized(conn):
    """Check that evals table has been created in a sqlite3 database

    Parameters
    ----------
    conn : `sqlite3.Connection`
        connection to a sqlite3 database

    Returns
    -------
    is_created : `bool`
        `True` if table was created and `False` otherwise

    """
    cur = conn.execute(
        "SELECT name FROM sqlite_master WHERE type='table' AND name=?", (
        'evals',))
    return not cur.fetchone() is None


def pg_column_exists(conn, table, column):
    """
    Does a postgres object exist?
    :rtype bool
    """
    return conn.execute(
        """
                        SELECT 1 FROM pg_attribute
                        WHERE attrelid = to_regclass(%s)
                        AND attname = %s
                        AND NOT attisdropped
                        """
        , table, column).scalar() is not None


@classmethod
def unit_circle(cls):
    """
        Return the readonly :class:`Path` of the unit circle.

        For most cases, :func:`Path.circle` will be what you want.
        """
    if cls._unit_circle is None:
        cls._unit_circle = cls.circle(center=(0, 0), radius=1, readonly=True)
    return cls._unit_circle


def set_hostname(new_hostname, use_https=False):
    """Set the hostname for MusicBrainz webservice requests.
    Defaults to 'musicbrainz.org', accessing over https.
    For backwards compatibility, `use_https` is False by default.

    :param str new_hostname: The hostname (and port) of the MusicBrainz server to connect to
    :param bool use_https: `True` if the host should be accessed using https. Default is `False`

    Specify a non-standard port by adding it to the hostname,
    for example 'localhost:8000'."""
    global hostname
    global https
    hostname = new_hostname
    https = use_https


def export_element(doc, node):
    """Export the properties of the given element with the given
        element schema interface and append them to the given root node.
        Use the doc object to create new nodes.
        """


def forward(apps, schema_editor):
    """Empty forward method."""
    pass


def signum(x):
    """ Give info about the sign of the given int.

        :param int x: Value whose sign is asked
        :return: -1 if the given value is negative, 0 if it is null, 1 if it is positive
        :rtype: int
    """
    return -1 if x < 0 else 0 if x == 0 else 1


def preprocessing(settings):
    """Check all the settings."""
    replaces = settings.get('replaces', {})
    if not isinstance(replaces, dict):
        raise Exception('You must inform a valid replaces settings !')
    return settings


def _filter_non_json_lines(data):
    """
    Used to filter unrelated output around module JSON output, like messages from
    tcagetattr, or where dropbear spews MOTD on every single command (which is nuts).

    Filters leading lines before first line-starting occurrence of '{' or '[', and filter all
    trailing lines after matching close character (working from the bottom of output).
    """
    warnings = []
    lines = data.splitlines()
    for start, line in enumerate(lines):
        line = line.strip()
        if line.startswith(u'{'):
            endchar = u'}'
            break
        elif line.startswith(u'['):
            endchar = u']'
            break
    else:
        raise ValueError('No start of json char found')
    lines = lines[start:]
    for reverse_end_offset, line in enumerate(reversed(lines)):
        if line.strip().endswith(endchar):
            break
    else:
        raise ValueError('No end of json char found')
    if reverse_end_offset > 0:
        trailing_junk = lines[len(lines) - reverse_end_offset:]
        for line in trailing_junk:
            if line.strip():
                warnings.append(
                    'Module invocation had junk after the JSON data: %s' %
                    '\n'.join(trailing_junk))
                break
    lines = lines[:len(lines) - reverse_end_offset]
    return '\n'.join(lines), warnings


def error_views():
    """Return views of any errors.

        The errors are returned as an iterable.
        """


def _itemsize(t, item=0):
    """Get non-zero itemsize of type.
    """
    return getattr(t, '__itemsize__', 0) or item


def underline(s, symbol='='):
    """
    Add an underline to the string `s`.

    Parameters
    ----------
    s : str
        String to use for the title

    symbol : str
        Character to use for the underline
    """
    return '\n'.join([s, symbol * len(s)])


@classmethod
def _latest_partition_from_df(cls, df):
    """Hive partitions look like ds={partition name}"""
    return df.ix[:, (0)].max().split('=')[1]


def __and__(i1, i2):
    """ Return the intersection of i1 and i2
        """
    return i1.__class__(i1._intersection(i1, i2))


def getWidth():
    """ Display width of this video """


def _has_value(value, conf):
    """The value of an argument not passed in the command is *None*, except:
        * if **action** is ``store_true`` or ``store_false``: in this case, the
          value is respectively ``False`` and ``True``.
    This function take theses cases in consideration and check if an argument
    really has a value.
    """
    if value is None:
        return False
    action = conf.get('action', None)
    return (not action and value or action and action == 'store_true' and
        value or action and action == 'store_false' and not value)


def get_or_create(model, **kwargs):
    """ use it to get or create object from a table """
    instance = model.selectBy(**kwargs)
    if instance.count():
        return instance
    else:
        instance = model(**kwargs)
        return instance


def highlight():
    """Highlight selected file(s)

    """
    pass


@classmethod
def quote_identifier(cls, name):
    """Escape a name for valid use as an identifier.

        E.g. for SQLite::

            >>> engine.quote_identifier('hello world')
            '"hello world"'

        """
    return '"{}"'.format(name.replace('"', '""'))


def _expand_ellipsis(args, rank):
    """ Expand ellipsis objects and fill in missing axes.
    """
    n_el = sum(1 for arg in args if arg is Ellipsis)
    if n_el > 1:
        raise ValueError('Only one ellipsis may be used.')
    elif n_el == 0 and len(args) != rank:
        args = args + (Ellipsis,)
    final_args = []
    n_args = len(args)
    for arg in args:
        if arg is Ellipsis:
            final_args.extend((slice(None, None, None),) * (rank - n_args + 1))
        else:
            final_args.append(arg)
    if len(final_args) > rank:
        raise TypeError('Argument sequence too long')
    return final_args


def pairwise(iterable):
    """Return a generator which generate a pair wise list from an iterable: s -> (s[0],s[1]),
    (s[1],s[2]), ... (s[N-1], s[N]).

    """
    prev = iterable[0]
    for x in iterable[1:]:
        yield prev, x
        prev = x


def path_shift(script_name, path_info, shift=1):
    """ Shift path fragments from PATH_INFO to SCRIPT_NAME and vice versa.

        :return: The modified paths.
        :param script_name: The SCRIPT_NAME path.
        :param script_name: The PATH_INFO path.
        :param shift: The number of path fragments to shift. May be negative to
          change the shift direction. (default: 1)
    """
    if shift == 0:
        return script_name, path_info
    pathlist = path_info.strip('/').split('/')
    scriptlist = script_name.strip('/').split('/')
    if pathlist and pathlist[0] == '':
        pathlist = []
    if scriptlist and scriptlist[0] == '':
        scriptlist = []
    if shift > 0 and shift <= len(pathlist):
        moved = pathlist[:shift]
        scriptlist = scriptlist + moved
        pathlist = pathlist[shift:]
    elif shift < 0 and shift >= -len(scriptlist):
        moved = scriptlist[shift:]
        pathlist = moved + pathlist
        scriptlist = scriptlist[:shift]
    else:
        empty = 'SCRIPT_NAME' if shift < 0 else 'PATH_INFO'
        raise AssertionError('Cannot shift. Nothing left from %s' % empty)
    new_script_name = '/' + '/'.join(scriptlist)
    new_path_info = '/' + '/'.join(pathlist)
    if path_info.endswith('/') and pathlist:
        new_path_info += '/'
    return new_script_name, new_path_info


@classmethod
def find_registry(cls, id: str=None, name: str=None) ->'Registry':
    """Finds a registry based on either id or name.

        If neither is provided and there is only 1 registry, return the
        only registry.
        """
    if id:
        return cls.get(id)
    elif name:
        return cls.find_by_name(name)
    else:
        registries = cls.list()
        if len(registries) == 1:
            return registries[0]


@staticmethod
def setup_command_line(parser):
    """Setup the command line options for Ordering principle formula

        Arguments:
        - `parser`: parser to load with options.
        """
    parser.add_argument('N', metavar='<N>', type=int, help='domain size')
    g = parser.add_mutually_exclusive_group()
    g.add_argument('--total', '-t', default=False, action='store_true',
        help='assume a total order')
    g.add_argument('--smart', '-s', default=False, action='store_true',
        help="encode 'x<y' and 'x>y' in a single variable (implies totality)")
    g.add_argument('--knuth2', action='store_const', dest='knuth', const=2,
        help='transitivity axioms: "(i<j)(j<k)->(i,k)" only for j>i,k')
    g.add_argument('--knuth3', action='store_const', dest='knuth', const=3,
        help='transitivity axioms: "(i<j)(j<k)->(i,k)" only for k>i,j')
    parser.add_argument('--plant', '-p', default=False, action='store_true',
        help='allow a minimum element')


def add_jinja_extensions(app):
    """ Activate custom jinja extensions """
    from boiler.feature.jinja_extensions import jinja_extensions_feature
    jinja_extensions_feature(app)


def _to_degrees(value):
    """
    Helper function to convert the GPS coordinates stored in the EXIF to
    degrees in float format
    """
    degrees, minutes, seconds = value
    d = float(degrees[0]) / float(degrees[1])
    m = float(minutes[0]) / float(minutes[1])
    s = float(seconds[0]) / float(seconds[1])
    return d + m / 60.0 + s / 3600.0


def parse_metadata(section):
    """Given the first part of a slide, returns metadata associated with it."""
    metadata = {}
    metadata_lines = section.split('\n')
    for line in metadata_lines:
        colon_index = line.find(':')
        if colon_index != -1:
            key = line[:colon_index].strip()
            val = line[colon_index + 1:].strip()
            metadata[key] = val
    return metadata


@classmethod
def construct_from(cls, values, klass_name=None):
    """
        Creates an instance of the class from a dictionary

        :param values: Object returned by the API
        :type values: dict
        :param klass_name: Used from ListObject to convert the objects to the specified type.
        :type klass_name: str
        :return: instance
        :rtype: PianoObject
        """
    instance = cls(values.get(cls.id_map), klass_name=klass_name)
    instance.refresh_from(values, klass_name)
    return instance


def diffdict(new, old, inexistent_value=None):
    """Returns the differences between two dictionaries.
In case of addition or deletion, old or new values are set to inexistent_value.

:param new: first dictionary to compare.
:param old: second dictionary to compare.
:param inexistent_value: value used as old or new value for deletion or addition, defaults to None.
:returns: a list of the differences between the two dictionaries, like: [(key, new_value, old_value),...]
"""
    changes = []
    for key, val in old.items():
        new_val = new.get(key, Ellipsis)
        if new_val is Ellipsis:
            changes.append((key, inexistent_value, val))
        elif new_val != val:
            changes.append((key, new_val, val))
    for key, val in new.items():
        old_val = old.get(key, Ellipsis)
        if old_val is Ellipsis:
            changes.append((key, val, inexistent_value))
    return changes


def httpdate(dt):
    """Return a string representation of a date according to RFC 1123 (HTTP/1.1).

    The supplied date must be in UTC.

    :param dt: Datetime object in UTC.
    :type dt: datetime
    :rtype: str
    """
    weekday = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'][dt.weekday()]
    month = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
        'Oct', 'Nov', 'Dec'][dt.month - 1]
    return (
        '{weekday}, {dt.day:02d} {month} {dt.year:04d} {dt.hour:02d}:{dt.minute:02d}:{dt.second:02d} GMT'
        .format(weekday=weekday, month=month, dt=dt))


def psi_MgOH_Na_HCO3_HMW84(T, P):
    """c-c'-a: magnesium-hydroxide sodium bicarbonate [HMW84]."""
    psi = 0.0
    valid = T == 298.15
    return psi, valid


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

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

    Example::

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

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

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


def _get_embedding_layer_name_from_var(var):
    """Get name for ElasticDL embedding layer from variable."""
    if isinstance(var, str):
        return var
    return None


def announce(zelf, *args, **kwargs):
    """ announce on channels. """
    for channel in zelf.channels:
        zelf.say(channel, args[0])


@classmethod
def best(cls):
    """
        Choose the best CommandSpec class based on environmental conditions.
        """
    return cls


def latlong_to_locator(latitude, longitude):
    """converts WGS84 coordinates into the corresponding Maidenhead Locator

        Args:
            latitude (float): Latitude
            longitude (float): Longitude

        Returns:
            string: Maidenhead locator

        Raises:
            ValueError: When called with wrong or invalid input args
            TypeError: When args are non float values

        Example:
           The following example converts latitude and longitude into the Maidenhead locator

           >>> from pyhamtools.locator import latlong_to_locator
           >>> latitude = 48.5208333
           >>> longitude = 9.375
           >>> latlong_to_locator(latitude, longitude)
           'JN48QM'

        Note:
             Latitude (negative = West, positive = East)
             Longitude (negative = South, positive = North)

    """
    if longitude >= 180 or longitude <= -180:
        raise ValueError
    if latitude >= 90 or latitude <= -90:
        raise ValueError
    longitude += 180
    latitude += 90
    locator = chr(ord('A') + int(longitude / 20))
    locator += chr(ord('A') + int(latitude / 10))
    locator += chr(ord('0') + int(longitude % 20 / 2))
    locator += chr(ord('0') + int(latitude % 10))
    locator += chr(ord('A') + int((longitude - int(longitude / 2) * 2) / (2 /
        24)))
    locator += chr(ord('A') + int((latitude - int(latitude / 1) * 1) / (1 /
        24)))
    return locator


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

        :param EnabledDomainInvitesDetails val:
        :rtype: EventDetails
        """
    return cls('enabled_domain_invites_details', val)


def _floatable(item):
    """Check if an item can be intepreted with float()"""
    try:
        float(item)
        return True
    except ValueError:
        return False


def xyz_to_lab(x_val, y_val, z_val):
    """
    Convert XYZ color to CIE-Lab color.

    :arg float x_val: XYZ value of X.
    :arg float y_val: XYZ value of Y.
    :arg float z_val: XYZ value of Z.
    :returns: Tuple (L, a, b) representing CIE-Lab color
    :rtype: tuple

    D65/2° standard illuminant
    """
    xyz = []
    for val, ref in ((x_val, 95.047), (y_val, 100.0), (z_val, 108.883)):
        val /= ref
        if val > 0.008856:
            val = pow(val, 1 / 3.0)
        else:
            val = 7.787 * val + 16 / 116.0
        xyz.append(val)
    x_val, y_val, z_val = xyz
    cie_l = 116 * y_val - 16
    cie_a = 500 * (x_val - y_val)
    cie_b = 200 * (y_val - z_val)
    return cie_l, cie_a, cie_b


def getid(obj):
    """
    Abstracts the common pattern of allowing both an object or an object's ID
    as a parameter when dealing with relationships.
    """
    try:
        return obj.id
    except AttributeError:
        return obj


@staticmethod
def get_subtype(object_dictionary):
    """
        Given the hash representation of a subtype of this class,
        use the info in the hash to return the class of the subtype.
        """
    type = object_dictionary['attributeName']
    if type == 'SOURCE_VCN_ID':
        return 'SourceVcnIdCondition'
    if type == 'SOURCE_IP_ADDRESS':
        return 'SourceIpAddressCondition'
    if type == 'PATH':
        return 'PathMatchCondition'
    if type == 'SOURCE_VCN_IP_ADDRESS':
        return 'SourceVcnIpAddressCondition'
    else:
        return 'RuleCondition'


@classmethod
def global_config(cls, key, *args):
    """ This reads or sets the global settings stored in class.settings. """
    if args:
        cls.settings = cls.settings.copy()
        cls.settings[key] = args[0]
    else:
        return cls.settings[key]


def argsort(seq):
    """
    Generate the sorted arguments of a collection of values

    Parameters
    ----------
    seq : dict

    Returns
    -------
    list
        list of keys sorted by value
    """
    return sorted(range(len(seq)), key=seq.__getitem__)


@staticmethod
def get_addresses_model():
    """
        This is needed so the BaseConnector can validate the
        provided addresses and throw an error if any are missing.
        As well as automatically generate documentation.
        NOTE: types must always be "str"
        return = {
            'required_addresses': {
                'req_address_name_1': str,
                'req_address_name_2': str,
            },
            'optional_addresses': {
                'opt_address_name_1': str,
                'opt_address_name_2': str,
            },
        }
        """
    return {'required_addresses': {'requester': str}, 'optional_addresses': {}}


@classmethod
def create(cls, **kwargs):
    """Returns a new instance of the model (without saving it) with the attributes specified in ``kwargs``

        :returns: trigger -- a new local instance of the Trigger
        """
    return cls(**kwargs)


def _show_slicing(name, query, _print):
    """Show slicing objects"""
    objects = list(query)
    if objects:
        _print(name)
        for obj in objects:
            _print(str(obj), 1)


def version():
    """Show the version"""
    return 'echo version 0.2'


@classmethod
def _convert_to_font(cls, font_dict):
    """
        Convert ``font_dict`` to an openpyxl v2 Font object.

        Parameters
        ----------
        font_dict : dict
            A dict with zero or more of the following keys (or their synonyms).
                'name'
                'size' ('sz')
                'bold' ('b')
                'italic' ('i')
                'underline' ('u')
                'strikethrough' ('strike')
                'color'
                'vertAlign' ('vertalign')
                'charset'
                'scheme'
                'family'
                'outline'
                'shadow'
                'condense'

        Returns
        -------
        font : openpyxl.styles.Font
        """
    from openpyxl.styles import Font
    _font_key_map = {'sz': 'size', 'b': 'bold', 'i': 'italic', 'u':
        'underline', 'strike': 'strikethrough', 'vertalign': 'vertAlign'}
    font_kwargs = {}
    for k, v in font_dict.items():
        if k in _font_key_map:
            k = _font_key_map[k]
        if k == 'color':
            v = cls._convert_to_color(v)
        font_kwargs[k] = v
    return Font(**font_kwargs)


def p_function_call_parameter_list_empty(p):
    """function_call_parameter_list : empty"""
    p[0] = []


def unsubscribe(subscriber, type_name=None):
    """
        Unsubscribes 'subscriber.'  'subscriber' can any of the supported
        subscription types.
        """


def set_vault_access_policy(accountId=None, vaultName=None, policy=None):
    """
    This operation configures an access policy for a vault and will overwrite an existing policy. To configure a vault access policy, send a PUT request to the access-policy subresource of the vault. An access policy is specific to a vault and is also called a vault subresource. You can set one access policy per vault and the policy can be up to 20 KB in size. For more information about vault access policies, see Amazon Glacier Access Control with Vault Access Policies .
    See also: AWS API Documentation

    Examples
    The example configures an access policy for the vault named examplevault.
    Expected Output:

    :example: response = client.set_vault_access_policy(
        vaultName='string',
        policy={
            'Policy': 'string'
        }
    )

    :type accountId: string
    :param accountId: The AccountId value is the AWS account ID of the account that owns the vault. You can either specify an AWS account ID or optionally a single '- ' (hyphen), in which case Amazon Glacier uses the AWS account ID associated with the credentials used to sign the request. If you use an account ID, do not include any hyphens ('-') in the ID.
            Note: this parameter is set to '-' bydefault if no value is not specified.

    :type vaultName: string
    :param vaultName: [REQUIRED]
            The name of the vault.

    :type policy: dict
    :param policy: The vault access policy as a JSON string.
            Policy (string) --The vault access policy.

    :return: response = client.set_vault_access_policy(
        accountId='-',
        policy={
            'Policy': '{"Version":"2012-10-17","Statement":[{"Sid":"Define-owner-access-rights","Effect":"Allow","Principal":{"AWS":"arn:aws:iam::999999999999:root"},"Action":"glacier:DeleteArchive","Resource":"arn:aws:glacier:us-west-2:999999999999:vaults/examplevault"}]}',
        },
        vaultName='examplevault',
    )

    print(response)

    """
    pass


def dix_entiers_carre():
    """
    fait la somme des dix premiers entiers au carré

    :returns: nombre réel

    .. faqref::
        :tag: python
        :title: Quelle est la différence entre return et print ?

        La fonction ``print`` sert à afficher un résultat sur la sortie standard.
        Elle peut être utilisée à tout moment
        mais elle n'a pas d'impact sur le déroulement programme. Le mot-clé ``return``
        n'est utilisé que dans une fonction. Lorsque le programme rencontre
        une instruction commençant par ``return``, il quitte la fonction
        et transmet le résultat à l'instruction qui a appelé la fonction.
        La fonction ``print`` ne modifie pas votre algorithme. La fonction ``return``
        spécifie le résultat de votre fonction : elle modifie l'algorithme.

    .. exref::
        :title: calcul de la somme des dix premiers entiers au carré
        :tag: Base

        Ce calcul simple peut s'écrire de diffèrentes manières.

        ::

            s = 0
            for i in range(1,11):
                s += i**2

        D'une façon abrégée :

        ::

            s = sum ( [ i**2 for i in range(1,11) ] )
    """
    s = 0
    for i in range(1, 11):
        s += i ** 2
    return s


@classmethod
def all(cls, client):
    """Get all certificates."""
    response = client.api.certificates.get()
    certs = []
    for cert in response.json()['metadata']:
        fingerprint = cert.split('/')[-1]
        certs.append(cls(client, fingerprint=fingerprint))
    return certs