def dump_uint_b_into(n, width, buffer, offset=0):
    """
    Serializes fixed size integer to the buffer
    :param n:
    :param width:
    :return:
    """
    for idx in range(width):
        buffer[idx + offset] = n & 255
        n >>= 8
    return buffer


def temperature(K, P, model, T_bc, t=1):
    """Apply Dirichlet boundary conditions

    """
    if T_bc is not None:
        for bound_line in T_bc(1, 1).keys():
            for line, n1, n2 in model.nodes_in_bound_line:
                if line == bound_line:
                    K[(n1), :] = 0.0
                    K[(n2), :] = 0.0
                    K[n1, n1] = 1.0
                    K[n2, n2] = 1.0
                    t1 = T_bc(model.XYZ[n1, 0], model.XYZ[n1, 1], t)
                    t2 = T_bc(model.XYZ[n2, 0], model.XYZ[n2, 1], t)
                    P[n1] = t1[line]
                    P[n2] = t2[line]
    return K, P


def edges_iter(G, nbunch=None):
    """Return iterator over edges incident to nodes in nbunch.

    Return all edges if nbunch is unspecified or nbunch=None.

    For digraphs, edges=out_edges
    """
    return G.edges_iter(nbunch)


def levenshtein(string1, string2):
    """ Measures the amount of difference between two strings.
        The return value is the number of operations (insert, delete, replace)
        required to transform string a into string b.
    """
    n, m = len(string1), len(string2)
    if n > m:
        string1, string2, n, m = string2, string1, m, n
    current = list(range(n + 1))
    for i in range(1, m + 1):
        previous, current = current, [i] + [0] * n
        for j in range(1, n + 1):
            insert, delete, replace = previous[j] + 1, current[j - 1
                ] + 1, previous[j - 1]
            if string1[j - 1] != string2[i - 1]:
                replace += 1
            current[j] = min(insert, delete, replace)
    return current[n]


def ofs_nbits(start, end):
    """
    The utility method for ofs_nbits

    This method is used in the class to set the ofs_nbits.

    This method converts start/end bits into ofs_nbits required to
    specify the bit range of OXM/NXM fields.

    ofs_nbits can be calculated as following::

      ofs_nbits = (start << 6) + (end - start)

    The parameter start/end  means the OXM/NXM field of ovs-ofctl command.

    ..
      field[start..end]
    ..

    +------------------------------------------+
    | *field*\\ **[**\\ *start*\\..\\ *end*\\ **]** |
    +------------------------------------------+

    ================ ======================================================
    Attribute        Description
    ================ ======================================================
    start            Start bit for OXM/NXM field
    end              End bit for OXM/NXM field
    ================ ======================================================
    """
    return (start << 6) + (end - start)


def _cc(recipient):
    """
    Returns a query item matching messages that have certain recipients in
    the cc field.

    Args:
        recipient (str): The recipient in the cc field to match.

    Returns:
        The query string.

    """
    return f'cc:{recipient}'


def gethref(input):
    """small function to extract a href link from a dictionary"""
    for ky, val in input.items():
        if ky.endswith('href'):
            return val
    return None


def EmptyScheduling(TaskMapping, GlobalDII):
    """
	Add one module per module type as key.
	"""
    Sched = {}
    for T, M in TaskMapping.items():
        if M not in Sched:
            DII = M.GetDataIntroductionInterval()
            SharingCapability = int(GlobalDII / DII)
            if SharingCapability < 1:
                Sched[M] = [None]
            else:
                Sched[M] = [None for i in range(SharingCapability)]
    return Sched


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

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

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


def check_domain_exists(conn, guestname, logger):
    """ check if the domain exists, may or may not be active """
    guest_names = []
    ids = conn.listDomainsID()
    for id in ids:
        obj = conn.lookupByID(id)
        guest_names.append(obj.name())
    if guestname not in guest_names:
        logger.error('%s is not running or does not exist' % guestname)
        return False
    else:
        return True


@staticmethod
def get_non_index_reads(summary):
    """
        Pick-out the reads which are not index reads

        :param summary: a Interop read summary object to parse the read numbers from
        :returns: all reads which are not index reads
        """
    non_index_reads = []
    for read_nbr in range(summary.size()):
        if not summary.at(read_nbr).read().is_index():
            non_index_reads.append(read_nbr)
    return non_index_reads


def makeNodeID(Rec, ndType, extras=None):
    """Helper to make a node ID, extras is currently not used"""
    if ndType == 'raw':
        recID = Rec
    else:
        recID = Rec.get(ndType)
    if recID is None:
        pass
    elif isinstance(recID, list):
        recID = tuple(recID)
    else:
        recID = recID
    extraDict = {}
    if extras:
        for tag in extras:
            if tag == 'raw':
                extraDict['Tag'] = Rec
            else:
                extraDict['Tag'] = Rec.get(tag)
    return recID, extraDict


def _add_transport_headers(headers):
    """
    Adds the transport framing headers, if needed. Naturally, this method
    cannot add a content-length header, so if there is no content-length header
    then it will add Transfer-Encoding: chunked instead. Should only be called
    if there is a body to upload.

    This should be a bit smarter: in particular, it should allow for bad or
    unexpected versions of these headers, particularly transfer-encoding.
    """
    transfer_headers = 'content-length', 'transfer-encoding'
    for header_name in headers:
        if header_name.lower() in transfer_headers:
            return
    headers['transfer-encoding'] = 'chunked'


def extract_status_code(json_response):
    """
    Extract the status code string from a JSON response
    """
    return json_response.get('result', {}).get('status')


@classmethod
def Filesearch(cls, _file_, _path_='C:'):
    """
        Return a list with all the files with the specified name in the specified path.
        """
    import os
    _path_ = _path_ + '\\'
    _result = []
    for RootDir, _Fldrs_, _FlsSrch_ in os.walk(_path_):
        for __files__ in _FlsSrch_:
            if __files__ == _file_:
                __pth = RootDir + '\\' + __files__
                _result.append(__pth)
    return _result


def generate_service_id(stop_times):
    """Generate service_id into stop_times DataFrame"""
    stop_times['service_id'] = None
    calendar_info = stop_times.drop_duplicates(subset=['vehicle_journey_id'])
    calendar_groups = calendar_info.groupby('weekdays')
    for weekday, cgroup in calendar_groups:
        vehicle_journey_ids = cgroup['vehicle_journey_id'].to_list()
        service_ref = cgroup['service_ref'].unique()[0]
        daygroup = cgroup['weekdays'].unique()[0]
        start_d = cgroup['start_date'].unique()[0]
        end_d = cgroup['end_date'].unique()[0]
        service_id = '%s_%s_%s_%s' % (service_ref, start_d, end_d, daygroup)
        stop_times.loc[stop_times['vehicle_journey_id'].isin(
            vehicle_journey_ids), 'service_id'] = service_id
    return stop_times


@staticmethod
def getJavaPackage():
    """ Returns package name String. """
    return 'com.microsoft.ml.spark.recommendation.SARModel'


def as_text(article):
    """Convert a Wikipedia article to Text object.
    Concatenates the sections in wikipedia file and rearranges other information so it
    can be interpreted as a Text object.

    Links and other elements with start and end positions are annotated
    as layers.

    Parameters
    ----------
    article: dict
        The wikipedia article (deserialized JSON).

    Returns
    -------
    estnltk.text.Text
        The Text object.
    """
    pass


@classmethod
def from_json(cls, c):
    """Builds a `Concept` from a json object."""
    id_ = c.get('id')
    label = c.get('label')
    freebase_id = c.get('freebaseIdentifier')
    return cls(id_, label, freebase_id)


@classmethod
def split(cls, dataset, start, end, datatype, **kwargs):
    """
        Splits a multi-interface Dataset into regular Datasets using
        regular tabular interfaces.
        """
    objs = []
    if datatype is None:
        for d in dataset.data[start:end]:
            objs.append(dataset.clone(d, datatype=cls.subtypes))
        return objs
    elif not dataset.data:
        return objs
    ds = cls._inner_dataset_template(dataset)
    for d in dataset.data:
        ds.data = d
        if datatype == 'array':
            obj = ds.array(**kwargs)
        elif datatype == 'dataframe':
            obj = ds.dframe(**kwargs)
        elif datatype == 'columns':
            if ds.interface.datatype == 'dictionary':
                obj = dict(d)
            else:
                obj = ds.columns(**kwargs)
        else:
            raise ValueError('%s datatype not support' % datatype)
        objs.append(obj)
    return objs


def update_ldap_attr_mappings_member(apps, schema_editor):
    """
    update groupOfNames.member
    """
    LDAPOCMappings = apps.get_model('sql_backend', 'LDAPOCMappings')
    LDAPAttrMapping = apps.get_model('sql_backend', 'LDAPAttrMapping')
    groupOfNames = LDAPOCMappings.objects.get(name='groupOfNames')
    member = LDAPAttrMapping.objects.filter(name='member', oc_map=groupOfNames
        ).first()
    if member:
        member.delete()
    for name, sel_expr, from_tables, join_where, create_proc, delete_proc, param_order, expect_return in [
        ('member', 'member_entries.dn',
        'ldap_group, ldap_group_member, ldap_entries AS member_entries',
        'ldap_group_member.user_id=member_entries.keyval and ldap_group_member.owner_id =ldap_group.id and member_entries.oc_map_id = 4'
        , None, None, 3, 0)]:
        LDAPAttrMapping.objects.create(oc_map=groupOfNames, name=name,
            sel_expr=sel_expr, from_tbls=from_tables, join_where=join_where,
            create_proc=create_proc, delete_proc=delete_proc, param_order=
            param_order, expect_return=expect_return)


@classmethod
def event_timeline(cls, event):
    """Retrieve event timeline url for status.gandi.net."""
    return '%s/timeline/events/%s' % (cls.base_url, event['id'])


def make_filename_by_table_var(table, variable, prefix=''):
    """Generate a filename (without extention) using table and variable names."""
    if prefix != '':
        prefix += '_'
    return prefix + variable + '_' + table


def occupancy_indicator(ch2bins, peak_sets):
    """
This function determines the occupancy indicator for each pair of bin and peak
set.

ch2bins = { chrom: [(start, end, summit, ID), ...], ... }, where bins for each
chromatin have been sorted based on (start, end), and ID's must range from 1
through the total number of bins. Each start coordinate must be strictly less
than the corresponding end site. Summit is not used in this function.

peak_sets is a list of peak sets, each having the format:
{ chrom: [(start, end, ...), ...], ... }, where peaks for each chromatin have
been sorted based on (start, end), and each start coordinate must be strictly
less than the corresponding end site.

Note: for ch2bins or each single peak set of peak_sets, there mustn't be a
region that is enclosed by another one.

Return value = [[0, 1, ...], ...]. For a bin of ID i, ret[i - 1][j] = 1 iff the
bin is occupied by the peak set at index j, which means the bin's middle point
falls within some peak of the set.

"""
    bin_num = sum(map(len, ch2bins.values()))
    sample_num = len(peak_sets)
    occupy = [None] * bin_num
    for i in range(bin_num):
        occupy[i] = [0] * sample_num
    for j, peak_set in enumerate(peak_sets):
        for ch in ch2bins:
            if ch not in peak_set:
                continue
            bins = ch2bins[ch]
            peaks = peak_set[ch]
            pind = 0
            for start, end, temp, id in bins:
                mid = (start + end - 1) // 2
                while pind < len(peaks):
                    s, e = peaks[pind][:2]
                    if mid < s:
                        break
                    if mid < e:
                        occupy[id - 1][j] = 1
                        break
                    pind += 1
                else:
                    break
    return occupy


@classmethod
def data2row(cls, data):
    """Convertit une probabilité allant être mise en cache en une ligne CSV."""
    return [data]


def describe_db_parameters(DBParameterGroupName=None, Source=None, Filters=
    None, MaxRecords=None, Marker=None):
    """
    Returns the detailed parameter list for a particular DB parameter group.
    See also: AWS API Documentation

    Examples
    This example lists information for up to the first 20 system parameters for the specified DB parameter group.
    Expected Output:

    :example: response = client.describe_db_parameters(
        DBParameterGroupName='string',
        Source='string',
        Filters=[
            {
                'Name': 'string',
                'Values': [
                    'string',
                ]
            },
        ],
        MaxRecords=123,
        Marker='string'
    )

    :type DBParameterGroupName: string
    :param DBParameterGroupName: [REQUIRED]
            The name of a specific DB parameter group to return details for.
            Constraints:
            Must be 1 to 255 alphanumeric characters
            First character must be a letter
            Cannot end with a hyphen or contain two consecutive hyphens

    :type Source: string
    :param Source: The parameter types to return.
            Default: All parameter types returned
            Valid Values: user | system | engine-default

    :type Filters: list
    :param Filters: This parameter is not currently supported.
            (dict) --This type is not currently supported.
            Name (string) -- [REQUIRED]This parameter is not currently supported.
            Values (list) -- [REQUIRED]This parameter is not currently supported.
            (string) --

    :type MaxRecords: integer
    :param MaxRecords: The maximum number of records to include in the response. If more records exist than the specified MaxRecords value, a pagination token called a marker is included in the response so that the remaining results can be retrieved.
            Default: 100
            Constraints: Minimum 20, maximum 100.

    :type Marker: string
    :param Marker: An optional pagination token provided by a previous DescribeDBParameters request. If this parameter is specified, the response includes only records beyond the marker, up to the value specified by MaxRecords .

    :rtype: dict
    :return: {
        'Parameters': [
            {
                'ParameterName': 'string',
                'ParameterValue': 'string',
                'Description': 'string',
                'Source': 'string',
                'ApplyType': 'string',
                'DataType': 'string',
                'AllowedValues': 'string',
                'IsModifiable': True|False,
                'MinimumEngineVersion': 'string',
                'ApplyMethod': 'immediate'|'pending-reboot'
            },
        ],
        'Marker': 'string'
    }

    """
    pass


def tracking_object_remove():
    """Remove object for tracking

    """
    pass


def instance_group(group_type, instance_type, instance_count, name=None):
    """
    Construct instance group

    :param group_type: instance group type
    :type group_type: ENUM {'Master', 'Core'}

    :param instance_type
    :type instance_type: ENUM {'g.small', 'c.large', 'm.medium', 's.medium'}

    :param instance_count
    :type instance_count: int

    :param name: instance group name
    :type name: string
    """
    instance_group = {'type': group_type, 'instanceCount': instance_count,
        'instanceType': instance_type}
    if name is not None:
        instance_group['name'] = name
    return instance_group


def hour_angle_deg(true_solar_time):
    """Returns Hour Angle in Degrees, with True Solar Time, true_solar_time."""
    if true_solar_time / 4 < 0:
        hour_angle_deg = true_solar_time / 4 + 180
    else:
        hour_angle_deg = true_solar_time / 4 - 180
    return hour_angle_deg


def escape_string(s):
    """Escape a string as a literal value for use in an Xquery expression."""
    return s.replace('"', '""').replace('&', '&')


def delete_domain_name(domainName=None):
    """
    Deletes the  DomainName resource.
    See also: AWS API Documentation

    :example: response = client.delete_domain_name(
        domainName='string'
    )

    :type domainName: string
    :param domainName: [REQUIRED]
            The name of the DomainName resource to be deleted.

    """
    pass


def google_map_view(context):
    """
    Dependencies for google_map_view gizmo.
    """
    return ('tethys_gizmos/vendor/farbtastic/farbtastic.css',
        'tethys_gizmos/vendor/farbtastic/farbtastic.js',
        'tethys_gizmos/js/tethys_google_map_view.js')


def interaction_plot():
    """
    Interaction plot
    """
    pass


def sg_inject_func(func):
    """Converts the function `func` to a sugar function
    so that it can be used in a chainable manner.

    Args:
      func: A function to inject.

    Returns:
      None
    """
    exec('tf.Variable.%s = func' % func.__name__)
    exec('tf.Tensor.%s = func' % func.__name__)


def encodePassword(password):
    """Return encoded data for the given password

        Return encoded bytes.
        """


def set_layout_hook(session, hook_name):
    """Set layout hooks to normalize layout.

    References:

        - tmuxp issue: https://github.com/tmux-python/tmuxp/issues/309
        - tmux issue: https://github.com/tmux/tmux/issues/1106

    tmux 2.6+ requires that the window be viewed with the client before
    select-layout adjustments can take effect.

    To handle this, this function creates temporary hook for this session to
    iterate through all windows and select the layout.

    In order for layout changes to take effect, a client must at the very
    least be attached to the window (not just the session).

    hook_name is provided to allow this to set to multiple scenarios, such
    as 'client-attached' (which the user attaches the session). You may
    also want 'after-switch-client' for cases where the user loads tmuxp
    sessions inside tmux since tmuxp offers to switch for them.

    Also, the hooks are set immediately unbind after they're invoked via -u.

    Parameters
    ----------
    session : :class:`libtmux.session.Session`
        session to bind hook to
    hook_name : str
        hook name to bind to, e.g. 'client-attached'
    """
    cmd = ['set-hook', '-t', session.id, hook_name]
    hook_cmd = []
    attached_window = session.attached_window
    for window in session.windows:
        hook_cmd.append('selectw -t {}'.format(window.id))
        hook_cmd.append('selectl'.format(window.id))
        hook_cmd.append('selectw -p'.format(window.id))
    hook_cmd.append('set-hook -u -t {target_session} {hook_name}'.format(
        target_session=session.id, hook_name=hook_name))
    hook_cmd.append('selectw -t {}'.format(attached_window.id))
    hook_cmd = '{}'.format('; '.join(hook_cmd))
    cmd.append(hook_cmd)
    session.cmd(*cmd)


def apply_generic_variability(tmodel, va, inplace=True):
    """
    Reactions a dealt with cobra, but the other variables added use pytfa's
    interface: the class GenericVariable. We use a different method to apply
    variability directly in the solver

    :param tmodel:
    :param va:
    :param inplace:
    :return:
    """
    if inplace:
        _tmodel = tmodel
    else:
        _tmodel = tmodel.copy()
    for varname in va.index:
        the_min, the_max = va.loc[varname, ['minimum', 'maximum']]
        _tmodel._var_dict[varname].variable.lb = the_min
        _tmodel._var_dict[varname].variable.ub = the_max
    return _tmodel


def change_tarinfo_properties(tarinfo):
    """
    Filter for insertion local file to tar archive.

    * tarinfo: tarinfo to insert
    * **return:** original tarinfo with changed permissions
    """
    tarinfo.uid = 0
    tarinfo.gid = 0
    return tarinfo


@classmethod
def sink_path(cls, project, sink):
    """Returns a fully-qualified sink resource name string."""
    return cls._SINK_PATH_TEMPLATE.render({'project': project, 'sink': sink})


@classmethod
def echo(cls, msg):
    u"""write line to UI"""
    cls.write(msg + '\n')


@classmethod
def register(cls, fmt):
    """ Register a format object."""
    for ext in fmt.file_extensions:
        cls._ext_map['.' + ext.lower()] = fmt


@staticmethod
def _deprecated_message(new_arg_name, deprecated_from='2.x'):
    """ Alerts the user that an argument will be deprecated within the
        next release version
        """
    msg = (
        'Deprecated argument (it will be dropped from version {} onwards) please use --{} instead.'
        .format(deprecated_from, new_arg_name))
    return msg


def is_delegated(delegated_names, name):
    """
    Tests a name to see if it is in a delegated zone.

    :param list delegated_names: List of non-apex dns.name.Names in zone with NS RRSets.
    :param obj name: The dns.name.Name to test.
    :return: True if name is delegated, False otherwise.
    """
    for deleg_name in delegated_names:
        if name.is_subdomain(deleg_name):
            return True
    return False


def iter_transactions(cursor):
    """
        Iterate over the transaction log, newest first.

        Skips packed transactions. Yields (tid, username, description,
        extension) for each transaction.
        """


def entries(daterange):
    """ Returns a list of non repeating and non overlapping time entries to cover the provided date range
        """


@classmethod
def parse_query_output(cls, out):
    """
        Example output to parse:
        141914132 user_name DONE queue_name exec_host b63cee711a job_name Feb 8 14:54
        """
    query_data = {}
    for line in out.strip().split('\n'):
        parts = line.split()
        if len(parts) < 6:
            continue
        job_id = parts[0]
        status_flag = parts[2]
        status = cls.map_status(status_flag)
        query_data[job_id] = cls.job_status_dict(job_id=job_id, status=status)
    return query_data


def __delitem__(key):
    """Removes the annotation stored under key.

        Raises a KeyError if the key is not found.
        """


def truncate_or_pad(sequence, block_size, pad_token_id):
    """ Adapt the source and target sequences' lengths to the block size.
    If the sequence is shorter we append padding token to the right of the sequence.
    """
    if len(sequence) > block_size:
        return sequence[:block_size]
    else:
        sequence.extend([pad_token_id] * (block_size - len(sequence)))
        return sequence


@staticmethod
def add_opts(parser):
    """Populate and return the parser with the options for this plugin.

        If the plugin does not need any options, it should return the same
        parser untouched.
        """
    return parser


def get_percentage(position: int, length: int) ->str:
    """Format completion percentage in square brackets."""
    percentage_message = f'{position * 100 // length}%'.rjust(4)
    return f'[{percentage_message}]'


def dict_find_key(dd, value):
    """ Find first suitable key in dict.

    :param dd:
    :param value:
    :return:
    """
    key = next(key for key, val in dd.items() if val == value)
    return key


def smoothscroll():
    """Smooth scroll to make editable file visible

    """
    pass


def sanitize_wwpn_for_api(wwpn):
    """Updates the format of the WWPN to match the expected PowerVM format.

    :param wwpn: The original WWPN.
    :return: A WWPN of the format expected by the API.
    """
    return wwpn.upper().replace(':', '')


def test_command():
    """This is the shortdoc for 'test'

	More documentation can be put here. It will only show up when you call the help for this command, i.e. ``feature-command-doc.py help test``.
	It can be as long as you want and should describe what this command does.
	"""
    pass


def sub(x, y):
    """
    Substract two integers
    :param x: first integer
    :param y: second interger
    :return: result of the operation
    """
    return x - y


def assoc_in(d, ks, v):
    """
    Associates a value in a nested associative structure, where `ks` is a
    sequence of keys and `v` is the new value, and returns a nested structure.
    If any levels do not exist, `dict`s will be created.
    """
    ks_ = ks[:-1]
    last = ks[-1]
    d_ = d
    for k in ks_:
        if k not in d_:
            d_[k] = {}
        d_ = d_[k]
    d_[last] = v
    return d


def cache_get(key, cache=None):
    """Gets a value from the cache.

    .. warning:: Bytes are returned for Python 3.

    :param str|unicode key: The cache key to get value for.

    :param str|unicode cache: Cache name with optional address (if @-syntax is used).

    :rtype: bytes|str|None
    """


def get_default_os_string():
    """helper function to consistently return the default os for windows files"""
    return 'Win10'


def getDmax(peaks):
    """needs a doc string"""
    return peaks[0][-2]


@staticmethod
def format(keys, value, _type):
    """
        General format function.

        >>> StatsdClient.format("example.format", 2, "T")
        {'example.format': '2|T'}
        >>> formatted = StatsdClient.format(("example.format31", "example.format37"), "2", "T")
        >>> formatted['example.format31'] == '2|T'
        True
        >>> formatted['example.format37'] == '2|T'
        True
        >>> len(formatted)
        2
        """
    data = {}
    value = '{0}|{1}'.format(value, _type)
    if not isinstance(keys, (list, tuple)):
        keys = [keys]
    for key in keys:
        data[key] = value
    return data


def get_file_source(filename):
    """Read the source of a file.

    This convenience function is present to match the interface of get_module_source.
    """
    with open(filename, 'r') as f:
        return f.read()


@staticmethod
def is_xml_tree(el):
    """Check if element (or document) is from a XML tree."""
    return el._is_xml


def _get_template_params(template, param_values):
    """Return all required parameter values for the specified template.
    :param dict template: Template JSON object.
    :param dict param_values: User provided parameter values.
    """
    param_keys = {}
    try:
        for param, values in template['parameters'].items():
            if 'type' not in values:
                raise ValueError('Parameter {} does not have type defined'.
                    format(param))
            try:
                value = param_values[param]
                if isinstance(value, dict) and value.get('value') != None:
                    param_keys[param] = value.get('value')
                else:
                    param_keys[param] = value
            except KeyError:
                param_keys[param] = values.get('defaultValue')
    except KeyError:
        pass
    return param_keys


def rollback_quietly():
    """
        Rollback the connection and return a true value on success.

        When this completes, the connection will be in a neutral state,
        not idle in a transaction.

        If an error occurs during rollback, the connection is dropped
        and a false value is returned.
        """


def csv_to_set(x):
    """Convert a comma-separated list of strings to a set of strings."""
    if not x:
        return set()
    else:
        return set(x.split(','))


def get_attribute(get_from, prop_name, default=None):
    """
    Get attribute from object with name <prop_name>, or take it from function get_<prop_name>
    :param get_from: instance of object
    :param prop_name: name of attribute (str)
    :param default: what to return if attribute doesn't exist
    :return: value of attribute <prop_name> or default
    """
    prop = getattr(get_from, prop_name, None)
    if not prop:
        prop_func = getattr(get_from, 'get_{}'.format(prop_name), None)
        if prop_func:
            prop = prop_func()
    if prop is None:
        prop = default
    return prop


def ensure_valid_kernel_type(specified_kernel, kernel_type_list):
    """
    Checks to make sure that `specified_kernel` is in `kernel_type_list` and
    raises a helpful error if this is not the case.

    Parameters
    ----------
    specified_kernel : str.
        Denotes the user-specified kernel class that is to be checked.
    kernel_type_list : list of strings.
        Contains all of the valid kernel classes types.

    Returns
    -------
    None.
    """
    if specified_kernel not in kernel_type_list:
        msg_1 = 'The kernel_type specified was not valid.'
        msg_2 = 'Valid kernel-types are {}'.format(kernel_type_list)
        msg_3 = 'The passed kernel_type was: {}'.format(specified_kernel)
        total_msg = '\n'.join([msg_1, msg_2, msg_3])
        raise ValueError(total_msg)
    return None


def nb_of_attrs_mismatch(source, target):
    """Generate a query which returns the number of attributes of a node which
    are not in its image."""
    query = (
        """REDUCE(invalid = 0, k in filter(k in keys({}) WHERE k <> 'id' AND k <> 'count') |
"""
        .format(source) + '\tinvalid + CASE\n' +
        '\t\tWHEN NOT k IN keys({}) THEN 1\n'.format(target) +
        """		ELSE REDUCE(invalid_values = 0, v in {}[k] |
""".format(source
        ) + '\t\t\tinvalid_values + CASE {}[k]\n'.format(target) +
        """				WHEN ['IntegerSet'] THEN CASE WHEN toInt(v) IS NULL THEN 1 ELSE 0 END
"""
         +
        "\t\t\t\tWHEN ['StringSet'] THEN CASE WHEN toString(v) <> v THEN 1 ELSE 0 END\n"
         +
        """				WHEN ['BooleanSet'] THEN CASE WHEN v=true OR v=false THEN 0 ELSE 1 END
"""
         + '\t\t\t\tELSE CASE WHEN NOT v IN {}[k] THEN 1 ELSE 0 END END)\n'
        .format(target) + '\t\tEND)')
    return query


def listify(d):
    """
  Turn dicts to single-element lists
  """
    if isinstance(d, list):
        return d
    elif isinstance(d, dict):
        return [d]


def filter_alpha(Input_Dict):
    """
    Filter alpha parameter.

    :param Input_Dict: input parameters dictionary
    :type Input_Dict : dict
    :return: modified dictionary
    """
    try:
        if Input_Dict['alpha'] > 1:
            Input_Dict['alpha'] = 1
            print(
                '[Warning] Opem Automatically Set Alpha To Maximum Value (1) ')
        elif Input_Dict['alpha'] < 0:
            Input_Dict['alpha'] = 0
            print(
                '[Warning] Opem Automatically Set Alpha To Maximum Value (0) ')
        return Input_Dict
    except Exception:
        return Input_Dict


def GetConsensusData(header):
    """

    gets the address of the consensus

    """
    pass


def b2mb(num):
    """ convert Bs to MBs and round down """
    return int(num / 2 ** 20)


def _parse_datetime(s):
    """Parse a date/time string.

    The string should be in an ISO 8601 format except that the date and time
    parts may be separated by a space or colon instead of T.
    """
    import dateutil.parser as du
    return du.parse(s)


def calcs(MW, Mvar):
    """ Calculates S from MW and Mvar"""
    return (MW ** 2 + Mvar ** 2) ** 0.5


def has_valid_token(client):
    """Does the session have a valid token?"""
    return client.authorized


@classmethod
def from_api_data(cls, data):
    """Creates a new Customer object from API data from ticketswitch.

        Args:
            data (dict): the part of the response from a ticketswitch API call
                that concerns a customer.

        Returns:
            :class:`Customer <pyticketswitch.customer.Customer>`: a new
            :class:`Customer <pyticketswitch.customer.Customer>` object
            populated with the data from the api.

        """
    kwargs = {'first_name': data.get('first_name'), 'first_name_latin':
        data.get('first_name_latin'), 'last_name': data.get('last_name'),
        'last_name_latin': data.get('last_name_latin'), 'title': data.get(
        'title'), 'title_latin': data.get('title_latin'), 'initials': data.
        get('initials'), 'initials_latin': data.get('initials_latin'),
        'suffix': data.get('suffix'), 'suffix_latin': data.get(
        'suffix_latin'), 'country_code': data.get('country_code'),
        'post_code': data.get('postcode'), 'post_code_latin': data.get(
        'postcode_latin'), 'town': data.get('town'), 'town_latin': data.get
        ('town_latin'), 'county': data.get('county'), 'county_latin': data.
        get('county_latin'), 'country': data.get('country'),
        'country_latin': data.get('country_latin'), 'email': data.get(
        'email_addr'), 'phone': data.get('phone'), 'home_phone': data.get(
        'home_phone'), 'work_phone': data.get('work_phone'),
        'agent_reference': data.get('agent_ref'), 'supplier_can_use_data':
        data.get('dp_supplier'), 'user_can_use_data': data.get('dp_user'),
        'world_can_use_data': data.get('dp_world')}
    address_line_one = data.get('addr_line_one')
    address_line_two = data.get('addr_line_two')
    address_line_one_latin = data.get('addr_line_one_latin')
    address_line_two_latin = data.get('addr_line_two_latin')
    address_lines = []
    if address_line_one:
        address_lines.append(address_line_one)
    if address_line_two:
        address_lines.append(address_line_two)
    address_lines_latin = []
    if address_line_one_latin:
        address_lines_latin.append(address_line_one_latin)
    if address_line_two_latin:
        address_lines_latin.append(address_line_two_latin)
    kwargs.update(address_lines=address_lines, address_lines_latin=
        address_lines_latin)
    return cls(**kwargs)


def trailing_whitespace(editor, item):
    """ Pylint method to fix trailing-whitespace error """
    line_no = item.line_no
    repaired_line = editor.lines[line_no].rstrip()
    loc = line_no, line_no + 1
    editor.replace_range(loc, [repaired_line])
    return line_no, 0


def car(obj):
    """
    Alias of ``obj[0]``.

    >>> car(loads('(a . b)'))
    Symbol('a')
    >>> car(loads('(a b)'))
    Symbol('a')

    """
    return obj[0]


def get_complete_version(version=None):
    """
    Return a tuple of the django version. If version argument is non-empty,
    check for correctness of the tuple provided.
    """
    if version is None:
        from django import VERSION as version
    else:
        assert len(version) == 5
        assert version[3] in ('alpha', 'beta', 'rc', 'final')
    return version


def parameter(parameterName, value):
    """
    Encode a simple parameter for yaml data.

    :param parameterName: Name of yaml parameter.
    :param value: Parameter value in a format suitable for output to yaml.
    :return: Yaml data structure.
    """
    return {parameterName: value}


def _upload_file(sftp, local_file, remote_file):
    """ Upload a file using existent sftp session
    :param sftp: sftp session object
    :param local_file: either a file path or a file-like object to be uploaded.
    :param remote_file: a remote file path where the uploaded file will be
        placed.

    """
    if hasattr(local_file, 'read'):
        sftp.putfo(local_file, remote_file)
    else:
        sftp.put(local_file, remote_file)


@classmethod
def get_artifacts(cls, artifacts_to_prefetch):
    """
        Return a list of (sha, obj_blob) for all the object_path(s) specified in
        `artifacts_to_prefetch`.
        """
    raise NotImplementedError()


def asId(v, default=0):
    """
    The *asId* method transforms the *value* attribute either to an instance of @
    int@ or to @None@, so it can be used as *id* field in a @Record@
    instance. If the value cannot be converted, then the optional *default* (default value is @0
    @) is answered.

    >>> asId(123) == 123
    True
    >>> asId('abcd', 'ABCD')
    'ABCD'
    """
    try:
        v = int(v)
        if v <= 0:
            return default
        return v
    except (ValueError, TypeError):
        return default


def iter_delete_duplicates(iter, key=lambda x: x):
    """Yields non-repeating (and consecutive) items from `iter`.

    `key` has the same meaning as in `delete_duplicates`:func:.

    Examples:

      >>> list(iter_delete_duplicates('AAAaBBBA'))
      ['A', 'a', 'B', 'A']

      >>> list(iter_delete_duplicates('AAAaBBBA', key=lambda x: x.lower()))
      ['A', 'B', 'A']

    .. versionadded:: 1.7.4

    """
    last = object()
    for x in iter:
        k = key(x)
        if k != last:
            yield x
        last = k


def _scatter_elemwise_div(lhs=None, rhs=None, name=None, attr=None, out=
    None, **kwargs):
    """Divides arguments element-wise.  If the left-hand-side input is 'row_sparse', then
    only the values which exist in the left-hand sparse array are computed.  The 'missing' values
    are ignored.

    The storage type of ``_scatter_elemwise_div`` output depends on storage types of inputs

    - _scatter_elemwise_div(row_sparse, row_sparse) = row_sparse
    - _scatter_elemwise_div(row_sparse, dense) = row_sparse
    - _scatter_elemwise_div(row_sparse, csr) = row_sparse
    - otherwise, ``_scatter_elemwise_div`` behaves exactly like elemwise_div and generates output
    with default storage

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

    name : string, optional.
        Name of the resulting symbol.

    Returns
    -------
    Symbol
        The result symbol.
    """
    return 0,


def textBitmap(text, width, height, fontSize, fgColour, bgColour, alpha=1.0):
    """Draw some text using :mod:`matplotlib`.

    The rendered text is returned as a RGBA bitmap within a ``numpy.uint8``
    array of size :math:`w \\times h \\times 4`, with the top-left pixel
    located at index ``[0, 0, :]``.

    :arg text:     Text to render.

    :arg width:    Width in pixels.

    :arg height:   Height in pixels.

    :arg fontSize: Font size in points.

    :arg fgColour: Foreground (text) colour - can be any colour specification
                   that is accepted by :mod:`matplotlib`.

    :arg bgColour: Background colour  - can be any colour specification that
                   is accepted by :mod:`matplotlib`..

    :arg alpha:    Text transparency, in the range ``[0.0 - 1.0]``.
    """
    import numpy as np
    import matplotlib.backends.backend_agg as mplagg
    import matplotlib.figure as mplfig
    dpi = 96.0
    fig = mplfig.Figure(figsize=(width / dpi, height / dpi), dpi=dpi)
    canvas = mplagg.FigureCanvasAgg(fig)
    ax = fig.add_axes([0, 0, 1, 1])
    ax.axis('off')
    if bgColour is not None:
        fig.patch.set_facecolor(bgColour)
    else:
        fig.patch.set_alpha(0)
    ax.set_xticks([])
    ax.set_yticks([])
    ax.text(0.5, 0.5, text, fontsize=fontSize, verticalalignment='center',
        horizontalalignment='center', transform=ax.transAxes, color=
        fgColour, alpha=alpha)
    fig.subplots_adjust(bottom=0, top=1, left=0, right=1)
    canvas.draw()
    buf = canvas.tostring_argb()
    ncols, nrows = canvas.get_width_height()
    bitmap = np.frombuffer(buf, dtype=np.uint8)
    bitmap = bitmap.reshape(nrows, ncols, 4)
    rgb = bitmap[:, :, 1:]
    a = bitmap[:, :, (0)]
    bitmap = np.dstack((rgb, a))
    return bitmap


def nstep(a):
    """ Return negative logic step function
        ^....
        |   |
        |___|________
            a
    """
    return lambda x: 1.0 if x <= a else 0.0


def get_bases_at_site_fetch(alignment_obj, chromosome, position,
    reference_base, alternative_base):
    """

    So to convert INS from 0 to 1-based system:
    start = start + 1; end = end + 1
    and to convert INS from 1 to 0-based system:
    start = start - 1; end = end - 1

    :param alignment_obj:
    :param chromosome:
    :param position:
    :return:
    """
    position = int(position)
    base_list = []
    counts = alignment_obj.count_coverage(chromosome, position, position + 1)
    base_list = []
    print(counts[0][0])
    """
    # for read in alignment_obj.fetch(chromosome,  position, position + 1, multiple_iterators=True):
        print(read.__dict__)
        if not read.is_duplicate:
            for i in range(len(read.query_sequence)):
                tmp_global_pos = read.pos + i
    """
    return base_list


def compile_dict_sub(brown_clusters_path=None, user_dicts=[]):
    """
  Takes in a list of tuples of form (DICT_LABEL, set_of_words)
  AND/OR a file path to a tsv file list of (word, brown cluster id) lines
  And returns a single dictionary mapping from word -> DICT_LABEL, based on priority ordering
  Assume user dicts take priority over brown clusters...
  """
    dict_sub = {}
    for dict_label, words in user_dicts:
        for word in words:
            if word not in dict_sub:
                dict_sub[word] = dict_label
    if brown_clusters_path is not None:
        with open(brown_clusters_path, 'rb') as f:
            for line in f:
                word, cluster_id = line.rstrip().split('\t')
                dict_sub[word] = 'BC-%s' % cluster_id
    return dict_sub


def _get_pos_mapping(doc, normalize, pos_filter=['NOUN', 'PROPN', 'ADJ',
    'VERB', 'ADV', 'SYM', 'PUNCT']):
    """
    Iterates through the doc and finds the pos_tag corresponding to each
    token. This is then mapped to the token's normalized form.
    Since the same word can have multiple different POS tags, only the tag
    present in pos_filter is kept. If multiple tags are present in pos_filter,
    then the update sequence of the dictionary determines which one is kept.
    """
    mapping = dict()
    if normalize == 'lemma':
        for token in doc:
            if token.pos_ in pos_filter or token.lemma_ not in mapping.keys():
                mapping.update({token.lemma_: token.pos_})
    elif normalize == 'lower':
        for token in doc:
            if token.pos_ in pos_filter or token.lower_ not in mapping.keys():
                mapping.update({token.lower_: token.pos_})
    else:
        for token in doc:
            if token.pos_ in pos_filter or token.text not in mapping.keys():
                mapping.update({token.text: token.pos_})
    return mapping


def decode_modm(limbs):
    """
    Decodes scalar mod m from limbs with base 30
    :param n:
    :return:
    """
    n = 0
    c = 0
    shift = 0
    mask = (1 << 30) - 1
    for i in range(9):
        n += (limbs[i] & mask) + c << shift
        c = limbs[i] >> 30
        shift += 30
    return n


@classmethod
def _from_dict(cls, _dict):
    """Initialize a AnalyticsEngineCreateCustomizationResponse object from a json dictionary."""
    return cls.from_dict(_dict)


def _raise(ex=None):
    """Wrapper for exceptions so they can be thrown from inside lambdas"""
    exception = []
    if ex:
        exception.append(ex)
    if len(exception):
        raise exception.pop()


def percentage(value, total, multiply=True, fail_silently=True):
    """
    Accepts two integers, a value and a total.

    The value is divided into the total and then multiplied by 100,
    returning its percentage as a float.

    If you don't want the number multiplied by 100, set the 'multiply'
    kwarg to False.

    If you divide into zero -- an illegal operation -- a null value
    is returned by default. If you prefer for an error to be raised,
    set the kwarg 'fail_silently' to False.

    h3. Example usage

        >>> import calculate
        >>> calculate.percentage(2, 10)
        20.0
        >>> calculate.percentage(2,0, multiply=False)
        0.20000000000000001
        >>> calculate.percentage(2,0)
        >>> calculate.percentage(2,0, fail_silently=False)
        ZeroDivisionError

    h3. Documentation

        * "percentage":http://en.wikipedia.org/wiki/Percentage
    """
    try:
        percent = value / float(total)
        if multiply:
            percent = percent * 100
        return percent
    except ZeroDivisionError:
        if fail_silently:
            return None
        else:
            raise ZeroDivisionError("Sorry. You can't divide into zero.")


@staticmethod
def p_message_size(p):
    """message_size : NUMERIC"""
    p[0] = p[1]


@classmethod
def from_sqla(cls, sqla_obj):
    """ Create a yalchemy ForeignKey from a sqlalchemy ForeignKeyConstraint

        Arguments:
            sqla_obj: The sqlalchemy ForeignKeyConstraint object.
        """
    assert len(sqla_obj.column_keys) == 1
    assert len(sqla_obj.elements) == 1
    target_table, target_col = sqla_obj.elements[0].target_fullname.rsplit('.',
        1)
    return cls(sqla_obj.column_keys[0], target_table, target_col)


def select_less():
    """Deselect objects at the boundaries of parent/child relationships

    """
    pass


def idsInOrder():
    """ Return all object ids, in the correct order """


@staticmethod
def get_true_niche(niche, threshold=0.25):
    """Select cells with good level of niche adequacy."""
    true_niche = niche >= threshold
    return true_niche


def loop_strand(cs):
    """
    Get the closed loop starting at crossing strand cs
    """
    strand = [cs]
    cs = cs[0].adjacent[(cs[1] + 2) % 4]
    while cs not in strand:
        strand.append(cs)
        cs = cs[0].adjacent[(cs[1] + 2) % 4]
    return strand


@classmethod
def decomment(cls, line, char='/', repeat=2, esc='\\'):
    """ where we decomment comments char is a single
			that need to be repeated atleast 2 times or repeat times
			line that need to be decommented
			Note - There is escape of comment with esc
			"""
    prevprevc = prevc = o = ''
    dqon = sqon = mpos = commenton = 0
    ccount = 1
    firstentry = 1
    for i, c in enumerate(line):
        if commenton:
            if firstentry:
                o = o[0:len(o) - repeat]
                firstentry = 0
            continue
        elif c == '"':
            if dqon:
                dqon = 0
            else:
                dqon = 1
            o += c
        elif c == "'":
            if sqon:
                sqon = 0
            else:
                sqon = 1
            o += c
        elif c == char and not sqon and not dqon:
            if prevc == c:
                ccount += 1
            else:
                ccount = 1
            o += c
            if ccount == repeat:
                if prevprevc == esc:
                    commenton = 0
                    cc = ''
                    for i in range(repeat):
                        o = o[0:-1]
                        cc += char
                    o = o[0:-1] + cc
                else:
                    commenton = 1
        else:
            o += c
        if prevc:
            prevprevc = prevc
        prevc = c
    return o


@staticmethod
def push_notification(name, updates, original):
    """
        Ignore this request, as we want to handle the notification separately in update
        """
    pass


@classmethod
def supports_replay_gain(cls):
    """returns True if this class supports ReplayGain"""
    return True


def _proportion(a, b):
    """ Return the len(a & b) / len(a) """
    return 1.0 * len(a & b) / len(a)


def sanitize_df(df, d_round=2, **options):
    """All dataframe cleaning and standardizing logic goes here."""
    for c in df.columns[df.dtypes == float]:
        df[c] = df[c].round(d_round)
    return df


@classmethod
def set_game_display(cls, screen, screen_width, screen_height):
    """
        set the screen reference
        :param screen: the pygame's screen object
        :param screen_width:
        :param screen_height:
        """
    cls.game_display = screen
    cls.screen_width = screen_width
    cls.screen_height = screen_height


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

        :param AllowDownloadDisabledDetails val:
        :rtype: EventDetails
        """
    return cls('allow_download_disabled_details', val)


def dummy_callback(*_, **__):
    """ A dummy callable. """
    return 1


@staticmethod
def _subscribe_broadcast(sub_id, channel, callback, **kwargs):
    """Listen to a broadcast topic, notify via callback function.
        :param sub_id: ID for this subscription in the transport layer
        :param channel: Topic name to subscribe to
        :param callback: Function to be called when messages are received
        :param **kwargs: Further parameters for the transport layer. For example
               retroactive: Ask broker to send old messages if possible
        """
    raise NotImplementedError('Transport interface not implemented')


def forge_nat(value) ->bytes:
    """
    Encode a number using LEB128 encoding (Zarith)
    :param int value: the value to encode
    :return: encoded value
    :rtype: bytes
    """
    if value < 0:
        raise ValueError('Value cannot be negative.')
    buf = bytearray()
    more = True
    while more:
        byte = value & 127
        value >>= 7
        if value:
            byte |= 128
        else:
            more = False
        buf.append(byte)
    return bytes(buf)


def tile(srf, tile=0, cols=1, rows=1, padding=0):
    """Return a tile subsurface"""
    w, h = srf.get_size()
    n = cols * rows
    if tile < 0:
        tile += n
    if tile >= n or tile < 0:
        raise IndexError('tile index is out of range')
    w = w // cols
    h = h // rows
    x = tile % cols * w + padding
    y = tile // cols * h + padding
    padding *= 2
    return srf.subsurface(x, y, w - padding, h - padding)


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


@classmethod
def edit_form_entry_edit_option_html(cls):
    """For adding the edit link to edit form entry view.

        :return str:
        """
    return (
        """

              {edit_text}

            """
        .format(edit_url='{edit_url}', edit_option_class=cls.
        form_edit_form_entry_option_class, edit_text='{edit_text}'))


def get_filename_from_uri(uri):
    """Get filename from the URI.

    :param uri: the URI
    :return: the filename
    """
    return uri.rpartition('/')[-1]


@classmethod
def _decode(cls, packet, key_handler):
    """Decode an SSH certificate"""
    raise NotImplementedError


def hfloat(f, p=5):
    """Convert float to value suitable for humans.

    Arguments:
        f (float): The floating point number.
        p (int): Floating point precision (default is 5).

    Copied from celery
    """
    i = int(f)
    return i if i == f else '{0:.{p}}'.format(f, p=p)


def find_notification(notification_name, notification_defs):
    """ Find a notification by name in a list of notification definitions.

    :param notification_name: the name of the notification to look for.
    :param notification_defs: a list of notification definitions.
    :return: the notification_def with matching name, or None.
    """
    for notification_def in notification_defs:
        if notification_def.name == notification_name:
            return notification_def
    return None


def plot_residual_error(ax, x, y, y_hat, n_bins=50, alpha=0.7, s=2):
    """ Plots all the residuals from y and 'y_hat' across x
        INPUT:
            dataframe:
                dataframe of floats or invts
            x:
                a dataframe,list or array of ints or floats
            y
                a dataframe,list or array of ints or floats
            y_hat:
                a array of y values you predicted from x to be compared with the values of y
        OUTPUT:
            A plot showing the residuals across x (error)
    """
    residuals = y - y_hat
    ax.axhline(0, color='black', linestyle='--')
    ax.scatter(x, residuals, color='red', alpha=alpha, s=s)
    ax.set_ylabel('Residuals ($y - \\hat y$)')


def factor(n, p=2):
    """
    Compute n-1 = 2^s * d for strong psuedoprime and strong lucas psuedoprime.
    """
    s = 0
    n -= 1
    while not n % p:
        s += 1
        n //= p
    return s, n


def get_api_url(method):
    """
    Returns API URL for the given method.

    :param method: Method name
    :type method: str

    :returns: API URL for the given method
    :rtype: str
    """
    return 'https://slack.com/api/{}'.format(method)


def find_most_common_color(image):
    """
    Find pixel color that is the most commond use in image
    image: an Image object
    return: the most commond color
    """
    width, height = image.size
    pixel = image.getcolors(width * height)
    common_color = max(pixel, key=lambda t: t[0])
    return common_color[1]


def set_param(current_scene_db, parameter, value):
    """set or update an parameter variable"""
    from src.praxxis.sqlite import connection
    conn = connection.create_connection(current_scene_db)
    cur = conn.cursor()
    set_param = (
        'INSERT OR IGNORE INTO "Parameters"(Parameter, Value) VALUES(?,?)')
    upate_param = 'UPDATE "Parameters" SET Value = ? WHERE Parameter = ?'
    cur.execute(set_param, (parameter, value))
    cur.execute(upate_param, (value, parameter))
    conn.commit()
    conn.close()


def lookupMailGroup(name, timeout=None):
    """
        Perform an MG record lookup.

        @type name: C{str}
        @param name: DNS name to resolve.

        @type timeout: Sequence of C{int}
        @param timeout: Number of seconds after which to reissue the query.
            When the last timeout expires, the query is considered failed.

        @rtype: L{Deferred}
        @return: A L{Deferred} which fires with a three-tuple of lists of
            L{twisted.names.dns.RRHeader} instances.  The first element of the
            tuple gives answers.  The second element of the tuple gives
            authorities.  The third element of the tuple gives additional
            information.  The L{Deferred} may instead fail with one of the
            exceptions defined in L{twisted.names.error} or with
            C{NotImplementedError}.
        """


def _str_to_python(node):
    """Convert string node to a python object."""
    return node.text or ''


def select_most_recent_belief(df: 'classes.BeliefsDataFrame'
    ) ->'classes.BeliefsDataFrame':
    """Drop all but most recent belief."""
    if 'belief_horizon' in df.index.names:
        return df.groupby(level=['event_start', 'source'], group_keys=False
            ).apply(lambda x: x.xs(min(x.lineage.belief_horizons), level=
            'belief_horizon', drop_level=False))
    elif 'belief_time' in df.index.names:
        return df.groupby(level=['event_start', 'source'], group_keys=False
            ).apply(lambda x: x.xs(max(x.lineage.belief_times), level=
            'belief_time', drop_level=False))
    else:
        raise KeyError(
            'No belief_horizon or belief_time index level found in DataFrame.')


def convert_param(parameter_dict, vals_as_string=False):
    """
    converts dictionary format {argument_name: value, argument_name: value, ...}
    to {'workflow_argument_name': argument_name, 'value': value}
    """
    metadata_parameters = []
    for k, v in parameter_dict.items():
        if not vals_as_string:
            try:
                v = float(v)
                if v % 1 == 0:
                    v = int(v)
            except ValueError:
                v = str(v)
        else:
            v = str(v)
        metadata_parameters.append({'workflow_argument_name': k, 'value': v})
    return metadata_parameters


def carmichael_of_ppower(pp):
    """Carmichael function of the given power of the given prime.
  """
    p, a = pp
    if p == 2 and a > 2:
        return 2 ** (a - 2)
    else:
        return (p - 1) * p ** (a - 1)


def smoothen(df):
    """
    Helper funciton to smooth out vacuum energy fluctuations (DFT problem).
    :param df: A DataFrame with distance and energy values.
    :return: DataFrame with smooth data.
    """
    df_new = df.copy(deep=True)
    df_new = df_new.sort_values(by='distance').reset_index(drop=True)
    for idx, entry in enumerate(df.energy):
        if idx == 0:
            previos_entry = entry
        else:
            dE = entry - previos_entry
            if dE < 0:
                df_new = df_new.drop([idx], axis=0)
            previos_entry = entry
    df_new = df_new.reset_index(drop=True)
    return df_new


def apply_scripts(scripts, config, protocol_class, connection_class):
    """ Application of scripts modules

    It applies the script modules to the specified protocol and connection class instances, in order to build
    the resulting classes with all the additional features that the scripts implement (more information
    about how scripts are implemented and used can be found in the project documentation
    https://piqueserver.readthedocs.io/en/latest/architecture.html#extension-scripts).

    Args:
        scripts: List of scripts modules to apply
        config: It holds the dict of sections and options; this is required by the scripts
         logic
        protocol_class: The protocol class instance to update
        connection_class: The connection class instance to update

    Return:
        (FeatureProtocol, FeatureConnection): The updated protocol and connection class instances
    """
    for script in scripts:
        protocol_class, connection_class = script.apply_script(protocol_class,
            connection_class, config.get_dict())
    return protocol_class, connection_class


def devour_keys(d):
    """Iterator that pops keys from `d` until it's exhaused (i.e. empty)."""
    while d:
        key = next(iter(d.keys()))
        del d[key]
        yield key


def shape_array(data=None, out=None, name=None, **kwargs):
    """Returns a 1D int64 array containing the shape of data.

    Example::

      shape_array([[1,2,3,4], [5,6,7,8]]) = [2,4]

    Defined in src/operator/tensor/elemwise_unary_op_basic.cc:L574

    Parameters
    ----------
    data : NDArray
        Input Array.

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

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


@classmethod
def forget_all(cls):
    """ Forget all cached :class:`.Database` details.
        """
    for _, db in cls._instances.items():
        db._connector.close()
        db._connector = None
    cls._instances.clear()


def _demean(in_file, in_mask=None, usemode=True):
    """
    Subtract the median (since it is robuster than the mean) from a map.

    Parameters
    ----------
    usemode : bool
        Use the mode instead of the median (should be even more robust
        against outliers).

    """
    from os import getcwd
    import numpy as np
    import nibabel as nb
    from nipype.utils.filemanip import fname_presuffix
    nii = nb.load(in_file)
    data = nii.get_fdata(dtype='float32')
    msk = np.ones_like(data, dtype=bool)
    if in_mask is not None:
        msk[nb.load(in_mask).get_fdata(dtype='float32') < 0.0001] = False
    if usemode:
        from scipy.stats import mode
        data[msk] -= mode(data[msk], axis=None)[0][0]
    else:
        data[msk] -= np.median(data[msk], axis=None)
    out_file = fname_presuffix(in_file, suffix='_demean', newpath=getcwd())
    nb.Nifti1Image(data, nii.affine, nii.header).to_filename(out_file)
    return out_file


def get_mv_header(version):
    """Gets a formatted HTTP microversion header.

    :param version: The microversion needed.
    :return: A tuple containing the microversion header with the
             requested version value.
    """
    return {'OpenStack-API-Version': 'volume %s' % version}


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

        :param MemberSuggestionsChangePolicyType val:
        :rtype: EventType
        """
    return cls('member_suggestions_change_policy', val)


@staticmethod
def reverseEngineerMMParameters(y0, v0, e0):
    """
        calculates the parameters KM1...KM5 and Vmax1...Vmax5 from a given steady-state solution
        (y0), steady-state rates (v0) and pre-defined elasticities (e0).
        :param y0: steady-state concentrations (substrates of reactions in v0)
        :param v0: steady-state rates
        :param e0: elasticities
        :return: Vmax, KM
        """
    KM = v0 / (v0 / y0 - e0) - y0
    Vmax = v0 * (KM + y0) / y0
    return Vmax, KM


def send_digest():
    """
        Retrieves digested messages, constructs digest, and sends the
        digest to any digest subscribers.
        """


def pretty_time(time_in_seconds: float) ->str:
    """
    Return the time in a more friendly way.

    Parameters
    ----------
    time_in_seconds : float
        Time in seconds.

    Returns
    -------
    time_string : str
        Pretty time representation as a string.

    Examples
    --------
    >>> pretty_time(30)
    '30.00s'
    >>> pretty_time(76)
    '1m:16s'
    >>> pretty_time(4343)
    '1h:12m:23s'
    """
    seconds = time_in_seconds
    minutes = int(seconds) // 60
    seconds = int(round(seconds % 60))
    hours = minutes // 60
    minutes %= 60
    if hours > 0:
        return '%sh:%02dm:%02ds' % (hours, minutes, seconds)
    if minutes > 0:
        return '%sm:%02ds' % (minutes, seconds)
    return '%.2fs' % time_in_seconds


def check_callback_arg(callback, name):
    """Raise TypeError if callback is not callable

    :param callback: callback to check
    :param name: Name to include in exception text
    :raises TypeError:

    """
    if not callable(callback):
        raise TypeError('{} must be callable, but got {!r}'.format(name,
            callback))


@classmethod
def parse(cls, times, dates, weekdays) ->dict:
    """Return the values in a normalized form."""
    return cls._export3(*cls._parse3(times, dates, weekdays))


def load_json(path):
    """
    Load a file in JSON format.

    :param Path path: Path to the JSON file.

    :return: A dictionary with the parsed content.
    :rtype: dict
    """
    from ujson import loads
    return loads(path.read_text(encoding='utf-8'))


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

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

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


def toPrecision(x):
    """
        convert float precision
    """
    if isinstance(x, float) or isinstance(x, int):
        return float('%0.2f' % x)
    else:
        return None


@classmethod
def create(cls, client, application_id):
    """Creates an AegisBladeApplication instance from an application id.

        Args:
            client (aegisblade.client.AegisBladeClient): The AegisBlade client. The default client is imported
                using 'from aegisblade import aegisblade'.

            application_id (str): The id of the application corresponding to the
                `AegisBladeApplication.id` instance property.
        """
    return cls(client._get_api_consumer(), application_id)


def s2h(ss):
    """convert seconds to a pretty "d hh:mm:ss.s" format"""
    mm, ss = divmod(ss, 60)
    hh, mm = divmod(mm, 60)
    dd, hh = divmod(hh, 24)
    tstr = '%02i:%04.1f' % (mm, ss)
    if hh > 0:
        tstr = '%02i:' % hh + tstr
    if dd > 0:
        tstr = '%id ' % dd + tstr
    return tstr


def generic_find_uq_constraint_name(table, columns, insp):
    """Utility to find a unique constraint name in alembic migrations"""
    for uq in insp.get_unique_constraints(table):
        if columns == set(uq['column_names']):
            return uq['name']


def set_listener(x, y, o):
    """sets the position of the listener:

	- x, y: coordinates of the listener
	- o: orientation in degrees, east is 0 degrees, counterclockwise
	"""
    global _x, _y, _o
    _x, _y, _o = x, y, o


def itself(value):
    """Do-nothing function which returns the input value;
    used as an no-op implementation of converter for types that don't need it,
    equivalent to lambda value: value"""
    return value


def is_client_error(code: int) ->bool:
    """Return true if the code is a client error HTTP response code.

    Args:
        code (int): The HTTP response code.

    Returns:
        bool: True if the code was a client error else false.
    """
    return code >= 400 and code < 500


def repeat_flag(seq, flag):
    """Intersperse flag as a predecessor to each element of seq.

    Example:
    seq = ['foo', 'bar', 'bas']
    flag = '--word'
    print repeat_flag(seq, flag)
      ==>  ['--word', 'foo', '--word', 'bar', '--word', 'bas']
    """
    for item in iter(seq):
        yield flag
        yield item


def unduplicate_field_names(field_names):
    """Append a number to duplicate field names to make them unique. """
    res = []
    for k in field_names:
        if k in res:
            i = 1
            while k + '_' + str(i) in res:
                i += 1
            k += '_' + str(i)
        res.append(k)
    return res


def build(log_cnt):
    """''Build a structure (a list of truples) that ChiMerge algorithm works properly on it
         return a list like ([0:[6,0]],...) 含义：变量值为0是，非违规6人，违规0人 """
    log_dic = {}
    for record in log_cnt:
        if record[0] not in log_dic.keys():
            log_dic[record[0]] = [0, 0]
        if record[1] == 0:
            log_dic[record[0]][0] = record[2]
        elif record[1] == 1:
            log_dic[record[0]][1] = record[2]
        else:
            raise TypeError('Data Exception')
    log_truple = sorted(log_dic.items())
    return log_truple


def interactive(type=None, button_actions=None):
    """Interactive payload creation.
    :keyword type: The name of one of the predefined interactive notifications
    or a custom defined interactive notification. Expects a string.
    :keyword button_actions: A button_actions object that maps button IDs to
    valid action objects. Expects a dictionary.
    """
    payload = {}
    if type is not None:
        payload['type'] = type
        if button_actions is not None:
            if not isinstance(button_actions, dict):
                raise TypeError("'button_actions' must be a dictionary")
            payload['button_actions'] = button_actions
    else:
        raise AttributeError("'interactive' must have a type attribute")
    return payload


def get_nameplate_completions(prefix):
    """
        Return a list of nameplate completions for the given prefix.

        This takes the most-recently-received set of active nameplates from
        the rendezvous server, finds the subset that start with the given
        prefix, and returns the result.  The result strings include the
        prefix and the terminating hyphen, in random order.

        This returns synchronously: it does not wait for a server response.
        If called before getting any response from the server, it will return
        an empty set.  If user input causes completion, it may be a good idea
        to kick off a new ``refresh_nameplates()`` too, in case the user is
        bouncing on the TAB key in the hopes of seeing their expected
        nameplate appear in the list eventually.

        :param str prefix: the nameplate as typed so far

        :return: a set of potential completions
        :rtype: set[str]
        """


def table_has_row(connection, table, rowname):
    """Check whether actual table has row."""
    with connection.cursor() as cursor:
        table_description = connection.introspection.get_table_description(
            cursor, table)
        for row in table_description:
            if row.name == rowname:
                return True
    return False


def revert_mainfile(use_scripts: bool=True):
    """Reload the saved file

    :param use_scripts: Trusted Source, Allow .blend file to execute scripts automatically, default available from system preferences
    :type use_scripts: bool
    """
    pass


@staticmethod
def _key2str(key):
    """From string like <class 'mutagen.id3.TCOM'> get the name TCOM.

        Returns
        -------
        str
            string reptresentation of mutagen.ID3 class tag name
        """
    return str(key).rsplit('.', 1)[1][:-2]


def enc(x, codec='ascii'):
    """Encodes a string for SGML/XML/HTML"""
    if isinstance(x, bytes):
        return ''
    x = x.replace('&', '&').replace('>', '>').replace('<', '<'
        ).replace('"', '"')
    if codec:
        x = x.encode(codec, 'xmlcharrefreplace')
    return x


def Identity():
    """
    Packet containing peer identity file.
    """
    return 'Identity'


def parse_smt_command(command):
    """Breaks the given SMT command "(CMD ARG ARG ARG)" into tuple (CMD, [ARG]),
    where ARG again can be a (non-parsed) command"""
    command = command.strip()
    if command[0] != '(':
        return command, []
    command = command[1:-1].split(maxsplit=1)
    if len(command) == 1:
        return command[0], []
    command, arguments = command
    args = ['']
    paren = 0
    while len(arguments) > 0:
        c = arguments[0]
        arguments = arguments[1:]
        if c == '(':
            paren += 1
        elif c == ')':
            paren -= 1
            if paren < 0:
                raise RuntimeError('Unmatched closing brace in SMT output')
        elif c == ' ':
            if paren == 0:
                arguments = arguments.strip()
                args.append('')
                continue
        args[-1] += c
    if not args[-1]:
        args = args[:-1]
    return command, args


def from_iso_permissive(datestring, use_dateutil=True):
    """Parse an ISO8601-formatted datetime and return a datetime object.

        Inspired by the marshmallow.utils.from_iso function, but also accepts
        datestrings that don't contain the time.
        """
    dateutil_available = False
    try:
        from dateutil import parser
        dateutil_available = True
    except ImportError:
        dateutil_available = False
        import datetime
    if dateutil_available and use_dateutil:
        return parser.parse(datestring)
    else:
        return datetime.datetime.strptime(datestring[:19], '%Y-%m-%dT%H:%M:%S')


@classmethod
def add_subscription(cls, options=None):
    """Add subscription"""
    cls.command_sub = 'add-subscription'
    return cls.execute(cls._construct_command(options))


@staticmethod
def fixedlen():
    """Return the constant length of all filehandle bytearrays"""
    return 24


def liftover_using_gnomad_map(ht, data_type):
    """
    Liftover a gnomAD table using already-established liftover file. Warning: shuffles!

    :param ht: Input Hail table
    :param data_type: one of "exomes" or "genomes" which to map across
    :return: Lifted over table
    """
    from gnomad.resources.grch37.gnomad import liftover
    lift_ht = liftover(data_type).ht()
    ht = ht.key_by(original_locus=ht.locus, original_alleles=ht.alleles).drop(
        'locus', 'alleles')
    return lift_ht.annotate(**ht[lift_ht.original_locus, lift_ht.
        original_alleles]).key_by('locus', 'alleles')


def example_function(param='param'):
    """
    Prints hello world and returns param.
    Good link on how to write these napolean docs:
    https://sphinxcontrib-napoleon.readthedocs.io/en/latest/

    Parameters
    ----------
    param
        A string to be prtined. Very creative.

    Returns
    -------
    string
        Whatever param is set to.
    """
    print('Hello world')
    return param


@classmethod
def setup(cls, **kwargs):
    """Set up the storage system for memcached-based sessions.

        This should only be called once per process; this will be done
        automatically when using sessions.init (as the built-in Tool does).
        """
    for k, v in kwargs.items():
        setattr(cls, k, v)
    import memcache
    cls.cache = memcache.Client(cls.servers)


def _unlink(subs, shared):
    """Configure the `doorstop unlink` subparser."""
    info = 'remove a link between two items'
    sub = subs.add_parser('unlink', description=info.capitalize() + '.',
        help=info, **shared)
    sub.add_argument('child', help='child item UID to unlink from parent')
    sub.add_argument('parent', help='parent item UID child is linked to')


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 _readlines(fname, fpointer1=open, fpointer2=open):
    """Read all lines from file."""
    try:
        with fpointer1(fname, 'r') as fobj:
            return fobj.readlines()
    except UnicodeDecodeError:
        with fpointer2(fname, 'r', encoding='utf-8') as fobj:
            return fobj.readlines()
    except:
        raise


def unique_list_and_keep_original_order(target_list, key=None):
    """
    从列表中删除重复的元素, 同时保留其原始顺序
    :param target_list: 待处理的list
    :param key: 是一个函数，它接受一个参数并返回一个 key 来测试唯一性
    :return:
    """
    key = key or (lambda x: x)
    seen = set()
    unique_list = []
    for value in target_list:
        unique_value = key(value)
        if unique_value in seen:
            continue
        seen.add(unique_value)
        unique_list.append(value)
    return unique_list


def setdefault(key, default=None):
    """D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D"""


def run_all_import_steps(portal_setup):
    """This example invokes an extension profile which in turn performs
    a migration.
    """
    portal_setup.runAllImportStepsFromProfile(
        'profile-collective.idashboard:default', purge_old=False)


def impersonate_other_page(page, other_page):
    """Function to change the page metadata so the user gets to see the
    non-personalized path and page.

    :param page: The page to be impersonated
    :type page: wagtail_personalisation.models.PersonalisablePage
    :param other_page: The page it should impersonate
    :type other_page: wagtail_personalisation.models.PersonalisablePage

    """
    page.path = other_page.path
    page.depth = other_page.depth
    page.url_path = other_page.url_path
    page.title = other_page.title


@classmethod
def from_queryset(cls, other, **kwargs):
    """根据其他QuerySet对象的数据生成实例"""
    query = other.query.clone()
    if other._sticky_filter:
        query.filter_is_sticky = True
    clone = cls(model=other.model, query=query, using=other._db, hints=
        other._hints)
    clone._for_write = other._for_write
    clone._prefetch_related_lookups = other._prefetch_related_lookups[:]
    clone._known_related_objects = other._known_related_objects
    clone._iterable_class = other._iterable_class
    clone._fields = other._fields
    clone.__dict__.update(kwargs)
    return clone


def rotate(deg, x, y):
    """
    Generate an SVG transform statement representing rotation around a given
    point.
    """
    return 'rotate(%i %i %i)' % (deg, x, y)


def p_method_modifiers_empty(p):
    """method_modifiers : empty"""
    p[0] = []


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 hour_angle_localtime(localtime):
    """
    returns the hour angle from time in Python datetime format
    no corrections for equation of time, longitude, timezone

    this function is used for the generation of solar path plots,
    where the time input is already in naive format and no eot
    correction is necessary

    input:
    - localtime, local (solar) time in Python datetime format

    output:
    - hour angle in decimal degrees [-180..+180], float

    """
    hour = localtime.hour
    minute = localtime.minute
    hra = round((hour - 12) * 15 + minute / 4, 3)
    return hra


def HTML4():
    """Return the object in the format used in the HTML4.0
        specification, one of the standard forms in ISO8601.  See
        http://www.w3.org/TR/NOTE-datetime

        Dates are output as: YYYY-MM-DDTHH:MM:SSZ
           T, Z are literal characters.
           The time is in UTC.
        """


def toDegree(rawPosition):
    """位置情報の単位を[360/65536 * 度]から[度]に変換する
    """
    return round(rawPosition * 360.0 / float(65536), 2)


@classmethod
def register_file_class(cls, kls):
    """
        Convenience method for setting current class file_class property.

        :param kls: class to set
        :type kls: type
        :returns: given class (enabling using this as decorator)
        :rtype: type
        """
    cls.file_class = kls
    return kls


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


@staticmethod
def format_sizeof(num, suffix='', divisor=1000):
    """
        Formats a number (greater than unity) with SI Order of Magnitude
        prefixes.

        Parameters
        ----------
        num  : float
            Number ( >= 1) to format.
        suffix  : str, optional
            Post-postfix [default: ''].
        divisor  : float, optional
            Divisor between prefixes [default: 1000].

        Returns
        -------
        out  : str
            Number with Order of Magnitude SI unit postfix.
        """
    for unit in ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z']:
        if abs(num) < 999.5:
            if abs(num) < 99.95:
                if abs(num) < 9.995:
                    return '{0:1.2f}'.format(num) + unit + suffix
                return '{0:2.1f}'.format(num) + unit + suffix
            return '{0:3.0f}'.format(num) + unit + suffix
        num /= divisor
    return '{0:3.1f}Y'.format(num) + suffix


def get_windows_terminal_size():
    """Get the terminal size of a Windows OS terminal."""
    from ctypes import windll, create_string_buffer
    handle = windll.kernel32.GetStdHandle(-12)
    try:
        csbi = create_string_buffer(22)
        res = windll.kernel32.GetConsoleScreenBufferInfo(handle, csbi)
    except (IOError, OSError):
        return None
    if res:
        import struct
        (bufx, bufy, curx, cury, wattr, left, top, right, bottom, maxx, maxy
            ) = struct.unpack('hhhhHhhhhhh', csbi.raw)
        sizex = right - left + 1
        sizey = bottom - top + 1
        return sizex, sizey
    else:
        return None


def pairwise(iterable, reverse=False):
    """Iterate over current and next items in iterable, optionally in
    reverse order.

    >>> tuple(pairwise([]))
    ()
    >>> tuple(pairwise([], reverse=True))
    ()
    >>> tuple(pairwise([0]))
    ((0, 0),)
    >>> tuple(pairwise([0], reverse=True))
    ((0, 0),)
    >>> tuple(pairwise([0, 1]))
    ((0, 1), (1, 0))
    >>> tuple(pairwise([0, 1], reverse=True))
    ((1, 0), (0, 1))
    >>> tuple(pairwise([0, 1, 2]))
    ((0, 1), (1, 2), (2, 0))
    >>> tuple(pairwise([0, 1, 2], reverse=True))
    ((2, 1), (1, 0), (0, 2))
    >>> tuple(pairwise(['a', 'b', 'c', 'd']))
    (('a', 'b'), ('b', 'c'), ('c', 'd'), ('d', 'a'))
    >>> tuple(pairwise(['a', 'b', 'c', 'd'], reverse=True))
    (('d', 'c'), ('c', 'b'), ('b', 'a'), ('a', 'd'))
    """
    if not iterable:
        return
    if reverse:
        it = reversed(iterable)
    else:
        it = iter(iterable)
    first = next(it, None)
    a = first
    for b in it:
        yield a, b
        a = b
    yield a, first


def registerMemberData(m, id):
    """ Add the given member data to the _members btree.

        o 'm' is an object whose attributes are the memberdata for the member.

        o 'id' is the userid of the member.

        o Add the record late as possible to avoid side effect transactions
          and to reduce the necessary number of entries.

        o ???: these argument names are silly;  can we use more sensible
          ones (i.e., does anyone actually depend on them)?

        o Permission:  Private (Python only)
        """


def get_grade_explanation(grade, normal_grades=False):
    """Converts grade explanation code to logical english

    Example HH => To be continued """
    explanation = {'HH': 'To be continued', 'IP': 'In progress', 'J':
        'Absent', 'K': 'Incomplete', 'KE': 'Further extension granted',
        'K*': 'Further extension granted', 'KF': 'Incomplete - Failed',
        'KK': 'Completion requirement waived', 'L': 'Deferred', 'LE':
        'Deferred - extension granted', 'L*':
        'Deferred - extension granted', 'NA': 'Grade not yet available',
        '&&': 'Grade not yet available', 'NE': 'No evaluation', 'NR':
        'No grade reported by the instructor (recorded by the Registrar)',
        'P': 'Pass', 'Q': 'Course continues in following term', 'R':
        'Course credit', 'W': 'Permitted to withdraw', 'WF':
        'Withdraw - failing', 'WL':
        'Faculty permission to withdraw from a deferred examination', 'W--':
        'No grade: student withdrew from the University', '--':
        'No grade: student withdrew from the University', 'CO':
        'Complete [Academic Integrity Tutorial]', 'IC':
        'Incomplete [Academic Integrity Tutorial]'}
    normal_explanation = {'A': '85 - 100', 'A-': '80 - 84', 'B+': '75 - 79',
        'B': '70 - 74', 'B-': '65 - 69', 'C+': '60 - 64', 'C': '55 - 59',
        'D': '50 - 54', 'F': '0 - 49', 'S': 'Satisfactory', 'U':
        'Unsatisfactory'}
    if normal_grades:
        explanation.update(normal_explanation)
    if grade in explanation:
        return explanation[grade]
    else:
        return ''


def start_responding(server_name, challenge, response):
    """
        Start responding for a particular challenge.

        :param str server_name: The server name for which the challenge is
            being completed.
        :param challenge: The `acme.challenges` challenge object; the exact
            type of this object depends on the challenge type.
        :param response: The `acme.challenges` response object; the exact type
            of this object depends on the challenge type.

        :rtype: ``Deferred``
        :return: A deferred firing when the challenge is ready to be verified.
        """


def get_status_new(code):
    """Get the torrent status using new status codes"""
    mapping = {(0): 'stopped', (1): 'check pending', (2): 'checking', (3):
        'download pending', (4): 'downloading', (5): 'seed pending', (6):
        'seeding'}
    return mapping[code]


@staticmethod
def get_tags(instance):
    """
        Return a dictionary of tags
        """
    if 'tags' in instance:
        return dict.fromkeys(instance['tags'])
    return {}


def find_in_enum_members(item, enum_members: list):
    """Matches a string in the provided list of member strings.
	The item must be not fully matched.
	Rules:
	- If the member string starts with underscore, it is cut out before the matching continues.
	- The item is matched if a member string starts with the item (item is a prefix of the member)."""
    found = None
    for x in enum_members:
        if x.startswith(item):
            found = x
            break
        if x.startswith('_'):
            if x.strip('_').startswith(item):
                found = x
                break
    return found


def df_string(df, percentage_columns=(), format_map=None, **kwargs):
    """Return a nicely formatted string for the given dataframe.

    Arguments
    ---------
    df : pandas.DataFrame
        A dataframe object.
    percentage_columns : iterable
        A list of cloumn names to be displayed with a percentage sign.

    Returns
    -------
    str
        A nicely formatted string for the given dataframe.

    Example
    -------
    >>> import pandas as pd
    >>> df = pd.DataFrame([[8,'a'],[5,'b']],[1,2],['num', 'char'])
    >>> print(df_string(df))
       num char
    1    8    a
    2    5    b
    """
    formatters_map = {}
    for col, dtype in df.dtypes.iteritems():
        if col in percentage_columns:
            formatters_map[col] = '{:,.2f} %'.format
        elif dtype == 'float64':
            formatters_map[col] = '{:,.2f}'.format
    if format_map:
        for key in format_map:
            formatters_map[key] = format_map[key]
    return df.to_string(formatters=formatters_map, **kwargs)


def _switch_package_license_ids(old_ids, old_license_titles, map):
    """Returns a dict of new license ids, keyed by package id."""
    new_ids = {}
    for package_id, old_license_id in old_ids.items():
        if old_license_id != None:
            old_license_title = old_license_titles[old_license_id]
            new_license_id = map[old_license_title]
            new_ids[package_id] = new_license_id
            print('Switched license_id %s to %s' % (old_license_id,
                new_license_id))
    return new_ids


def bookmark_toggle():
    """Toggle bookmarks display

    """
    pass


def test_setup(test):
    """Called before every test is run.

    Add an implementation of this to your own lifecycle module.

    :param unittest_jasmine.unittest.Test test: The test that is about to
        start.
    """
    pass


def expected(typ, val=None):
    """
    Return an indication of expected input and the position where it was
    expected and not encountered.
    """
    return [('expected', typ, val)]


def angle(val):
    """Convert an integer value to a floating point angle."""
    return val * 360.0 / 2 ** 16


def overlap_coefficient_join(ltable, rtable, l_key_attr, r_key_attr,
    l_join_attr, r_join_attr, tokenizer, threshold, comp_op='>=',
    allow_empty=True, allow_missing=False, l_out_attrs=None, r_out_attrs=
    None, l_out_prefix='l_', r_out_prefix='r_', out_sim_score=True, n_jobs=
    1, show_progress=True):
    """Join two tables using overlap coefficient.

    For two sets X and Y, the overlap coefficient between them is given by:

        :math:`overlap\\_coefficient(X, Y) = \\frac{|X \\cap Y|}{\\min(|X|, |Y|)}`

    In the case where one of X and Y is an empty set and the other is a
    non-empty set, we define their overlap coefficient to be 0. In the case
    where both X and Y are empty sets, we define their overlap coefficient to
    be 1.

    Finds tuple pairs from left table and right table such that the overlap
    coefficient between the join attributes satisfies the condition on input
    threshold. For example, if the comparison operator is '>=', finds tuple
    pairs whose overlap coefficient between the strings that are the values of
    the join attributes is greater than or equal to the input threshold, as
    specified in "threshold".

    Args:
        ltable (DataFrame): left input table.

        rtable (DataFrame): right input table.

        l_key_attr (string): key attribute in left table.

        r_key_attr (string): key attribute in right table.

        l_join_attr (string): join attribute in left table.

        r_join_attr (string): join attribute in right table.

        tokenizer (Tokenizer): tokenizer to be used to tokenize join
            attributes.

        threshold (float): overlap coefficient threshold to be satisfied.

        comp_op (string): comparison operator. Supported values are '>=', '>'
            and '=' (defaults to '>=').

        allow_empty (boolean): flag to indicate whether tuple pairs with empty
            set of tokens in both the join attributes should be included in the
            output (defaults to True).

        allow_missing (boolean): flag to indicate whether tuple pairs with
            missing value in at least one of the join attributes should be
            included in the output (defaults to False). If this flag is set to
            True, a tuple in ltable with missing value in the join attribute
            will be matched with every tuple in rtable and vice versa.

        l_out_attrs (list): list of attribute names from the left table to be
            included in the output table (defaults to None).

        r_out_attrs (list): list of attribute names from the right table to be
            included in the output table (defaults to None).

        l_out_prefix (string): prefix to be used for the attribute names coming
            from the left table, in the output table (defaults to 'l\\_').

        r_out_prefix (string): prefix to be used for the attribute names coming
            from the right table, in the output table (defaults to 'r\\_').

        out_sim_score (boolean): flag to indicate whether similarity score
            should be included in the output table (defaults to True). Setting
            this flag to True will add a column named '_sim_score' in the
            output table. This column will contain the similarity scores for the
            tuple pairs in the output.

        n_jobs (int): number of parallel jobs to use for the computation
            (defaults to 1). If -1 is given, all CPUs are used. If 1 is given,
            no parallel computing code is used at all, which is useful for
            debugging. For n_jobs below -1, (n_cpus + 1 + n_jobs) are used
            (where n_cpus is the total number of CPUs in the machine). Thus for
            n_jobs = -2, all CPUs but one are used. If (n_cpus + 1 + n_jobs)
            becomes less than 1, then no parallel computing code will be used
            (i.e., equivalent to the default).

        show_progress (boolean): flag to indicate whether task progress should
            be displayed to the user (defaults to True).

    Returns:
        An output table containing tuple pairs that satisfy the join
        condition (DataFrame).
    """
    from py_stringsimjoin import __use_cython__
    if __use_cython__:
        from py_stringsimjoin.join.overlap_coefficient_join_cy import overlap_coefficient_join_cy
        return overlap_coefficient_join_cy(ltable, rtable, l_key_attr,
            r_key_attr, l_join_attr, r_join_attr, tokenizer, threshold,
            comp_op, allow_empty, allow_missing, l_out_attrs, r_out_attrs,
            l_out_prefix, r_out_prefix, out_sim_score, n_jobs, show_progress)
    else:
        from py_stringsimjoin.join.overlap_coefficient_join_py import overlap_coefficient_join_py
        return overlap_coefficient_join_py(ltable, rtable, l_key_attr,
            r_key_attr, l_join_attr, r_join_attr, tokenizer, threshold,
            comp_op, allow_empty, allow_missing, l_out_attrs, r_out_attrs,
            l_out_prefix, r_out_prefix, out_sim_score, n_jobs, show_progress)


def read_dinogws():
    """ read data from Dinoloket csv file with groundwater measurement
    data """
    pass


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


def units_to_msec(units, resolution):
    """Convert BLE specific units to milliseconds."""
    time_ms = units * float(resolution) / 1000
    return time_ms


def parse_cluster_id(line):
    """
    If the line is a cluster ID, return the cluster number

    Example:
    >Cluster 597
    return 597
    """
    line = line.strip().split()
    return line[1]


def GetMaxLayer(docks, dock_direction):
    """
    This is an internal function which returns
    the highest layer inside the specified dock.

    :param `docks`: a list of :class:`AuiDockInfo`;
    :param `dock_direction`: the :class:`AuiDockInfo` docking direction to analyze.
    """
    max_layer = 0
    for dock in docks:
        if (dock.dock_direction == dock_direction and dock.dock_layer >
            max_layer and not dock.fixed):
            max_layer = dock.dock_layer
    return max_layer


def merge(*dicts):
    """Given any number of dicts, shallow copy and merge into a new dict,
    precedence goes to key value pairs in latter dicts."""
    result = {}
    for d in dicts:
        result.update(d)
    return result


@staticmethod
def query_add(s, value):
    """check if value in s(et) and add if not

        return True if added, False if already in.

        >>> x = set()
        >>> if query_add(x, 'a'):
        ...     print 'hello'
        hello
        >>> if query_add(x, 'a'):
        ...     print 'hello'
        >>>

        """
    if value not in s:
        s.add(value)
        return True
    return False


@classmethod
def prolog_query(cls, query):
    """Run prolog query without specifying trial"""
    cls.init_cli()
    id_to_instance = {}
    cache = set()
    no_cache = set()
    for inst in cls.get_instances():
        id_to_instance[inst.trial.id] = inst
        (cache if inst.use_cache else no_cache).add(inst.trial.id)
    retract_ids = no_cache - cache
    for tid in retract_ids:
        id_to_instance[tid].retract()
    return cls.prolog_cli.query(query)


@classmethod
def __calculate_max_move(cls, point_1, point_2, lidars):
    """
        Considering all provided lidar positions it calculates maximum
        angular displacement they need to perform from one to another point.

        Parameters
        ----------
        point_1 : ndarray
            nD array containing the first trajectory point coordinates
            in the Cartesian coordinate system.
        point_2 : ndarray
            nD array containing the second trajectory point coordinates
            in the Cartesian coordinate system.
        lidars : ndarray
            nD array containing lidars positions in the Cartesian
            coordinate system.

        Returns
        -------
        Maximum angular displacement lidars need to perform.

        """
    azimuth_max = max(map(lambda x: abs(cls.__rollover(point_1, point_2, x)
        [0]), lidars))
    elevation_max = max(map(lambda x: abs(cls.__rollover(point_1, point_2,
        x)[1]), lidars))
    return max(azimuth_max, elevation_max)


def hms_string(sec_elapsed):
    """Convert seconds to human readable h:min:seconds

    Parameters
    ----------
    sec_elapsed : float
        Elapsed seconds

    References
    ----------
    Copied verbatim from http://arcpy.wordpress.com/2012/04/20/146/

    """
    h = int(sec_elapsed / (60 * 60))
    m = int(sec_elapsed % (60 * 60) / 60)
    s = sec_elapsed % 60.0
    return '{}:{:>02}:{:>05.2f}'.format(h, m, s)


def set_text(text):
    """Set post text content
        """


@classmethod
def get_configuration_for_impersonation(cls, uri, impersonate_user, username):
    """
        Return a configuration dictionary that can be merged with other configs
        that can set the correct properties for impersonating users
        :param uri: URI string
        :param impersonate_user: Bool indicating if impersonation is enabled
        :param username: Effective username
        :return: Dictionary with configs required for impersonation
        """
    return {}


def p_comp_op_lte(p):
    """comp_op : expr LT EQUAL expr"""
    p[0] = 'lte', p[1], p[4]


def name_history_model(name):
    """
    Returns the name of the history model class from a name
    """
    return '%sHistory' % name


def prepare_bearer_headers(token, headers=None):
    """Add a `Bearer Token`_ to the request URI.
    Recommended method of passing bearer tokens.

    Authorization: Bearer h480djs93hd8

    .. _`Bearer Token`: http://tools.ietf.org/html/draft-ietf-oauth-v2-bearer-18
    """
    headers = headers or {}
    headers[u'Authorization'] = u'Bearer %s' % token
    return headers


def getPageHeight():
    """Returns page_height or the default value from the registry.
        """
    pass


@classmethod
def from_httplib(cls, message):
    """Read headers from a Python 2 httplib message object."""
    headers = []
    for line in message.headers:
        if line.startswith((' ', '\t')):
            key, value = headers[-1]
            headers[-1] = key, value + '\r\n' + line.rstrip()
            continue
        key, value = line.split(':', 1)
        headers.append((key, value.strip()))
    return cls(headers)


def tanh(data=None, name=None, attr=None, out=None, **kwargs):
    """Returns the hyperbolic tangent of the input array, computed element-wise.

    .. math::
       tanh(x) = sinh(x) / cosh(x)

    The storage type of ``tanh`` output depends upon the input storage type:

       - tanh(default) = default
       - tanh(row_sparse) = row_sparse
       - tanh(csr) = csr

    Defined in src/operator/tensor/elemwise_unary_op_trig.cc:L393

    Parameters
    ----------
    data : Symbol
        The input array.

    name : string, optional.
        Name of the resulting symbol.

    Returns
    -------
    Symbol
        The result symbol.
    """
    return 0,


def format_duration(secs):
    """
    Format a duration in seconds as minutes and seconds.
    """
    secs = int(secs)
    if abs(secs) > 60:
        mins = abs(secs) / 60
        secs = abs(secs) - mins * 60
        return '%s%im %02is' % ('-' if secs < 0 else '', mins, secs)
    return '%is' % secs