@staticmethod
def compare_results(save, best_hsp, tmp_results, tmp_gene_split):
    """
         Function for comparing hits and saving only the best hit
      """
    hit_id = best_hsp['hit_id']
    new_start_query = best_hsp['query_start']
    new_end_query = best_hsp['query_end']
    new_start_sbjct = int(best_hsp['sbjct_start'])
    new_end_sbjct = int(best_hsp['sbjct_end'])
    new_score = best_hsp['cal_score']
    new_db_hit = best_hsp['sbjct_header']
    new_contig = best_hsp['contig_name']
    new_HSP = best_hsp['HSP_length']
    keys = list(tmp_results.keys())
    for hit in keys:
        hit_data = tmp_results[hit]
        old_start_query = hit_data['query_start']
        old_end_query = hit_data['query_end']
        old_start_sbjct = int(hit_data['sbjct_start'])
        old_end_sbjct = int(hit_data['sbjct_end'])
        old_score = hit_data['cal_score']
        old_db_hit = hit_data['sbjct_header']
        old_contig = hit_data['contig_name']
        old_HSP = hit_data['HSP_length']
        remove_old = 0
        if new_db_hit == old_db_hit:
            if (new_start_sbjct < old_start_sbjct or new_end_sbjct >
                old_end_sbjct):
                tmp_gene_split[old_db_hit][hit_id] = 1
                if hit not in tmp_gene_split[old_db_hit]:
                    tmp_gene_split[old_db_hit][hit] = 1
            elif new_score > old_score:
                remove_old = 1
                if (new_db_hit in tmp_gene_split and hit_id not in
                    tmp_gene_split[new_db_hit]):
                    tmp_gene_split[new_db_hit][hit_id] = 1
            else:
                save = 0
                if hit_id != hit:
                    if (new_db_hit in tmp_gene_split and hit_id in
                        tmp_gene_split[new_db_hit]):
                        del tmp_gene_split[new_db_hit][hit_id]
                break
        if new_contig == old_contig:
            if (old_start_query == new_start_query and old_end_query ==
                new_end_query):
                if best_hsp['perc_ident'] > hit_data['perc_ident']:
                    remove_old = 1
                    if (new_db_hit in tmp_gene_split and hit_id not in
                        tmp_gene_split[new_db_hit]):
                        tmp_gene_split[new_db_hit][hit_id] = 1
                elif best_hsp['perc_ident'] == hit_data['perc_ident']:
                    if (new_db_hit in tmp_gene_split and hit_id not in
                        tmp_gene_split[new_db_hit]):
                        tmp_gene_split[new_db_hit][hit_id] = 1
                else:
                    save = 0
                    if (new_db_hit in tmp_gene_split and hit_id in
                        tmp_gene_split[new_db_hit]):
                        del tmp_gene_split[new_db_hit][hit_id]
                    break
            elif max(old_end_query, new_end_query) - min(old_start_query,
                new_start_query) <= old_end_query - old_start_query + (
                new_end_query - new_start_query):
                if new_score > old_score:
                    remove_old = 1
                    if (new_db_hit in tmp_gene_split and hit_id not in
                        tmp_gene_split[new_db_hit]):
                        tmp_gene_split[new_db_hit][hit_id] = 1
                elif new_score == old_score:
                    if int(best_hsp['perc_coverage']) == 100 and int(hit_data
                        ['perc_coverage']) == 100 and new_HSP > old_HSP:
                        remove_old = 1
                    if (new_db_hit in tmp_gene_split and hit_id not in
                        tmp_gene_split[new_db_hit]):
                        tmp_gene_split[new_db_hit][hit_id] = 1
                else:
                    if (new_db_hit in tmp_gene_split and hit_id in
                        tmp_gene_split[new_db_hit]):
                        del tmp_gene_split[new_db_hit][hit_id]
                    save = 0
                    break
        if remove_old == 1:
            del tmp_results[hit]
            if old_db_hit in tmp_gene_split and hit in tmp_gene_split[
                old_db_hit]:
                del tmp_gene_split[old_db_hit][hit]
    return save, tmp_gene_split, tmp_results


def get_func_definition(sourcelines):
    """Given a block of source lines for a method or function,
    get the lines for the function block.
    """
    count = 1
    for line in sourcelines:
        if line.rstrip().endswith(':'):
            break
        count += 1
    return sourcelines[:count], sourcelines[count:]


def extract_tarball(src, dest):
    """extract a .tar file"""
    import tarfile
    with tarfile.open(src) as bundle:
        namelist = []
        for m in bundle:
            bundle.extract(m, path=dest)
            namelist.append(m.name)
    return namelist


def nii_ones_like(in_file, value, dtype, newpath=None):
    """Create a NIfTI file filled with ``value``, matching properties of ``in_file``"""
    import os
    import numpy as np
    import nibabel as nb
    nii = nb.load(in_file)
    data = np.ones(nii.shape, dtype=float) * value
    out_file = os.path.join(newpath or os.getcwd(), 'filled.nii.gz')
    nii = nb.Nifti1Image(data, nii.affine, nii.header)
    nii.set_data_dtype(dtype)
    nii.to_filename(out_file)
    return out_file


def calculate_score_insertion(main_score, translocation_distances,
    translocation_stds, destination_stds):
    """Calculate the score of a merged insertion or duplication detected from an insertion.
       Parameters: - main_score - score of the underlying main insertion
                   - translocation_distances - mean distance of the translocation clusters flanking the main insertion (left)
                   - translocation_stds - standard deviation of the translocation clusters flanking the main insertion (left)
                   - destination_stds - standard deviations of the left and right translocation destinations"""
    td0 = max(0, 100 - translocation_distances[0]) / 100
    td1 = max(0, 100 - translocation_distances[1]) / 100
    ts0 = max(0, 100 - translocation_stds[0]) / 100
    ts1 = max(0, 100 - translocation_stds[1]) / 100
    ds0 = max(0, 100 - destination_stds[0]) / 100
    ds1 = max(0, 100 - destination_stds[1]) / 100
    product = td0 * td1 * ts0 * ts1 * ds0 * ds1
    final_score = pow(product, 1 / 6) * main_score
    return final_score


def gen_child_count(dx_nodes, child_cnt, *dx_node_types):
    """
    Generator for dx_nodes of a certain type and a specific number of children

    :param dx_nodes: [DiffxNode, DiffxNode, .. ]
    :param child_cnt: int - number of children
    """
    for _dx_node in dx_nodes:
        if _dx_node.child_cnt == child_cnt:
            if isinstance(_dx_node.type, dx_node_types):
                yield _dx_node


def print_setup_instructions():
    """
    Prints the setup instructions for the .pgpass file required to access wrds via python.
    """
    print(
        """To build a connection to the wrds server via python, a .pgpass file is required in the user's home
directory, with access limited to the user.
To create this file, follow the instructions here:
https://wrds-www.wharton.upenn.edu/pages/support/programming-wrds/programming-python/python-from-your-computer/
After creating the file, don't forget to run "chmod 0600 ~/.pgpass" in the console to limit access.
Access issue also described here:
https://www.postgresql.org/docs/9.5/libpq-pgpass.html"""
        )


def _fmt_metric(value, show_stdv=True):
    """format metric string"""
    if len(value) == 2:
        return '{0}:{1:.5f}'.format(value[0], value[1])
    if len(value) == 3:
        if show_stdv:
            return '{0}:{1:.5f}+{2:.5f}'.format(value[0], value[1], value[2])
        return '{0}:{1:.5f}'.format(value[0], value[1])
    raise ValueError('wrong metric value')


def public_modules(path):
    """Yield all the paths to public modules in a given directory."""
    for entry in path.iterdir():
        if entry.name.startswith('_'):
            continue
        if entry.is_dir() or entry.is_file() and entry.suffix == '.py':
            yield entry


def make_tensor_5d(t):
    """Extends a tensor or numpy array to have exactly 5 dimensions.

    In doing so, it interprets 1d tensors as being aligned
    in time, 2d tensors to be aligned in space, etc.

        - 1d: t[None,None,:,None,None]
        - 2d: t[None,None,None,:,:]
        - 3d: t[None,None,:,:,:]
        - 4d: t[None,:,:,:,:]
        - 5d: t
        - 6d and more: selects the first element of t until t has 5 dimensions

    """
    if type(t.shape) is tuple:
        if len(t.shape) > 5:
            while len(t.shape) > 5:
                t = t[0]
        if len(t.shape) == 4:
            t = t[None]
        if len(t.shape) == 3:
            t = t[None, None]
        if len(t.shape) == 2:
            t = t[None, None, None]
        if len(t.shape) == 1:
            t = t[(None), (None), :, (None), (None)]
        return t
    else:
        if len(t.size()) > 5:
            while len(t.shape) > 5:
                t = t[0]
        if len(t.size()) == 4:
            t = t[None]
        if len(t.size()) == 3:
            t = t[None, None]
        if len(t.size()) == 2:
            t = t[None, None, None]
        if len(t.size()) == 1:
            t = t[(None), (None), :, (None), (None)]
        return t


def run(cli_args):
    """
    Split the functionality into 2 methods.

    One for parsing the cli and one that runs the application.
    """
    from .core import Core
    c = Core(source_file=cli_args['--data-file'], schema_files=cli_args[
        '--schema-file'], extensions=cli_args['--extension'],
        strict_rule_validation=cli_args['--strict-rule-validation'],
        fix_ruby_style_regex=cli_args['--fix-ruby-style-regex'],
        allow_assertions=cli_args['--allow-assertions'])
    c.validate()
    return c


def _SI(size, K=1024, i='i'):
    """Return size as SI string.
    """
    if 1 < K <= size:
        f = float(size)
        for si in iter('KMGPTE'):
            f /= K
            if f < K:
                return ' or %.1f %s%sB' % (f, si, i)
    return ''


def clitable_to_dict(cli_table):
    """Converts TextFSM cli_table object to list of dictionaries."""
    objs = []
    for row in cli_table:
        temp_dict = {}
        for index, element in enumerate(row):
            temp_dict[cli_table.header[index].lower()] = element
        objs.append(temp_dict)
    return objs


def open(isolation=None, deferrable=False, read_only=False,
    replica_selector=None, application_name=None, **kwargs):
    """Open a database connection and return (conn, cursor)."""


def display_error(context, message):
    """
        function display_error
    """
    print('=' * 80)
    print('({0}) {1}'.format(context, message))
    print('=' * 80)


def get_instance_id_to_name_map(instance_info):
    """generate instance_id to instance_name map.  If an instance has no name it will have value 'unknown'."""
    instance_id_to_name = {}
    for instance_id in instance_info:
        instance = instance_info[instance_id]
        instance_name = 'unnamed'
        if 'Tags' in instance:
            for tag in instance['Tags']:
                if tag['Key'] == 'Name':
                    instance_name = tag['Value']
        instance_id_to_name[instance['InstanceId']] = instance_name
    return instance_id_to_name


def cumulative_distribution(distribution):
    """Returns normalized cumulative distribution from discrete distribution."""
    cdf = [0.0]
    psum = float(sum(distribution))
    for i in range(0, len(distribution)):
        cdf.append(cdf[i] + distribution[i] / psum)
    return cdf


def _setf_(flags, flag):
    """
     sets flag, adding to flags
     :param flags: current flag value
     :param flag: flag to set
     :return: new flag value
    """
    return flags | flag


def state_move_down():
    """Move boid state down in the list

    """
    pass


def normalize_url(url: str) ->str:
    """
    Remove leading and trailing slashes from a URL

    :param url: URL
    :return: URL with no leading and trailing slashes

    :private:
    """
    if url.startswith('/'):
        url = url[1:]
    if url.endswith('/'):
        url = url[:-1]
    return url


def describe_launch_configurations(LaunchConfigurationNames=None, NextToken
    =None, MaxRecords=None):
    """
    Describes one or more launch configurations.
    See also: AWS API Documentation

    Examples
    This example describes the specified launch configuration.
    Expected Output:

    :example: response = client.describe_launch_configurations(
        LaunchConfigurationNames=[
            'string',
        ],
        NextToken='string',
        MaxRecords=123
    )

    :type LaunchConfigurationNames: list
    :param LaunchConfigurationNames: The launch configuration names. If you omit this parameter, all launch configurations are described.
            (string) --

    :type NextToken: string
    :param NextToken: The token for the next set of items to return. (You received this token from a previous call.)

    :type MaxRecords: integer
    :param MaxRecords: The maximum number of items to return with this call. The default value is 50 and the maximum value is 100.

    :rtype: dict
    :return: {
        'LaunchConfigurations': [
            {
                'LaunchConfigurationName': 'string',
                'LaunchConfigurationARN': 'string',
                'ImageId': 'string',
                'KeyName': 'string',
                'SecurityGroups': [
                    'string',
                ],
                'ClassicLinkVPCId': 'string',
                'ClassicLinkVPCSecurityGroups': [
                    'string',
                ],
                'UserData': 'string',
                'InstanceType': 'string',
                'KernelId': 'string',
                'RamdiskId': 'string',
                'BlockDeviceMappings': [
                    {
                        'VirtualName': 'string',
                        'DeviceName': 'string',
                        'Ebs': {
                            'SnapshotId': 'string',
                            'VolumeSize': 123,
                            'VolumeType': 'string',
                            'DeleteOnTermination': True|False,
                            'Iops': 123,
                            'Encrypted': True|False
                        },
                        'NoDevice': True|False
                    },
                ],
                'InstanceMonitoring': {
                    'Enabled': True|False
                },
                'SpotPrice': 'string',
                'IamInstanceProfile': 'string',
                'CreatedTime': datetime(2015, 1, 1),
                'EbsOptimized': True|False,
                'AssociatePublicIpAddress': True|False,
                'PlacementTenancy': 'string'
            },
        ],
        'NextToken': 'string'
    }

    :returns:
    (string) --

    """
    pass


def conjunctive_partition(formula):
    """ Returns a generator over the top-level conjuncts of the given formula

    The result is such that for every formula phi, the following holds:
    phi <-> And(conjunctive_partition(phi))
    """
    to_process = [formula]
    seen = set()
    while to_process:
        cur = to_process.pop()
        if cur not in seen:
            seen.add(cur)
            if cur.is_and():
                to_process += cur.args()
            else:
                yield cur


def encrypted(func):
    """make sure data transmissions are encrypted"""
    return func


def url(request):
    """called from the template for the download page."""


def _has_instance(cls):
    """
        gets a value indicating that there is a registered instance.

        :rtype: bool
        """
    return cls._instance is not None


def _write(fobj, data):
    """Write data to file."""
    fobj.write(data)


def analyze_cigar_indel(tuples, min_length):
    """Parses CIGAR tuples (op, len) and returns Indels with a length > minLength"""
    pos_ref = 0
    pos_read = 0
    indels = []
    for operation, length in tuples:
        if operation == 0:
            pos_ref += length
            pos_read += length
        elif operation == 1:
            if length >= min_length:
                indels.append((pos_ref, pos_read, length, 'INS'))
            pos_read += length
        elif operation == 2:
            if length >= min_length:
                indels.append((pos_ref, pos_read, length, 'DEL'))
            pos_ref += length
        elif operation == 4:
            pos_read += length
        elif operation == 7 or operation == 8:
            pos_ref += length
            pos_read += length
    return indels


@classmethod
def _create_meters_by_bits(cls, figure, data_by_year, shifts, bits):
    """Meters passed by one average bit."""
    met_by_bit = figure.add_subplot(223)
    meters_by_bits1 = data_by_year[shifts[0]].meters / bits[0]
    meters_by_bits2 = data_by_year[shifts[1]].meters / bits[1]
    met_by_bit.plot(data_by_year[shifts[0]].month, meters_by_bits1, marker=
        'D', markersize=4)
    met_by_bit.plot(data_by_year[shifts[1]].month, meters_by_bits2, marker=
        'D', markersize=4)
    met_by_bit.legend(['Смена 1', 'Смена 2'])
    met_by_bit.set_ylabel('метров / коронку')
    met_by_bit.set_xlabel('месяцы')
    met_by_bit.grid(b=True, linestyle='--', linewidth=0.5)
    met_by_bit.set_title('Проход одной коронки.')


def is_forking(argv):
    """
    Return whether commandline indicates we are forking
    """
    if len(argv) >= 2 and argv[1] == '--multiprocessing-fork':
        return True
    else:
        return False


def grab_clone(delta: float=(0.0, 0.0)):
    """Move the clone source image

    :param delta: Delta, Delta offset of clone image in 0.0..1.0 coordinates
    :type delta: float
    """
    pass


def print_report(result_in):
    """Print time code, title, url and tags."""
    if result_in[0]:
        print('Time Codes: ' + ' '.join(result_in[0][:]))
    if result_in[1]:
        print('Titles: ' + ' '.join(result_in[1]))
    if result_in[2]:
        print('YouTube URL: ' + result_in[2])
    if result_in[3]:
        print('Tags: ' + ' '.join(result_in[3]))


@classmethod
def _ovalcheck(location, oval_id):
    """
        Perform an OVAL check.

        :param string location: URI of an OVAL definitions file
        :param string oval_id: OVAL definition ID
        :rtype: boolean
        :exception: NotImplementedError - Method not implemented
        """
    errmsg = 'Method not implemented'
    raise NotImplementedError(errmsg)


def change_angle_origin(angles, max_positive_angle):
    """
    Angles in DICOM are all positive values, but there is typically no mechanical continuity in across 180 degrees
    :param angles: angles to be converted
    :type angles list
    :param max_positive_angle: the maximum positive angle, angles greater than this will be shifted to negative angles
    :return: list of the same angles, but none exceed the max
    :rtype: list
    """
    if len(angles) == 1:
        if angles[0] > max_positive_angle:
            return [angles[0] - 360]
        else:
            return angles
    new_angles = []
    for angle in angles:
        if angle > max_positive_angle:
            new_angles.append(angle - 360)
        elif angle == max_positive_angle:
            if angle == angles[0] and angles[1] > max_positive_angle:
                new_angles.append(angle - 360)
            elif angle == angles[-1] and angles[-2] > max_positive_angle:
                new_angles.append(angle - 360)
            else:
                new_angles.append(angle)
        else:
            new_angles.append(angle)
    return new_angles


def open_for_load():
    """
        Open a connection for loading objects.

        This connection is read only, and presents a consistent view
        of the database as of the time the first statement is
        executed. It should be opened in ``REPEATABLE READ`` or higher
        isolation level. It must not be in autocommit.

        :return: ``(conn, cursor)``
        """


@classmethod
def all(cls) ->'QuerySet<Meta.Model>':
    """
        Shortcut for get all entity from model
        return: QuerySet<Model>
        """
    return cls.Meta.model.objects.all()


@staticmethod
def to_lcs_action(env_action):
    """
        Converts environment representation of an action to LCS
        representation.
        """
    return env_action


@staticmethod
def addIfValid(sumV, toAdd):
    """
        return the sum of the two given parameters (or None if the case)
        """
    if toAdd is None:
        return sumV
    if sumV is None:
        return toAdd
    return sumV + toAdd


def list_outgoing_typed_links(DirectoryArn=None, ObjectReference=None,
    FilterAttributeRanges=None, FilterTypedLink=None, NextToken=None,
    MaxResults=None, ConsistencyLevel=None):
    """
    Returns a paginated list of all the outgoing  TypedLinkSpecifier information for an object. It also supports filtering by typed link facet and identity attributes. For more information, see Typed link .
    See also: AWS API Documentation

    :example: response = client.list_outgoing_typed_links(
        DirectoryArn='string',
        ObjectReference={
            'Selector': 'string'
        },
        FilterAttributeRanges=[
            {
                'AttributeName': 'string',
                'Range': {
                    'StartMode': 'FIRST'|'LAST'|'LAST_BEFORE_MISSING_VALUES'|'INCLUSIVE'|'EXCLUSIVE',
                    'StartValue': {
                        'StringValue': 'string',
                        'BinaryValue': b'bytes',
                        'BooleanValue': True|False,
                        'NumberValue': 'string',
                        'DatetimeValue': datetime(2015, 1, 1)
                    },
                    'EndMode': 'FIRST'|'LAST'|'LAST_BEFORE_MISSING_VALUES'|'INCLUSIVE'|'EXCLUSIVE',
                    'EndValue': {
                        'StringValue': 'string',
                        'BinaryValue': b'bytes',
                        'BooleanValue': True|False,
                        'NumberValue': 'string',
                        'DatetimeValue': datetime(2015, 1, 1)
                    }
                }
            },
        ],
        FilterTypedLink={
            'SchemaArn': 'string',
            'TypedLinkName': 'string'
        },
        NextToken='string',
        MaxResults=123,
        ConsistencyLevel='SERIALIZABLE'|'EVENTUAL'
    )

    :type DirectoryArn: string
    :param DirectoryArn: [REQUIRED]
            The Amazon Resource Name (ARN) of the directory where you want to list the typed links.

    :type ObjectReference: dict
    :param ObjectReference: [REQUIRED]
            A reference that identifies the object whose attributes will be listed.
            Selector (string) --A path selector supports easy selection of an object by the parent/child links leading to it from the directory root. Use the link names from each parent/child link to construct the path. Path selectors start with a slash (/) and link names are separated by slashes. For more information about paths, see Accessing Objects . You can identify an object in one of the following ways:
            $ObjectIdentifier - An object identifier is an opaque string provided by Amazon Cloud Directory. When creating objects, the system will provide you with the identifier of the created object. An object s identifier is immutable and no two objects will ever share the same object identifier
            /some/path - Identifies the object based on path
            #SomeBatchReference - Identifies the object in a batch call

    :type FilterAttributeRanges: list
    :param FilterAttributeRanges: Provides range filters for multiple attributes. When providing ranges to typed link selection, any inexact ranges must be specified at the end. Any attributes that do not have a range specified are presumed to match the entire range.
            (dict) --Identifies the range of attributes that are used by a specified filter.
            AttributeName (string) --The unique name of the typed link attribute.
            Range (dict) -- [REQUIRED]The range of attribute values that are being selected.
            StartMode (string) -- [REQUIRED]The inclusive or exclusive range start.
            StartValue (dict) --The value to start the range at.
            StringValue (string) --A string data value.
            BinaryValue (bytes) --A binary data value.
            BooleanValue (boolean) --A Boolean data value.
            NumberValue (string) --A number data value.
            DatetimeValue (datetime) --A date and time value.
            EndMode (string) -- [REQUIRED]The inclusive or exclusive range end.
            EndValue (dict) --The attribute value to terminate the range at.
            StringValue (string) --A string data value.
            BinaryValue (bytes) --A binary data value.
            BooleanValue (boolean) --A Boolean data value.
            NumberValue (string) --A number data value.
            DatetimeValue (datetime) --A date and time value.

    :type FilterTypedLink: dict
    :param FilterTypedLink: Filters are interpreted in the order of the attributes defined on the typed link facet, not the order they are supplied to any API calls.
            SchemaArn (string) -- [REQUIRED]The Amazon Resource Name (ARN) that is associated with the schema. For more information, see arns .
            TypedLinkName (string) -- [REQUIRED]The unique name of the typed link facet.

    :type NextToken: string
    :param NextToken: The pagination token.

    :type MaxResults: integer
    :param MaxResults: The maximum number of results to retrieve.

    :type ConsistencyLevel: string
    :param ConsistencyLevel: The consistency level to execute the request at.

    :rtype: dict
    :return: {
        'TypedLinkSpecifiers': [
            {
                'TypedLinkFacet': {
                    'SchemaArn': 'string',
                    'TypedLinkName': 'string'
                },
                'SourceObjectReference': {
                    'Selector': 'string'
                },
                'TargetObjectReference': {
                    'Selector': 'string'
                },
                'IdentityAttributeValues': [
                    {
                        'AttributeName': 'string',
                        'Value': {
                            'StringValue': 'string',
                            'BinaryValue': b'bytes',
                            'BooleanValue': True|False,
                            'NumberValue': 'string',
                            'DatetimeValue': datetime(2015, 1, 1)
                        }
                    },
                ]
            },
        ],
        'NextToken': 'string'
    }

    :returns:
    $ObjectIdentifier - An object identifier is an opaque string provided by Amazon Cloud Directory. When creating objects, the system will provide you with the identifier of the created object. An objects identifier is immutable and no two objects will ever share the same object identifier
    /some/path - Identifies the object based on path
    #SomeBatchReference - Identifies the object in a batch call

    """
    pass


def map_to_docs(solr_response):
    """
    Response mapper that only returns the list of result documents.
    """
    return solr_response['response']['docs']


@classmethod
def list_all_scenario_types(scenario_cls):
    """Lists all the tests in all scenarios."""
    scenarios = scenario_cls.list_all_scenarios()
    scenario_dict = {}
    for scenario in scenarios:
        testype, test = scenario.split('.')
        if testype in scenario_dict:
            scenario_dict[testype].append(test)
        else:
            scenario_dict[testype] = []
            scenario_dict[testype].append(test)
    return scenario_dict


def value_to_fortran(value):
    """Return a Python compatible version of a FORTRAN argument.

    Parameters
    ----------
    value : bool | int | float | str
        A Python friendly representation of the input value.

    Returns
    -------
    fortran_value : str
        A FORTRAN argument.
    """
    if isinstance(value, bool):
        fortran_value = '.{}.'.format(str(value).lower())
    elif isinstance(value, float):
        fortran_value = str(value)
        if 'e' not in fortran_value:
            fortran_value += 'd0'
    return fortran_value


def readdelta(shallow=False):
    """Obtain the manifest data structure representing changes from parent.

        This manifest is compared to its 1st parent. A new manifest representing
        those differences is constructed.

        The returned object conforms to the ``imanifestdict`` interface.
        """


def matrix_scalar(m, sc):
    """ Matrix multiplication by a scalar value (iterative algorithm).

    The running time of the iterative matrix multiplication algorithm is :math:`O(n^{2})`.

    :param m: input matrix
    :type m: list, tuple
    :param sc: scalar value
    :type sc: int, float
    :return: resultant matrix
    :rtype: list
    """
    mm = [[(0.0) for _ in range(len(m[0]))] for _ in range(len(m))]
    for i in range(len(m)):
        for j in range(len(m[0])):
            mm[i][j] = float(m[i][j] * sc)
    return mm


def _format_return_message(results):
    """
    Formats and eliminates redundant return messages from a failed geocoding result.
    :param results: the returned dictionary from Geoclient API of a failed geocode.
    :return: Formatted Geoclient return messages
    """
    out_message = None
    if 'message' in results:
        out_message = results['message']
    if 'message2' in results:
        if out_message:
            if out_message != results['message2']:
                out_message = '{} {}'.format(out_message, results['message2'])
        else:
            return results['message2']
    return out_message


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


def render_pep440_bare(pieces):
    """TAG[.DISTANCE[.dev0]] .

    The ".dev0" means dirty.

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


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


def createMainWidget(argv):
    """
    Function to create the main widget.

    @param argv list of commandline parameters (list of strings)
    @return reference to the main widget (QWidget)
    """
    from PluginManager.PluginUninstallDialog import PluginUninstallWindow
    return PluginUninstallWindow()


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

        :param SharedFolderMemberError val:
        :rtype: RemoveFolderMemberError
        """
    return cls('member_error', val)


@classmethod
def _get_run_breadcrumbs(cls, source_type, data_object, task_attempt):
    """Create a path for a given file, in such a way
        that files end up being organized and browsable by run
        """
    if not task_attempt:
        return []
    task = task_attempt.tasks.earliest('datetime_created')
    if task is None:
        return []
    run = task.run
    if run is None:
        return []
    breadcrumbs = [run.name, 'task-%s' % str(task.uuid)[0:8], 'attempt-%s' %
        str(task_attempt.uuid)[0:8]]
    while run.parent is not None:
        run = run.parent
        breadcrumbs = [run.name] + breadcrumbs
    breadcrumbs[0] = '%s-%s-%s' % (run.datetime_created.strftime(
        '%Y-%m-%dT%H.%M.%SZ'), str(run.uuid)[0:8], breadcrumbs[0])
    breadcrumbs = ['runs'] + breadcrumbs
    return breadcrumbs


def _printf_s_to_format_field(printf_string, format_field):
    """Tries to replace %s with {format_field} in the provided printf_string.
    Raises ValueError in case of failure.
    """
    TEST_STRING = 'PELICAN_PRINTF_S_DEPRECATION'
    expected = printf_string % TEST_STRING
    result = printf_string.replace('{', '{{').replace('}', '}}'
        ) % '{{{}}}'.format(format_field)
    if result.format(**{format_field: TEST_STRING}) != expected:
        raise ValueError('Failed to safely replace %s with {{{}}}'.format(
            format_field))
    return result


@classmethod
def get_version(cls):
    """Get the current version as a tuple."""
    if not cls.table_exists():
        return 0, 0
    return cls.get(part='major').value, cls.get(part='minor').value


def next():
    """Return the next message.

        It should return a Deferred which will get fired when there is a new
        project that needs to run, or already fired if there was a project
        waiting to run already.

        The message is a dict containing (at least):
        * the name of the project to be run in the '_project' key
        * the name of the spider to be run in the '_spider' key
        * a unique identifier for this run in the `_job` key
        This message will be passed later to IEnvironment.get_environment().
        """


def shutdown_gateway(GatewayARN=None):
    """
    Shuts down a gateway. To specify which gateway to shut down, use the Amazon Resource Name (ARN) of the gateway in the body of your request.
    The operation shuts down the gateway service component running in the gateway's virtual machine (VM) and not the host VM.
    After the gateway is shutdown, you cannot call any other API except  StartGateway ,  DescribeGatewayInformation , and  ListGateways . For more information, see  ActivateGateway . Your applications cannot read from or write to the gateway's storage volumes, and there are no snapshots taken.
    If do not intend to use the gateway again, you must delete the gateway (using  DeleteGateway ) to no longer pay software charges associated with the gateway.
    See also: AWS API Documentation

    Examples
    This operation shuts down the gateway service component running in the storage gateway's virtual machine (VM) and not the VM.
    Expected Output:

    :example: response = client.shutdown_gateway(
        GatewayARN='string'
    )

    :type GatewayARN: string
    :param GatewayARN: [REQUIRED]
            The Amazon Resource Name (ARN) of the gateway. Use the ListGateways operation to return a list of gateways for your account and region.

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

    """
    pass


@classmethod
def __replace(cls, string):
    """ replaces characters not allowed in xml string

        :param string: text
        :type string: :obj:`str`
        :returns: converted text with special characters
        :rtype: :obj:`str`
        """
    return string.replace('&', '&').replace('<', '<').replace('>',
        '>')


def calculate_unladen_mass(curb_mass, fuel_mass):
    """
    Calculate unladen mass [kg].

    :param curb_mass:
        Curb mass [kg].
    :type curb_mass: float

    :param fuel_mass:
        Fuel mass [kg].
    :type fuel_mass: float

    :return:
        Unladen mass [kg].
    :rtype: float
    """
    return curb_mass + fuel_mass


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 __call__(form, action):
    """Execute the handler."""


@staticmethod
def _unmarshal_parts(pkg_reader, package, part_factory):
    """
        Return a dictionary of |Part| instances unmarshalled from
        *pkg_reader*, keyed by partname. Side-effect is that each part in
        *pkg_reader* is constructed using *part_factory*.
        """
    parts = {}
    for partname, content_type, reltype, blob in pkg_reader.iter_sparts():
        parts[partname] = part_factory(partname, content_type, reltype,
            blob, package)
    return parts


def perm(event):
    """ add/change permissions of an user. """
    from bot.space import fleet, users
    if not users.allowed(event.origin, 'OPER'):
        event.reply('you are not allowed to give the perm command.')
        return
    try:
        nick, perms = event._parsed.args
    except:
        event.reply('perm <origin> <perm>')
        return
    origin = fleet.get_origin(nick)
    user = users.set(origin, perms)
    if not user:
        event.reply("can't find a user matching %s" % origin)
        return
    event.reply(slice(user, skip=['type']))


def split_lines(lines):
    """
    split a MagIC upload format file into lists.
    the lists are split by the '>>>' lines between file_types.
    """
    container = []
    new_list = []
    for line in lines:
        if '>>>' in line:
            container.append(new_list)
            new_list = []
        else:
            new_list.append(line)
    container.append(new_list)
    return container


def im_func(method):
    """ Gets the function from the method in both Python 2 and 3. """
    return getattr(method, 'im_func', method)


def get_function(FunctionName=None, Qualifier=None):
    """
    Returns the configuration information of the Lambda function and a presigned URL link to the .zip file you uploaded with  CreateFunction so you can download the .zip file. Note that the URL is valid for up to 10 minutes. The configuration information is the same information you provided as parameters when uploading the function.
    Using the optional Qualifier parameter, you can specify a specific function version for which you want this information. If you don't specify this parameter, the API uses unqualified function ARN which return information about the $LATEST version of the Lambda function. For more information, see AWS Lambda Function Versioning and Aliases .
    This operation requires permission for the lambda:GetFunction action.
    See also: AWS API Documentation

    Examples
    This operation retrieves a Lambda function's event source mapping
    Expected Output:

    :example: response = client.get_function(
        FunctionName='string',
        Qualifier='string'
    )

    :type FunctionName: string
    :param FunctionName: [REQUIRED]
            The Lambda function name.
            You can specify a function name (for example, Thumbnail ) or you can specify Amazon Resource Name (ARN) of the function (for example, arn:aws:lambda:us-west-2:account-id:function:ThumbNail ). AWS Lambda also allows you to specify a partial ARN (for example, account-id:Thumbnail ). Note that the length constraint applies only to the ARN. If you specify only the function name, it is limited to 64 characters in length.

    :type Qualifier: string
    :param Qualifier: Using this optional parameter to specify a function version or an alias name. If you specify function version, the API uses qualified function ARN for the request and returns information about the specific Lambda function version. If you specify an alias name, the API uses the alias ARN and returns information about the function version to which the alias points. If you don't provide this parameter, the API uses unqualified function ARN and returns information about the $LATEST version of the Lambda function.

    :rtype: dict
    :return: {
        'Configuration': {
            'FunctionName': 'string',
            'FunctionArn': 'string',
            'Runtime': 'nodejs'|'nodejs4.3'|'nodejs6.10'|'java8'|'python2.7'|'python3.6'|'dotnetcore1.0'|'nodejs4.3-edge',
            'Role': 'string',
            'Handler': 'string',
            'CodeSize': 123,
            'Description': 'string',
            'Timeout': 123,
            'MemorySize': 123,
            'LastModified': 'string',
            'CodeSha256': 'string',
            'Version': 'string',
            'VpcConfig': {
                'SubnetIds': [
                    'string',
                ],
                'SecurityGroupIds': [
                    'string',
                ],
                'VpcId': 'string'
            },
            'DeadLetterConfig': {
                'TargetArn': 'string'
            },
            'Environment': {
                'Variables': {
                    'string': 'string'
                },
                'Error': {
                    'ErrorCode': 'string',
                    'Message': 'string'
                }
            },
            'KMSKeyArn': 'string',
            'TracingConfig': {
                'Mode': 'Active'|'PassThrough'
            }
        },
        'Code': {
            'RepositoryType': 'string',
            'Location': 'string'
        },
        'Tags': {
            'string': 'string'
        }
    }

    :returns:
    (string) --

    """
    pass


def linear_scale(datain, minval=0.0, maxval=1.0):
    """
    Program to scale the values of a matrix from a user specified minimum to a user specified maximum

    Parameters
    ----------
    datain : array-like
        numpy.array like with numbers
    minval : scalar, optional, default : 0
        This minimum value is attributed to the minimum value of the array
    maxval : scalar, optional, default : 1
        This maximum value is attributed to the maximum value of the array

    Returns
    -------
    dataout : array-like
        numpy.array like with numbers

    -------
    Example
    -------
        a = np.array([1,2,3,4,5]);
        a_out = scaledata(a,0,1);
    Out:
        array([0.  , 0.25, 0.5 , 0.75, 1.  ])

    References:
    ----------
    Program written by Aniruddha Kembhavi, July 11, 2007 for MATLAB
    Adapted by S. Haupert Dec 12, 2017 for Python
    """
    dataout = datain - datain.min()
    dataout = dataout / dataout.max() * (maxval - minval)
    dataout = dataout + minval
    return dataout


@staticmethod
def _get_settopdir_methodname(topdir_name):
    """
        Return the name of the method name to set top directory to `topdir_name`
        e.g. `outputdir()` for setting to `output`.
        """
    return topdir_name + 'dir'


def beautify_fill(angle_limit: float=3.14159):
    """Rearrange some faces to try to get less degenerated geometry

    :param angle_limit: Max Angle, Angle limit
    :type angle_limit: float
    """
    pass


@staticmethod
def extract_dimensions(instance_usage_dict, dimension_list):
    """Extract dimensions from instance usage.

        """
    dimensions_part = {}
    extra_data_map = instance_usage_dict.get('extra_data_map', {})
    for dim in dimension_list:
        value = instance_usage_dict.get(dim)
        if value is None:
            if len(list(extra_data_map)) > 0:
                value = extra_data_map.get(dim, 'all')
        if dim.startswith('dimensions#'):
            dim = dim.replace('dimensions#', '')
        elif dim.startswith('meta#'):
            dim = dim.replace('meta#', '')
        elif dim.startswith('value_meta#'):
            dim = dim.replace('value_meta#', '')
        dimensions_part[dim] = value
    return dimensions_part


def process():
    """ process the contents of the queue, i.e. start indexing;
            returns the number of processed queue items """


def min_mean_cycle(graph, weight, start=0):
    """Minimum mean cycle by Karp

    :param graph: directed graph in listlist or listdict format
    :param weight: in matrix format or same listdict graph
    :param int start: vertex that should be contained in cycle
    :returns: cycle as vertex list, average arc weights
              or None if there is no cycle from start
    :complexity:  `O(|V|*|E|)`
    """
    INF = float('inf')
    n = len(graph)
    dist = [[INF] * n]
    prec = [[None] * n]
    dist[0][start] = 0
    for ell in range(1, n + 1):
        dist.append([INF] * n)
        prec.append([None] * n)
        for node in range(n):
            for neighbor in graph[node]:
                alt = dist[ell - 1][node] + weight[node][neighbor]
                if alt < dist[ell][neighbor]:
                    dist[ell][neighbor] = alt
                    prec[ell][neighbor] = node
    valmin = INF
    argmin = None
    for node in range(n):
        valmax = -INF
        argmax = None
        for k in range(n):
            alt = (dist[n][node] - dist[k][node]) / float(n - k)
            if alt >= valmax:
                valmax = alt
                argmax = k
        if argmax is not None and valmax < valmin:
            valmin = valmax
            argmin = node, argmax
    if valmin == INF:
        return None
    C = []
    node, k = argmin
    for l in range(n, k, -1):
        C.append(node)
        node = prec[l][node]
    return C[::-1], valmin


def expanded_indexer(key, ndim):
    """Given a key for indexing an ndarray, return an equivalent key which is a
    tuple with length equal to the number of dimensions.

    The expansion is done by replacing all `Ellipsis` items with the right
    number of full slices and then padding the key with full slices so that it
    reaches the appropriate dimensionality.
    """
    if not isinstance(key, tuple):
        key = key,
    new_key = []
    found_ellipsis = False
    for k in key:
        if k is Ellipsis:
            if not found_ellipsis:
                new_key.extend((ndim + 1 - len(key)) * [slice(None)])
                found_ellipsis = True
            else:
                new_key.append(slice(None))
        else:
            new_key.append(k)
    if len(new_key) > ndim:
        raise IndexError('too many indices')
    new_key.extend((ndim - len(new_key)) * [slice(None)])
    return tuple(new_key)


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


@staticmethod
def is_valid_address_x64(i):
    """Check if int is within a valid Windows x64 memory range."""
    return 65536 <= i < 140737488355327


@staticmethod
def construct_default_dict():
    """Construct default predicate definition as it would be written in the configuration file."""
    return {'name': 'alwaysTrue'}


def identity(x):
    """
    Helper function which returns its argument unchanged.
    That is, `identity(x)` returns `x` for any input `x`.
    """
    return x


def view_frame():
    """Reset viewable area to show range around current frame

    """
    pass


def nameLength(name):
    """
    Remove the '~' from strings and count the letters.
    :param name: String to count
    :return: length of name without '~'
    """
    return len(name) - name.count('~')


@classmethod
def get_payment_method_priority(cls):
    """
        Priority order for payment methods. Downstream modules can override
        this method to change the method priority.
        """
    return 'manual', 'credit_card', 'dummy'


@classmethod
def getIdentifierForCurrentRequest(kls, request):
    """ It is not possible to get the user's email address from a request"""
    return kls.getIdentifierForUser(kls.get_ip(request))


@staticmethod
def is_numerical():
    """
        Return true if the written representation of the element are digits
        """
    raise NotImplementedError('is_numerical')


def delete_vpc_endpoints(DryRun=None, VpcEndpointIds=None):
    """
    Deletes one or more specified VPC endpoints. Deleting the endpoint also deletes the endpoint routes in the route tables that were associated with the endpoint.
    See also: AWS API Documentation

    :example: response = client.delete_vpc_endpoints(
        DryRun=True|False,
        VpcEndpointIds=[
            '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 VpcEndpointIds: list
    :param VpcEndpointIds: [REQUIRED]
            One or more endpoint IDs.
            (string) --

    :rtype: dict
    :return: {
        'Unsuccessful': [
            {
                'ResourceId': 'string',
                'Error': {
                    'Code': 'string',
                    'Message': 'string'
                }
            },
        ]
    }

    """
    pass


def iterate_attributes(cls):
    """iterate all the keys and attributes associated
       with a class, without using getattr().

       Does not use getattr() so that class-sensitive
       descriptors (i.e. property.__get__()) are not called.

    """
    keys = dir(cls)
    for key in keys:
        for c in cls.__mro__:
            if key in c.__dict__:
                yield key, c.__dict__[key]
                break


def num2ver(ver):
    """
	Converts a string, tuple or version number into an integer. The number is supposed to have at most 4 digits::

		from waflib.Utils import num2ver
		num2ver('1.3.2') == num2ver((1,3,2)) == num2ver((1,3,2,0))

	:type ver: string or tuple of numbers
	:param ver: a version number
	"""
    if isinstance(ver, str):
        ver = tuple(ver.split('.'))
    if isinstance(ver, tuple):
        ret = 0
        for i in range(4):
            if i < len(ver):
                ret += 256 ** (3 - i) * int(ver[i])
        return ret
    return ver


def _resolution_to_timedelta(res_text: str) ->str:
    """
    Convert an Entsoe resolution to something that pandas can understand
    """
    resolutions = {'PT60M': '60min', 'P1Y': '12M', 'PT15M': '15min',
        'PT30M': '30min', 'P7D': '7D', 'P1M': '1M'}
    delta = resolutions.get(res_text)
    if delta is None:
        raise NotImplementedError(
            "Sorry, I don't know what to do with the resolution '{}', because there was no documentation to be found of this format. Everything is hard coded. Please open an issue."
            .format(res_text))
    return delta


@classmethod
def get_unhealthy(cls, session, threshold):
    """
        Gets all health scores below a certain value
        :param session the instance of Session used for APIC communication
        :param threshold integer for determining unhealthy objects
        :returns: List of HealthScore objects
        """
    url = (
        '/api/node/class/healthInst.json?query-target-filter=and(lt(healthInst.cur,"{}"))'
        .format(threshold))
    objects = cls._get_by_url(session, url)
    return objects


def get_read_stats(barcode_stats, read_num):
    """
    .. deprecated:: 0.1.0
       Read stats are now parsed from the output of Picard Tools's CollectAlignmentSummaryMetrics.
       Such files are also stored in the DNAnexus projects created by GSSC.

    Each barcoded library in a DNAnexus project from GSSC contains a ${barcode}_stats.json file, where ${barcode} is a
    barcode sequence, that has read-level stats. This function accepts a barcode-specific hash
    from that file and parses out some useful read-based stats for the given read number.
    An example of a barcode_stats.json file is provided in the data subdirectory of this script.

    Args:
        barcode_stats: `dict`. The JSON-loaded content of a particular ${barcode}_stats.json file.
            See `scgpm_seqresults_dnanexus.dnanexus_utils.DxSeqResults.get_barcode_stats()` for
            more details.
        read_num: `int`. The read number (1 or 2) for which you need read stats.
    """
    read_num_key = 'Read {}'.format(read_num)
    read_hash = barcode_stats[read_num_key]
    stats = {}
    stats['pass_filter'] = read_hash['Post-Filter Reads']
    return stats


def markup_serialize_tokens(tokens, markup_func):
    """
    Serialize the list of tokens into a list of text chunks, calling
    markup_func around text to add annotations.
    """
    for token in tokens:
        for pre in token.pre_tags:
            yield pre
        html = token.html()
        html = markup_func(html, token.annotation)
        if token.trailing_whitespace:
            html += token.trailing_whitespace
        yield html
        for post in token.post_tags:
            yield post


@staticmethod
def get_read_sorted_int_length(buf, offset):
    """
        Returns the number of bytes that would be read by
        :py:meth:`read_sorted_int`.

        Because the length is stored in the first byte, this method may be
        called with only the first byte of the packed integer in the given
        buffer. This method only accesses one byte at the given offset.

        :param buf: the buffer to read from.
        :type buf: bytearray
        :param offset: the offset in the buffer at which to start reading.
        :type offset: int
        :returns: the number of bytes that would be read.
        :rtype: int
        """
    b1 = buf[offset] & 255
    if b1 < 8:
        return 1 + 8 - b1
    if b1 > 247:
        return 1 + b1 - 247
    return 1


def filterBuiltinFunctions(isGlobal, varName, varType):
    """Filters out builtin functions"""
    del isGlobal
    del varName
    return varType.lower() in ['method-wrapper', 'builtin function']


def _find_minimal_alignment(offset, base_alignment, prev_end):
    """
    Returns the minimal alignment that must be set for a field with
    ``base_alignment`` (the one inherent to the type),
    so that the compiler positioned it at ``offset`` given that the previous field
    ends at the position ``prev_end``.
    """
    alignment = base_alignment
    while True:
        if offset % alignment != 0:
            raise ValueError(
                'Field cannot be positioned at offset {offset}, since it is not multiple of the minimal alignment {alignment}'
                .format(offset=offset, alignment=alignment))
        if alignment > offset:
            raise ValueError(
                'Could not find a suitable alignment for the field at offset {offset}'
                .format(offset=offset))
        if offset - prev_end >= alignment:
            alignment *= 2
            continue
        return alignment


def append_no_duplicate(config, path, base, nxt):
    """ a list strategy to append only the elements not yet in the list."""
    for e in nxt:
        if e not in base:
            base.append(e)
    return base


def slice_axis(data, axis, begin, end):
    """Slice along a given axis.
    Returns an array slice along a given axis starting from :attr:`begin` index to :attr:`end` index.

    Parameters
    ----------
    data : Tensor
        The data tensor.
    axis : int
        The axis along to slice the tensor.
    begin : int
        Indicates the begin index.
    end : int
        Indicates the end index.
    Returns:
    --------
    Tensor
        The sliced tensor.
    """
    pass


@classmethod
def instance(cls):
    """Return the unique instance of Runner, if any, or None"""
    return cls._INSTANCE and cls._INSTANCE()


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

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

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


def finalizeInput(out):
    """Notify processor that input data is now complete.

        Processor can still choose to write data to pass along input
        stream to out, using .write().
        """


def get_border():
    """Returns the border.

    :return:  A tuple of 4 numbers (xmin, ymin, xmax, ymax).
    """
    pass


def metric_clutch_torque_converter_model(y_true, y_pred, on_engine):
    """
    Metric for the `clutch_torque_converter_model`.

    :param y_true:
        Reference engine speed vector [RPM].
    :type y_true: numpy.array

    :param y_pred:
        Predicted engine speed vector [RPM].
    :type y_pred: numpy.array

    :param on_engine:
        If the engine is on [-].
    :type on_engine: numpy.array

    :return:
        Error.
    :rtype: float
    """
    from co2mpas.utils import mae
    return float(mae(y_true[on_engine], y_pred[on_engine]))


def singleton(cls):
    """Decorates a class to turn it into a singleton."""
    obj = cls()
    obj.__name__ = cls.__name__
    return obj


def iter_properties(iterable):
    """Split lines on '=' and ':=' ignoring blank lines and comments.
    """
    for line in iterable:
        if not line.isspace() and not line.startswith('#'):
            key, sep, val = line.partition(':=')
            if not sep:
                key, sep, val = line.partition('=')
            if not key.isspace() and sep:
                yield key.strip(), val.strip()


def format_message(name, message, version):
    """Message formatter to create `DeprecationWarning` messages
    such as:

        'fn' is deprecated and will be remove in future versions (1.0).
    """
    return ("'{}' is deprecated and will be remove in future versions{}. {}"
        .format(name, ' ({})'.format(version) if version else '', message))


@classmethod
def is_private(cls, obj) ->bool:
    """
        Check chat is private

        :param obj:
        :return:
        """
    return cls._check(obj, [cls.PRIVATE])


def get_parser():
    """Build parser object"""
    from argparse import ArgumentParser
    from argparse import RawTextHelpFormatter
    parser = ArgumentParser(description=__doc__, formatter_class=
        RawTextHelpFormatter)
    parser.add_argument('input_file', action='store', help='the input file')
    return parser


def kill_duplicates(df):
    """
    Remove duplicate entries from a DataFrame (keeps the first one).
    """
    old_count = df.shape[0]
    new_df = df.loc[~df.duplicated()]
    new_count = new_df.shape[0]
    if new_count <= old_count:
        print('Removed {} of {} duplicate index entries, {} remaining'.
            format(old_count - new_count, old_count, new_count))
    return new_df


def _path_to_same_str(p_fn):
    """path -> str, but same on nt+posix, for alpha-sort only"""
    s_fn = str(p_fn)
    s_fn = s_fn.replace('\\', '.')
    s_fn = s_fn.replace('/', '.')
    return s_fn


def loss_surface_mesh(x, y, f):
    """
    Takes irregularly spaced points ``(x, y, f)`` and creates a mesh using
    the ``Mayavi`` package and Delaunay triangulation.

    This method is useful to visualize the output of an optimisation routine on
    a 2-dimensional parameter space.

    *Note: this method requires Mayavi to be installed.*
    """
    from mayavi import mlab
    mlab.figure(1, fgcolor=(0, 0, 0), bgcolor=(1, 1, 1))
    p = mlab.points3d(x, y, f, f, scale_mode='none', scale_factor=0)
    mlab.pipeline.surface(mlab.pipeline.delaunay2d(p))
    mlab.show()


@staticmethod
def out_quint(progress):
    """.. image:: images/anim_out_quint.png
        """
    p = progress - 1.0
    return p * p * p * p * p + 1.0


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


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


def isdir():
    """
        Check if this file path refers to a directory.

        @return: C{True} if the file at this file path is a directory, C{False}
            otherwise.
        """


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

    Args:
      n (int): integer

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


def collection(uid):
    """entity returns an entity object
    parent is an owner
    """
    fields = [{'key': 'uid', 'required': True, 'value': uid}]
    model = {'fields': fields, 'key': ['Collection', uid]}
    return model


@classmethod
def GetProgramSchedule(cls, class_key):
    """Retrieve the ProgramSchedule and a dict of task params.

    Args:
      class_key: String class key (i.e. `image.mnist.LeNet5`).

    Returns:
      ProgramSchedule.Params()
    """
    model_params_cls = cls.GetClass(class_key)
    model_params = model_params_cls()
    program_schedule_cfg = model_params.ProgramSchedule()
    return program_schedule_cfg


def _messages_iter(msg_iter):
    """Used to iterate through messages."""
    try:
        msg = next(msg_iter)
        yield msg.pop('claim')
        yield msg
        for msg in msg_iter:
            del msg['claim']
            yield msg
    except StopIteration:
        return


def add_open_client_order_items():
    """add all open client order items to this order.

    A client order item is considered open, when it is not yet
    associated with an order.
    """


def div(var1, var2):
    """
    Wrapper function for __truediv__ and __rtruediv__
    """
    return var1 / var2


def item_openclose(all: bool=True):
    """Toggle whether item under cursor is enabled or closed

    :param all: All, Close or open all items
    :type all: bool
    """
    pass


def is_fp_closed(obj):
    """
    Checks whether a given file-like object is closed.

    :param obj:
        The file-like object to check.
    """
    try:
        return obj.isclosed()
    except AttributeError:
        pass
    try:
        return obj.closed
    except AttributeError:
        pass
    try:
        return obj.fp is None
    except AttributeError:
        pass
    raise ValueError('Unable to determine whether fp is closed.')


def evalcontextfilter(f):
    """Decorator for marking eval-context dependent filters.  An eval
    context object is passed as first argument.  For more information
    about the eval context, see :ref:`eval-context`.

    .. versionadded:: 2.4
    """
    f.evalcontextfilter = True
    return f


def _is_python_file(filename):
    """return true if the given filename should be considered as a python file

    .pyc and .pyo are ignored
    """
    return filename.endswith(('.py', '.so', '.pyd', '.pyw'))


@classmethod
def __runXmippProgram(cls, program, args):
    """ Internal shortcut function to launch a Xmipp program. """
    from pwem import Domain
    xmipp3 = Domain.importFromPlugin('xmipp3')
    xmipp3.Plugin.runXmippProgram(program, args)


def remove_problematic_columns(x_df, columns_to_remove):
    """Return new df with problematic columns removed."""
    return x_df.drop(columns_to_remove, axis=1)


def cressman_weights(sq_dist, r):
    """Calculate the Cressman weights from squared distance values.

    Parameters
    ----------
    sq_dist: (N, ) ndarray
        Squared distances from interpolation point
        associated with each observation in meters.
    r: float
        Maximum distance an observation can be from an
        interpolation point to be considered in the inter-
        polation calculation.

    Returns
    -------
    weights: (N, ) ndarray
        Calculated weights for the given observations determined by their distance
        to the interpolation point.

    """
    return (r * r - sq_dist) / (r * r + sq_dist)


def freestyle_module_open(filepath: str='', make_internal: bool=True):
    """Open a style module file

    :param filepath: filepath
    :type filepath: str
    :param make_internal: Make internal, Make module file internal after loading
    :type make_internal: bool
    """
    pass


def validate_virtual_network_rules(ns):
    """ Extracts multiple space-separated virtual network rules """
    from azure.mgmt.cosmosdb.models import VirtualNetworkRule
    if ns.virtual_network_rules is not None:
        virtual_network_rules_list = []
        for item in ns.virtual_network_rules:
            virtual_network_rules_list.append(VirtualNetworkRule(id=item))
        ns.virtual_network_rules = virtual_network_rules_list


def shaderfx_remove(shaderfx: str=''):
    """Remove a shaderfx from the active grease pencil object

    :param shaderfx: Shader, Name of the shaderfx to edit
    :type shaderfx: str
    """
    pass


def get_id():
    """
    Returns the identifier of this API.
    """
    raise NotImplementedError()


def lambd_BOH3_SO4_FW86(T, P):
    """n-a: boric-acid sulfate [FW86]."""
    lambd = 0.018
    valid = T == 298.15
    return lambd, valid


@staticmethod
def _normalize_cmd(command):
    """Normalize CLI commands to have a single trailing newline"""
    command = command.rstrip('\n')
    command += '\n'
    return command


@classmethod
def run_hooks(cls, hook_type, *args, **kwargs):
    """Run all hooks of specified type.

        :param cls: class that registers hooks
        :param hook_type: hook type, e.g., '__pre_parse_args__'
        :param args: args to be passed to every hook function
        :param kwargs: kwargs to be passed to every hook function
        """
    hook_funcs = cls._hooks_map.get(hook_type) or []
    for hook_func in hook_funcs:
        hook_func(*args, **kwargs)


def _highlight(value):
    """
    highlight 'type validator'.
    """
    if value not in ('html', 'ansi'):
        raise ValueError('Highlight must be "html" or "ansi", got {0}'.
            format(value))
    return value


def addRatedReaction(IRatedReaction):
    """Add a reaction to the context object."""


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

        :param PasswordResetType val:
        :rtype: EventType
        """
    return cls('password_reset', val)


def untranslate_module_name(module):
    """Rename module names mention in JSON to names that we can import
    This reverses the translation applied by translate_module_name() to
    a module name available to the current version of Python.
    """
    if module == '__builtin__':
        module = 'builtins'
    elif module == 'exceptions':
        module = 'builtins'
    return module


def concat_drive_path(dest_path, end_point, default_folder='mydrive'):
    """
    Generate file path
    :param dest_path: parent path
    :param end_point: file_name or folder_name
    :param default_folder
    :return:
    """
    if dest_path is None:
        display_path = f'/{default_folder}/{end_point}'
    elif dest_path.startswith('id'):
        display_path = f'{dest_path}/folder_name'
    else:
        dest_path = f'/{dest_path}' if not dest_path.startswith('/'
            ) else dest_path
        dest_path = f'{dest_path}/' if not dest_path.endswith('/'
            ) else dest_path
        display_path = f'{dest_path}{end_point}'
    return display_path


def _Div(lhs=None, rhs=None, out=None, name=None, **kwargs):
    """Divides arguments element-wise.

    The storage type of ``elemwise_div`` output is always dense

    Parameters
    ----------
    lhs : NDArray
        first input
    rhs : NDArray
        second input

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

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


def _pct(name, n):
    """helper function for ctxrange"""
    i = yield name + ' 0%'
    while True:
        i = yield name + ' {:.0f}%'.format(100 * (i + 1) / n)


def datetime_passed_now(source):
    """
    Compares provided datetime with current time on the basis of Django
    settings. Checks source is in future or in past. False if it's in future.
    Parameters
    ----------
    source: datetime object than may or may not be naive

    Returns
    -------
    bool

    Author: Himanshu Shankar (https://himanshus.com)
    """
    import datetime
    import pytz
    if source.tzinfo is not None and source.tzinfo.utcoffset(source
        ) is not None:
        return source <= datetime.datetime.utcnow().replace(tzinfo=pytz.utc)
    else:
        return source <= datetime.datetime.now()


def num_from_str(s):
    """Return a number from a string."""
    try:
        return int(s)
    except ValueError:
        try:
            return float(s)
        except ValueError:
            raise ValueError('Can not convert the string "' + s +
                '" into a numeric value.')


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


def _apply_proto_op_extra_attrs(proto_op):
    """Applies applicable attrs to proto_op.extra_attrs.

    The proto op is generated from the original opspec when a batch is
    specified (either as an explicit optimizer or implicitly through a
    batch flag spec). Most of the original operation attributes apply
    to the proto op, but some are different. This function modifies
    proto_op.extra_attrs accordingly.
    """
    proto_op.extra_attrs['run_params']['optimizer'] = None


def merge(dicts):
    """Merge a sequence of dictionaries. In case of name clashes,
    the last dict in the sequence wins."""
    dic = {}
    for d in dicts:
        dic.update(d)
    return dic


def list_items(obj):
    """
    Returns a list of key,value pairs for the content of an object
    Creates an abstraction layer so that we do not have to worry.
    """
    try:
        return obj.items()
    except AttributeError:
        return obj.__dict__.items()
    except TypeError:
        return enumerate(list(obj))


def provider_api_configuration_default():
    """Default value for the API configuration field of a provider.

    Some provider implementations can be picky, configure these special cases here.
    """
    return {'trailing_slash': False}


def _bool_or_string(string):
    """Helper to interpret different ways of specifying boolean values."""
    if string in ['t', 'true', 'True']:
        return True
    if string in ['f', 'false', 'False']:
        return False
    return string


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


def unlines(ls):
    """
    unlines :: [str] -> str
    unlines is an inverse operation to lines. It joins lines, after appending a terminating newline to each.
    """
    return '\n'.join(ls)


@classmethod
def get_k8s_secrets(cls, secret_name, secrets):
    """ Given an array of Docker secrets return a set of secrets and a set of volumeMounts """
    volume_mounts = []
    volumes = []
    environment_variables = []
    for secret_config in secrets:
        if 'mount_path' in secret_config:
            mount_path = secret_config['mount_path']
            read_only = True
            volume_name = secret_name
            if 'read_only' in secret_config:
                read_only = secret_config['read_only']
            if 'name' in secret_config:
                volume_name = secret_config['name']
            secret_volume = dict(secretName=secret_name)
            if 'items' in secret_config:
                secret_volume['items'] = secret_config['items']
            volume_mounts.append(dict(mountPath=mount_path, name=
                volume_name, readOnly=read_only))
            volumes.append(dict(name=volume_name, secret=secret_volume))
        elif 'env_variable' in secret_config:
            secret_key_ref = dict(secretKeyRef=dict(name=secret_name, key=
                secret_config['key']))
            environment_variables.append(dict(name=secret_config[
                'env_variable'], valueFrom=secret_key_ref))
    return volumes, volume_mounts, environment_variables


def getMicIdName(mic, suffix=''):
    """ Return a name for the micrograph based on its IDs. """
    return '%d%s' % (mic.getObjId(), suffix)


def drawAsInfinite(requestContext, seriesList):
    """
    Takes one metric or a wildcard seriesList.
    If the value is zero, draw the line at 0. If the value is above zero, draw
    the line at infinity. If the value is null or less than zero, do not draw
    the line.

    Useful for displaying on/off metrics, such as exit codes. (0 = success,
    anything else = failure.)

    Example::

        drawAsInfinite(Testing.script.exitCode)

    """
    for series in seriesList:
        series.options['drawAsInfinite'] = True
        series.name = 'drawAsInfinite(%s)' % series.name
    return seriesList


def _set_client_factory(cls, factory):
    """Set the local client factory.
        This will only be available to subclasses of this class.
        """
    cls.__client_factory__ = factory.__get__


@staticmethod
def compute_bounds(data, pixel_size, center_on):
    """Return image bounds from *pixel_size* (scalar or tuple)"""
    if not isinstance(pixel_size, (tuple, list)):
        pixel_size = [pixel_size, pixel_size]
    dx, dy = pixel_size
    xmin, ymin = 0.0, 0.0
    xmax, ymax = data.shape[1] * dx, data.shape[0] * dy
    if center_on is not None:
        xc, yc = center_on
        dx, dy = 0.5 * (xmax - xmin) - xc, 0.5 * (ymax - ymin) - yc
        xmin -= dx
        xmax -= dx
        ymin -= dy
        ymax -= dy
    return xmin, xmax, ymin, ymax


def to_list(obj):
    """Convert an object to a list if it is not already one"""
    if not isinstance(obj, (list, tuple)):
        obj = [obj]
    return obj


def weld_verts(bm: 'bmesh.types.BMesh', targetmap: dict):
    """Welds verts together (kind-of like remove doubles, merge, etc, all of which use or will use this bmop). You pass in mappings from vertices to the vertices they weld with.

    :param bm: The bmesh to operate on.
    :type bm: 'bmesh.types.BMesh'
    :param targetmap: Undocumented.
    :type targetmap: dict
    """
    pass


def csv_prepare_entry(value):
    """
    Converts a "None" value into an empty string
    :param value:
    :return: <""> if value is none, <value> otherwise
    """
    return '' if value is None else str(value).replace(';', ',')


def _split_and_keep(_str, separator):
    """Replace end of sentence with separator"""
    if not _str:
        return []
    max_p = chr(ord(max(_str)) + 1)
    return _str.replace(separator, separator + max_p).split(max_p)


def get_fix_string(input_string: str, length: int):
    """
    Transforms input_string to the string of the size length.

    Parameters
    ----------
    input_string : str
        input_string
    length : int
        length of output_string, if -1 then output_string is the same as input_string

    Returns
    -------
    str
        beautiful string of the size length

    """
    input_string = str(input_string)
    if length < 0:
        output_string = input_string
    elif len(input_string) > length:
        sep = (length - 3) // 2
        if length % 2 == 0:
            output_string = input_string[:sep + 1] + '...' + input_string[-sep:
                ]
        else:
            output_string = input_string[:sep] + '...' + input_string[-sep:]
    else:
        output_string = input_string + ' ' * (length - len(input_string))
    return output_string


def bone_layers(layers: bool=(False, False, False, False, False, False,
    False, False, False, False, False, False, False, False, False, False,
    False, False, False, False, False, False, False, False, False, False,
    False, False, False, False, False, False)):
    """Change the layers that the selected bones belong to

    :param layers: Layer, Armature layers that bone belongs to
    :type layers: bool
    """
    pass


def can_print(payment):
    """If it's possible to print this payment

        :param payment: the payment to print
        """


def is_from_parent(cls, attribute_name, value=None):
    """
    Tests if the current attribute value is shared by a parent of the given
    class.

    Returns None if the attribute value is None.

    :param cls: Child class with the requested attribute
    :param attribute_name: Name of the attribute to be tested
    :param value: The exact value in the child class (optional)
    :return: True if the attribute value is shared with a parent class
    """
    if value is None:
        try:
            value = getattr(cls, attribute_name)
        except AttributeError:
            return False
    for base in cls.__bases__:
        try:
            return getattr(base, attribute_name) is value
        except AttributeError:
            pass
    return False


def _attr_is_callable(obj, attr_name: str) ->bool:
    """
    Checks if the attribute named is callable.

    This means that non-function objects can be used.

    :param obj: any object
    :param attr_name: the name of the attribute to check.
    :return: true if the named attribute is callable
    """
    return hasattr(obj, attr_name) and hasattr(getattr(obj, attr_name),
        '__call__')


@classmethod
def post_request(cls, target, instance_key, dev_mode=False, data={},
    url_override=False):
    """
        public class method - make a get request to the api
        """
    operator = cls(instance_key, dev_mode=dev_mode)
    return operator.post_request_inner(target, data, url_override=url_override)


@staticmethod
def concat_url(endpoint, url):
    """Concatenate endpoint and final URL.

        E.g., "http://keystone/v2.0/" and "/tokens" are concatenated to
        "http://keystone/v2.0/tokens".

        :param endpoint: the base URL
        :param url: the final URL
        """
    return '%s/%s' % (endpoint.rstrip('/'), url.strip('/'))


def is_owner(owner, user):
    """Check user instances and subclasses for equility."""
    return isinstance(user, owner.__class__) and owner.pk == user.pk


def execJs(selector, code, debug='0'):
    """You can pass a selector and the inline js code to be applied"""


def parse_address(address, port=None):
    """
    Return a (host, port) tuple based on the config value.
    """
    try:
        address, port = address.split(':', 1)
    except ValueError:
        pass
    if port:
        port = int(port)
    return address, port


@classmethod
def backend_disable(cls, backend):
    """ Disable a backend for a server """
    server = cls.backend_list(backend)
    oper = cls.call('hosting.rproxy.server.disable', server[0]['id'])
    cls.echo('Desactivating backend on server %s' % server[0]['ip'])
    cls.display_progress(oper)
    cls.echo('Backend desactivated')
    return oper


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


def roundval(val, reltol=0.01):
    """Calcul d'une valeur arrondie proche a reltol pres"""
    from math import log
    tol = reltol * abs(val)
    d = log(tol, 10.0) + 0.0001
    n = int(d)
    if n < 0:
        n -= 1
    base = 10 ** n
    rest = tol / base + 0.0001
    for x in (7.5, 5.0, 4.0, 2.5, 2.0, 1.5, 1.0):
        if x <= rest:
            break
    rest = base * x
    r1 = rest * (val // rest)
    if val >= 0.0:
        r2 = r1 + rest
    else:
        r1, r2 = r1 - rest, r1
    r3 = r1 if r2 - val > val - r1 else r2
    return r1, r3, r2


@classmethod
def allocate(cls, context, builder, set_type, nitems=None):
    """
        Allocate a SetInstance with its storage.  Same as allocate_ex(),
        but return an initialized *instance*.  If allocation failed,
        control is transferred to the caller using the target's current
        call convention.
        """
    ok, self = cls.allocate_ex(context, builder, set_type, nitems)
    with builder.if_then(builder.not_(ok), likely=False):
        context.call_conv.return_user_exc(builder, MemoryError, (
            'cannot allocate set',))
    return self


def standard_parameter_writer(filename, pid, params=None):
    """
    Standard parameter writer.

    The standard parameter writer writes a file containing
    1 line per parameter with the parameter value.

    All values will be written in IEEE double precision: {:.14e}.

    That means:

        3.000000000000000e-01

        2.300000000000000e-01

        1.440000000000000e+01

        3.000000000000000e-01

        ...

    Parameters
    ----------
    filename : string
        Output filename with parameter values
    pid : int
        Output file will be filename.pid
    params : iterable
        Parameter values

        If standard_parameter_writer is called with two arguments, then the second argument will be params.

    Returns
    -------
    None
        No return value but output file written: filename.pid

    Examples
    --------
    >>> randst = np.random.RandomState()
    >>> pid = str(randst.randint(2147483647))
    >>> params = sample_parameter(pis, pmin, pmax, pmask)
    >>> standard_parameter_writer(paramfile, pid, params)

    History
    -------
    Written,  Matthias Cuntz, Jan 2020
    Modified, Matthias Cuntz, Jan 2020 - call with 2 or 3 arguments, i.e. pid given or not
    """
    if params is None:
        ofile = filename
        iparams = pid
    else:
        ofile = filename + '.' + str(pid)
        iparams = params
    f = open(ofile, 'w')
    for pp in iparams:
        dstr = '{:.14e}'.format(pp)
        print(dstr, file=f)
    f.close()
    return


def pipeline_link_color(plug, link):
    """
    Link color and style for graphical display and graphviz graphs.

    Parameters
    ----------
    plug: Plug
        the plug the link belong to
    link: link tuple (5 values)
        link to color

    Returns
    -------
    link_props: tuple
        (color, style, active, weak) where color is a RGB tuple of float values
        (between 0. and 1.), style is a string ("solid", "dotted"), active and
        weak are booleans.
    """
    GRAY_1 = 0.7, 0.7, 0.8
    RED_2 = 0.92, 0.51, 0.12
    active = plug.activated and link[3].activated
    if active:
        color = RED_2
    else:
        color = GRAY_1
    weak = link[4]
    if weak:
        style = 'dotted'
    else:
        style = 'solid'
    return color, style, active, weak


def clear_zipimport_cache():
    """Clear out cached entries from _zip_directory_cache.
    See http://www.digi.com/wiki/developer/index.php/Error_messages"""
    import sys, zipimport
    syspath_backup = list(sys.path)
    zipimport._zip_directory_cache.clear()
    sys.path = syspath_backup
    sys.path_importer_cache.clear()


def partial_subset_of_span(span1, span2):
    """ Asks whether span1 is a subset of span2, or vice versa. Returns True or False. """
    if not span1:
        raise ValueError('{} is empty'.format(span1))
    if not span2:
        raise ValueError('{} is empty'.format(span2))
    span1_sub_span2 = span2[0] <= span1[0] <= span2[1] or span2[0] <= span1[1
        ] <= span2[1]
    condition = span1_sub_span2 or (span1[0] <= span2[0] <= span1[1] or
        span1[0] <= span2[1] <= span1[1])
    return condition


def passthrough():
    """Passthrough filter."""
    x = []
    while True:
        x = yield x


def next_batch(targ_capacity, curr_capacity, num_up_to_date, batch_size,
    min_in_service):
    """Return details of the next batch in a batched update.

    The result is a tuple containing the new size of the group and the number
    of members that may receive the new definition (by a combination of
    creating new members and updating existing ones).

    Inputs are the target size for the group, the current size of the group,
    the number of members that already have the latest definition, the batch
    size, and the minimum number of members to keep in service during a rolling
    update.
    """
    assert num_up_to_date <= curr_capacity
    efft_min_sz = min(min_in_service, targ_capacity, curr_capacity)
    efft_bat_sz = min(batch_size, max(targ_capacity - num_up_to_date, 0))
    new_capacity = efft_bat_sz + max(min(curr_capacity, targ_capacity -
        efft_bat_sz), efft_min_sz)
    return new_capacity, efft_bat_sz


@classmethod
def copy(cls, options):
    """Clone existing host collection"""
    cls.command_sub = 'copy'
    return cls.execute(cls._construct_command(options), output_format='csv')


def list_open_id_connect_providers():
    """
    Lists information about the IAM OpenID Connect (OIDC) provider resource objects defined in the AWS account.
    See also: AWS API Documentation

    :example: response = client.list_open_id_connect_providers()

    :rtype: dict
    :return: {
        'OpenIDConnectProviderList': [
            {
                'Arn': 'string'
            },
        ]
    }

    """
    pass


def checkGroupEffectsValidity(columnsForZ, columnEffects):
    """On input user request removal of columnsForZ
    Here we confimr if they all exist in the current data set. If not
    reduce columnsForZ to include only valid effects. Print out a message
    NOTE: always convert to and return uppercase for comparisons and subsequent analysis
    """
    upperColumnsForZ = list()
    for effect in columnsForZ:
        upperColumnsForZ.append(effect)
    newList = list(set(upperColumnsForZ) & set(columnEffects))
    if newList.sort() != upperColumnsForZ.sort():
        print(
            'Input group list has been reduced based on preestablished possible effects'
            )
        print('Size on data effects is ' + str(len(columnsForZ)) +
            ' new removal list is of size ' + str(len(newList)))
        print('New removal list is ' + str(newList))
    return newList


def parse_slack_output(slack_rtm_output, AT_BOT):
    """
        The Slack Real Time Messaging API is an events firehose.
        this parsing function returns None unless a message is
        directed at the Bot, based on its ID.
    """
    output_list = slack_rtm_output
    command, channel, user = None, None, None
    if output_list and len(output_list) > 0:
        for output in output_list:
            if output and 'text' in output and AT_BOT in output['text']:
                command, channel, user = output['text'].split(AT_BOT)[1].strip(
                    ), output['channel'], output['user']
    return command, channel, user


def setRoundFloatFunction(func):
    """ Globally set function for rounding floats within given precision.

    The function signature must be:

        def func(value: float, ndigits: int) -> float
    """
    global _ROUND_FLOAT_FUNC
    _ROUND_FLOAT_FUNC = func


@staticmethod
def _generate_item_md(text):
    """generates markdown for a list item."""
    return '- {}\n'.format(text)


def kelvin_2_celsius(x):
    """Convert kelvin to celcius."""
    return x - 273.15


def to_email_address(tokens):
    """Translate the tokens to email addresses"""


def reportNumber(n, options, field=None):
    """ Given n an integer, report back the correct format as string.
    """
    if field is not None:
        return '%*g' % (field, n)
    else:
        return '%g' % n


def upgrade():
    """Upgrade database."""


def _its_a_func(func):
    """
    In case the target func doesn't have it's `im_func` attr set.

    :param func:
    :return:
    """
    if func is not None:
        func.im_func = True
    return func


def shutdown():
    """Called when FSLeyes exits normally (i.e. the user closes the window).
    Does some final clean-up before exiting.
    """
    import fsl.utils.settings as fslsettings
    fslsettings.delete('loadSaveOverlayDir')


def table_delta(first_summary, second_summary):
    """
    A listing of changes between two TableSummarySet objects.

    :param first_summary: First TableSummarySet object
    :param second_summary: Second TableSummarySet object
    :return: Change in number of rows
    """
    differences = []
    for first, second in zip(first_summary, second_summary):
        diff = first.number_of_rows - second.number_of_rows
        differences.append(diff)
    return differences


def meta_make():
    """Group selected strips into a metastrip

    """
    pass


def inangle(theta, angle, atol):
    """
    Input:  (theta) angle inquestion
            (angle) reference angle
            (atol)  tolerance about (angle)
    Output:         True or False, depending on whether
                    theta is in [angle-atol,angle+atol)
    """
    lower = angle - atol
    upper = angle + atol
    if (lower >= 0) & (upper <= 360):
        if (theta >= lower) & (theta < upper):
            return True
    if lower < 0:
        lower %= 360
        if (theta > upper) & (theta >= lower):
            return True
        elif (theta >= 0) & (theta < upper):
            return True
    if upper > 360:
        upper %= 360
        if (theta >= lower) & (theta < 0):
            return True
        if (theta >= 0) & (theta < upper):
            return True
    return False


@classmethod
def build(cls, **kwargs):
    """Build the dict and return it."""
    ret = {}
    attributs = cls._clean_attr()
    for one_attribut in attributs:
        if one_attribut in kwargs:
            value = kwargs[one_attribut]
        else:
            value = getattr(cls, one_attribut)
        ret.update({one_attribut: value})
    return ret


def _check_slice(sli, dim):
    """
    Check if the current slice needs to be treated with pbc or if we can
    simply pass it to ndarray __getitem__.

    Slice is special in the following cases:
    if sli.start < 0 or > dim           # roll (and possibly pad)
    if sli.stop > dim or < 0            # roll (and possibly pad)
    if abs(sli.stop - sli.start) > 0    # pad
    """
    _roll = 0
    _pad = 0
    step = sli.step or 1
    start = (0 if step > 0 else dim) if sli.start is None else sli.start
    stop = (dim if step > 0 else 0) if sli.stop is None else sli.stop
    span = stop - start if step > 0 else start - stop
    if span <= 0:
        return _roll, _pad, sli.start, sli.stop, sli.step
    lower = min(start, stop)
    upper = max(start, stop)
    _start = 0 if step > 0 else span
    _stop = span if step > 0 else 0
    if span > dim:
        _pad = span - dim
        _roll = -lower % dim
    elif lower < 0 or upper > dim:
        _roll = -lower % dim
    else:
        _start = sli.start
        _stop = sli.stop
    return _roll, _pad, _start, _stop, step


@staticmethod
def _get_children_classes():
    """
        Get the acitoolkit class of the children of this object.
        This is meant to be overridden by any inheriting classes that have children.
        If they don't have children, this will return an empty list.
        :return: list of classes
        """
    return []


def toSecondLevelDomain(url):
    """
    Module function to get a second level domain from the given URL.

    @param url URL to extract domain from
    @type QUrl
    @return name of second level domain
    @rtype str
    """
    topLevelDomain = url.topLevelDomain()
    urlHost = url.host()
    if not topLevelDomain or not urlHost:
        return ''
    domain = urlHost[:len(urlHost) - len(topLevelDomain)]
    if domain.count('.') == 0:
        return urlHost
    while domain.count('.') != 0:
        domain = domain[domain.find('.') + 1:]
    return domain + topLevelDomain


def create_customer_gateway(DryRun=None, Type=None, PublicIp=None, BgpAsn=None
    ):
    """
    Provides information to AWS about your VPN customer gateway device. The customer gateway is the appliance at your end of the VPN connection. (The device on the AWS side of the VPN connection is the virtual private gateway.) You must provide the Internet-routable IP address of the customer gateway's external interface. The IP address must be static and may be behind a device performing network address translation (NAT).
    For devices that use Border Gateway Protocol (BGP), you can also provide the device's BGP Autonomous System Number (ASN). You can use an existing ASN assigned to your network. If you don't have an ASN already, you can use a private ASN (in the 64512 - 65534 range).
    For more information about VPN customer gateways, see Adding a Hardware Virtual Private Gateway to Your VPC in the Amazon Virtual Private Cloud User Guide .
    See also: AWS API Documentation

    Examples
    This example creates a customer gateway with the specified IP address for its outside interface.
    Expected Output:

    :example: response = client.create_customer_gateway(
        DryRun=True|False,
        Type='ipsec.1',
        PublicIp='string',
        BgpAsn=123
    )

    :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 Type: string
    :param Type: [REQUIRED]
            The type of VPN connection that this customer gateway supports (ipsec.1 ).

    :type PublicIp: string
    :param PublicIp: [REQUIRED]
            The Internet-routable IP address for the customer gateway's outside interface. The address must be static.

    :type BgpAsn: integer
    :param BgpAsn: [REQUIRED]
            For devices that support BGP, the customer gateway's BGP ASN.
            Default: 65000

    :rtype: dict
    :return: {
        'CustomerGateway': {
            'CustomerGatewayId': 'string',
            'State': 'string',
            'Type': 'string',
            'IpAddress': 'string',
            'BgpAsn': 'string',
            'Tags': [
                {
                    'Key': 'string',
                    'Value': 'string'
                },
            ]
        }
    }

    """
    pass


def ancestors(migration, population):
    """
    Return the dependencies for ``migration`` from ``population``.

    :param migration: a :class:`~yoyo.migrations.Migration` object
    :param population: a collection of migrations
    """
    to_process = set()
    for m in migration.depends:
        to_process.add(m)
    deps = set()
    while to_process:
        m = to_process.pop()
        deps.add(m)
        for d in m.depends:
            if d in deps:
                continue
            deps.add(d)
            to_process.add(d)
    return deps


def __init__(factory, request):
    """Adapt field, factory and request."""


def scaling_factor(rect, size):
    """ Calculate the scaling factor for the current image to be
      resized to the new dimensions

  :param rect: (x, y, w, h) bounding rectangle of the face
  :param size: (width, height) are the desired dimensions
  :returns: floating point scaling factor
  """
    new_height, new_width = size
    rect_h, rect_w = rect[2:]
    height_ratio = rect_h / new_height
    width_ratio = rect_w / new_width
    scale = 1
    if height_ratio > width_ratio:
        new_recth = 0.8 * new_height
        scale = new_recth / rect_h
    else:
        new_rectw = 0.8 * new_width
        scale = new_rectw / rect_w
    return scale


@staticmethod
def format_num(n):
    """
        Intelligent scientific notation (.3g).

        Parameters
        ----------
        n  : int or float or Numeric
            A Number.

        Returns
        -------
        out  : str
            Formatted number.
        """
    f = '{0:.3g}'.format(n).replace('+0', '+').replace('-0', '-')
    n = str(n)
    return f if len(f) < len(n) else n


@classmethod
def from_dict(cls, transaction):
    """
        Creates a vote transaction

        :param transaction: transaction (dict)
        :return: (Vote)
        """
    self = cls(transaction['fee'], _error_use_class_method=False)
    self._sender_public_key = transaction['senderPublicKey']
    self._recipient_id = transaction['recipientId']
    self._timestamp = transaction['timestamp']
    self._asset['votes'] = transaction['asset']['votes']
    self.sign_from_dict(transaction)
    return self