def dxl_angle_to_degrees(dxl_angle):
    """Normalize the given angle.

    PxAX-12 uses the position angle (-150.0°, +150.0°) range instead of the
    (0°, +300.0°) range defined in the Dynamixel official documentation because
    the former is easier to use (especially to make remarkable angles like
    right angles or 45° and 135° angles).

    :param int dxl_angle: an angle defined according to the Dynamixel internal
        notation, i.e. in the range (0, 1023) where:

        - 0 is a 150° clockwise angle;
        - 1023 is a 150° counter clockwise angle.

    :return: an angle defined in degrees in the range (-150.0°, +150.0°) where:

        - -150.0 is a 150° clockwise angle;
        - +150.0 is a 150° counter clockwise angle.

    :rtype: float.
    """
    angle_degrees = round(dxl_angle / 1023.0 * 300.0 - 150.0, 1)
    return angle_degrees


@staticmethod
def prepare_required_raw_item(item):
    """Prepare required field item.

        Convert replaces any special "dimensions#", "meta#" or "value_meta" occurrences into
        spark rdd syntax to fetch field value.

        """
    if item.startswith('dimensions#'):
        field_name = item.replace('dimensions#', '')
        return "metric.dimensions['%s']" % field_name
    elif item.startswith('meta#'):
        field_name = item.replace('meta#', '')
        return "meta['%s']" % field_name
    elif item.startswith('value_meta#'):
        field_name = item.replace('value_meta#', '')
        return "metric.value_meta['%s']" % field_name
    else:
        return item


@staticmethod
def get_quiz(course, activity):
    """Returns the canvasapi.quiz.Quiz object associated
        with this repository.
        """
    return course.get_quiz(activity.quiz_id)


def find_common_fixes(s1, s2):
    """Find common (prefix, suffix) of two strings.

    >>> find_common_fixes('abc', 'def')
    ('', '')

    >>> find_common_fixes('abcelephantdef', 'abccowdef')
    ('abc', 'def')

    >>> find_common_fixes('abcelephantdef', 'abccow')
    ('abc', '')

    >>> find_common_fixes('elephantdef', 'abccowdef')
    ('', 'def')

    """
    prefix = []
    suffix = []
    i = 0
    common_len = min(len(s1), len(s2))
    while i < common_len:
        if s1[i] != s2[i]:
            break
        prefix.append(s1[i])
        i += 1
    i = 1
    while i < common_len + 1:
        if s1[-i] != s2[-i]:
            break
        suffix.append(s1[-i])
        i += 1
    suffix.reverse()
    prefix = ''.join(prefix)
    suffix = ''.join(suffix)
    return prefix, suffix


def sqlize(string):
    """SQL-izes a string to ensure the characters are all legal

    Args:
        string (str): The string to be processed

    Returns:
        the processed SQL-friendly string
    """
    return string.upper().replace(' ', '_').replace('-', '_').replace(':', '_')


def select_verbosity():
    """
    Set verbosity/silent options from interactive mode
    Returns a boolean tuple-2 with the form:
        (silent, verbose)
    """
    print('Select one of the three modes:')
    print('\tN - Normal mode (by default). Prints the most relevant messages')
    print('\tV - Verbose mode. Prints info often about the running processes')
    print('\tS - Silent mode. Almost never prints any message')
    choice = input('> ')
    if choice in ['s', 'S']:
        return True, False
    elif choice in ['v', 'V']:
        return False, True
    else:
        return False, False


def min_max_normalize(F, floor=0.001):
    """Normalizes features such that each vector is between floor to 1."""
    F += -F.min() + floor
    F = F / F.max(axis=0)
    return F


@staticmethod
def emphasis(text: str) ->str:
    """
        Emphasizes a given text
        ex. markd.add_text(markd.emphasis('This text block will be emphasized'))
        :param text: The text to be emphazised

        :return: An emphazised string
        """
    return '**{}**'.format(text)


def table_from_primary_key(pkname):
    """Given the name of a primary key, return the related table.

    :param pkname: the name of a primary key
    :rtype: a SQLAlchemy table
    """
    from . import Base
    for t in Base.metadata.sorted_tables:
        if len(t.primary_key.columns) == 1 and pkname in t.primary_key.columns:
            return t
    raise Exception('Unknown PK: %s' % pkname)


def publish(topic=None, qos=None, payload=None):
    """
    Publishes state information.
    For more information, see HTTP Protocol in the AWS IoT Developer Guide .
    See also: AWS API Documentation

    :example: response = client.publish(
        topic='string',
        qos=123,
        payload=b'bytes'|file
    )

    :type topic: string
    :param topic: [REQUIRED]
            The name of the MQTT topic.

    :type qos: integer
    :param qos: The Quality of Service (QoS) level.

    :type payload: bytes or seekable file-like object
    :param payload: The state information, in JSON format.

    """
    pass


def is_total_homomorphism(elements, mapping):
    """Return True if mapping is total."""
    return set(elements) == set(mapping.keys())


@staticmethod
def _get_next_link(data):
    """
        Returns the link for the next page
        :param dict data: The response data as provided by self.__request
        :return bool:
        """
    return data.get('payload', {}).get('links', {}).get('next', None)


def power_piv(current, voltage):
    """Usage: power_piv(current, voltage)"""
    return current * voltage


@classmethod
def from_network_info(cls, network_info):
    """Returns a list of IpPayload object based on the passed
        network_info.
        """
    ips = []
    if network_info is not None:
        for vif in network_info:
            for ip in vif.fixed_ips():
                ips.append(cls(label=vif['network']['label'], mac=vif[
                    'address'], meta=vif['meta'], port_uuid=vif['id'],
                    version=ip['version'], address=ip['address'],
                    device_name=vif['devname']))
    return ips


def render_border(xmin: int=0, xmax: int=0, ymin: int=0, ymax: int=0,
    camera_only: bool=False):
    """Set the boundaries of the border render and enable border render

    :param xmin: X Min
    :type xmin: int
    :param xmax: X Max
    :type xmax: int
    :param ymin: Y Min
    :type ymin: int
    :param ymax: Y Max
    :type ymax: int
    :param camera_only: Camera Only, Set render border for camera view and final render only
    :type camera_only: bool
    """
    pass


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


def _represent_numpy_complex(dumper, npcomplex: 'numpy.complex_') ->str:
    """
    Convert the passed Numpy complex number into a YAML-formatted string.

    Specifically, this function returns a stringified YAML complex number
    equivalent to the passed complex number.

    Parameters
    ----------
    dumper: yaml.Dumper
        Object converting arbitrary Python objects to YAML-formatted strings.
    npcomplex: numpy.ndarray
        Numpy complex number to be converted into a YAML-formatted string.

    Returns
    ----------
    str
        YAML-formatted string representing this Numpy complex number.
    """
    return dumper.represent_complex(complex(npcomplex))


def __init_subclass__(cls, **kwargs):
    """Automatically register the class"""
    super().__init_subclass__(**kwargs)
    if not hasattr(cls, '_registry'):
        cls._registry = {}
    name = cls.__module__.split('.')[-1]
    cls._registry[name] = cls


def __init__(A):
    """UnstructuredRemittanceInformation - a model defined in Swagger"""
    A.discriminator = None


def exclude_nodes_from_states(traj_states, nodes_exluded=None):
    """Exclude nodes from states
    :param traj_states: list of states (each state is a liste of nodes)
    :param nodes_exluded: list/set of nodes to remove
    """
    if not nodes_exluded or len(nodes_exluded) <= 0:
        return traj_states
    traj_states_ret = []
    for one_traj_states in traj_states:
        new_traj_states = list(set(one_traj_states) - set(nodes_exluded))
        if len(new_traj_states) <= 0:
            new_traj_states = ['<nil>']
        traj_states_ret.append(new_traj_states)
    return traj_states_ret


@staticmethod
def _to_list(data):
    """Converts certain data types (str, unicode) into list.

        Args:
          data: data to convert

        Returns:
          list with converted data
        """
    types = [str]
    for data_type in types:
        if isinstance(data, data_type):
            return [data]
    return data


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 theta_Ca_K_PK74(T, P):
    """c-c': calcium potassium [PK74]."""
    theta = -0.04
    valid = T == 298.15
    return theta, valid


def hasLoginPasswordExtractor():
    """Check if a login & password extraction plugin is active.

        Check if there is a plugin with an enabled
        ILoginPasswordExtractionPlugin interface. This can be used to
        conditionally show username & password logins.
        """


def apply_error_style(w, error):
    """Applies error styling to the supplied widget based on the error code"""
    if error:
        color = '#FFCC00' if error == 'eval' else '#cc0000'
        w.layout.border = '5px solid %s' % color
    else:
        w.layout.border = '0px'


def get_data_folder():
    """
    Path to the folder containing example files.
    """
    import os
    p = __import__('pandas_plink').__path__[0]
    return os.path.join(p, 'test', 'data_files')


def serialize_milestone_with_course(course_milestone):
    """
    CourseMilestone serialization (composite object)
    """
    return {'id': course_milestone.milestone.id, 'name': course_milestone.
        milestone.name, 'display_name': course_milestone.milestone.
        display_name, 'namespace': course_milestone.milestone.namespace,
        'description': course_milestone.milestone.description, 'course_id':
        course_milestone.course_id}


def get_only_present_at_pos(fragFreqCounters, *args, **kwargs):
    """
    Find patterns in fragFreqCounters that, when present, are always
    at the same position.

    ``fragFreqCounters`` is a dictionary (usually keyed on ``fragments``)
    of whose values are dictionaries mapping positions to frequencies.

    For example::

        {
            ('a', 1, 1, 'fixed'): {1: 7, -1: 7, 3: 4},
            ('b', 1, 1, 'fixed'): {2: 6},
        }

    This indicates that the
      - pattern ``('a', 1, 1, 'fixed')`` has frequency 7 at positions 1 and -1,
        and frequency 4 at position 3;
      - pattern ``('b', 1, 1, 'fixed')`` has frequency 6 at position 2 (only)

    So this would return::

        [
            (('b', 1, 1, 'fixed'), 2)
        ]

    (sorted on ``pos``; each ``pos`` really should occur at most once.)
    """
    out = []
    print(fragFreqCounters)
    for frag, fragFreqs in fragFreqCounters.items():
        if len(fragFreqs) == 1:
            pos = fragFreqs.keys()[0]
            out.append((frag, pos))
    out.sort(key=lambda x: x[1])
    return out


def MFR(V):
    """
    Approximate the mode field radius for a step-index single mode fiber.

    The approximation is fairly accurate for V>1. In the multimode range
    (V > 2.405), it applies to the fundamental mode.

    D. Marcuse, "Loss analysis of single-mode fiber splices", Bell Syst.
    Tech. J., 56, 703 (1977)

    Args:
        V:      V-parameter of the fiber                            [--]
    Returns:
        approximate mode field radius normalized by the core radius [--]
    """
    return 0.65 + 1.619 * V ** -1.5 + 2.879 * V ** -6


def _safe_single_attr(x):
    """Handle cleaning of attributes after extraction:
      - '.'s to indicate None
      - tuples where we expect a single value
    """
    if x is None or x is '.':
        return None
    elif isinstance(x, (list, tuple)):
        return x[0]
    else:
        return x


def short_repr(item, max_length=15):
    """Short representation of item if it is too long"""
    item = repr(item)
    if len(item) > max_length:
        item = '{}...{}'.format(item[:max_length - 3], item[-1])
    return item


def get_ccp4_commands(lines_of_input):
    """Get the commands which were sent to a CCP4 program."""
    logicals = {}
    for line in lines_of_input:
        if 'Logical Name:' in line:
            token = line.split(':')[1].split()[0]
            value = line.split(':')[-1].strip()
            logicals[token] = value
    script = []
    for line in lines_of_input:
        if 'Data line---' in line:
            script.append(line.replace('Data line---', '').strip())
    return script, logicals


def profile_emails(profile, get_unverified=False):
    """Return a dict of user profile's emails,
    divided into primary, rest and optionally unverified.
    Also pass their total count.
    """
    emails = profile.emails.filter(verified=True).order_by('-primary')
    result = {'primary': emails[0], 'secondary': emails[1:]}
    count = len(emails)
    if get_unverified:
        result['unverified'] = profile.emails.filter(verified=False)
        count += len(result['unverified'])
    result['count'] = count
    return result


def userpref_show():
    """Edit user preferences and system settings

    """
    pass


def concatenate_dirs(dir1, dir2):
    """
    Appends dir2 to dir1. It is possible that either/both dir1 or/and dir2 is/are None
    """
    result_dir = dir1 if dir1 is not None and len(dir1) > 0 else ''
    if dir2 is not None and len(dir2) > 0:
        if len(result_dir) == 0:
            result_dir = dir2
        else:
            result_dir += '/' + dir2
    return result_dir


def step_filler(x, y, **kwargs):
    """Wrapper for a specific fill_between plot.

	Parameters
	----------
	x : array-like
		The x-axis values.
	y : array-like
		The y-axis values.
	Other arguments : **kwargs
		Optional kwargs supported by fill_between. Note that it will conflict if 'step' is given.
	Returns
	-------
	val : Recasted value
	"""
    from numpy import empty
    from matplotlib.pyplot import fill_between
    temp_y = empty(len(y) + 1)
    temp_y[1:] = y
    temp_y[0] = y[0]
    fill_between(x, temp_y, step='pre', **kwargs)
    return None


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

        :param TeamActivityCreateReportFailDetails val:
        :rtype: EventDetails
        """
    return cls('team_activity_create_report_fail_details', val)


def create_basic_edgelist_files(graphs, dir_name, common_node=False):
    """Creates files with basic edge list representations of the graphs"""
    for index in range(len(graphs)):
        file = open(dir_name + '/' + 'graph' + str(index) + '.txt', 'w')
        graph = graphs[index]
        if common_node:
            num_vertices = graph.get_num_vertices()
            for i in range(num_vertices):
                file.write('0 ' + str(i + 1) + '\n')
            for edge in graph.get_edges():
                file.write(str(edge[0] + 1) + ' ' + str(edge[1] + 1) + '\n')
        else:
            for edge in graph.get_edges():
                file.write(str(edge[0]) + ' ' + str(edge[1]) + '\n')
        file.close()


def switch_direction():
    """Switch direction of selected splines

    """
    pass


def is_weekend(d_or_dt):
    """Check if a datetime is weekend.
    """
    return d_or_dt.isoweekday() in [6, 7]


def analyze_children(children):
    """Analyzes children of the feature and prints info

    """
    test_strings = []
    for scenario in children:
        print(scenario['keyword'], ':', scenario['name'])
        steps = scenario['steps']
        print('Number of steps in the scenario: ', len(steps))
        print('Following steps found:')
        for step in steps:
            print('    ', step['keyword'], '\t :\t', step['text'])
            text = step['keyword'] + ': ' + step['text']
            if text not in test_strings:
                test_strings.append(text)
            else:
                print('\t*Duplicate test string:', text)
                print('\tOnly first occurence will be used to generate step')
        print('')


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 get_change_token():
    """
    When you want to create, update, or delete AWS WAF objects, get a change token and include the change token in the create, update, or delete request. Change tokens ensure that your application doesn't submit conflicting requests to AWS WAF.
    Each create, update, or delete request must use a unique change token. If your application submits a GetChangeToken request and then submits a second GetChangeToken request before submitting a create, update, or delete request, the second GetChangeToken request returns the same value as the first GetChangeToken request.
    When you use a change token in a create, update, or delete request, the status of the change token changes to PENDING , which indicates that AWS WAF is propagating the change to all AWS WAF servers. Use GetChangeTokenStatus to determine the status of your change token.
    See also: AWS API Documentation

    Examples
    The following example returns a change token to use for a create, update or delete operation.
    Expected Output:

    :example: response = client.get_change_token()

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

    """
    pass


def topk(input, k, dim, descending=True):
    """Return the k largest elements of the given input tensor along the given dimension.

    If descending is False then the k smallest elements are returned.

    Parameters
    ----------
    input : Tensor
        The input tensor.
    k : int
        The number of elements.
    dim : int
        The dim to sort along.
    descending : bool
        Controls whether to return largest/smallest elements.
    """
    pass


def decode_name(nbname):
    """Return the NetBIOS first-level decoded nbname."""
    if len(nbname) != 32:
        return nbname
    l = []
    for i in range(0, 32, 2):
        l.append(chr(ord(nbname[i]) - 65 << 4 | ord(nbname[i + 1]) - 65 & 15))
    return ''.join(l).split('\x00', 1)[0]


@classmethod
def is_usable(cls):
    """
        This implementation has no direct dependencies of its own.
        :rtype: bool
        """
    return True


def psi_K_CO3_Cl_HMW84(T, P):
    """c-a-a': potassium carbonate chloride [HMW84]."""
    psi = 0.004
    valid = T == 298.15
    return psi, valid


def radius_set(radius: float=1.0):
    """Set per-point radius which is used for bevel tapering

    :param radius: Radius
    :type radius: float
    """
    pass


def disconnect_hair(all: bool=False):
    """Disconnect hair from the emitter mesh

    :param all: All hair, Disconnect all hair systems from the emitter mesh
    :type all: bool
    """
    pass


def split_identifier(identifier):
    """
    Split a SQL identifier into a two element tuple of (namespace, name).
    The identifier could be a table, column, or sequence name might be prefixed
    by a namespace.
    """
    try:
        from django.db.backends.utils import split_identifier as django_split_identifier
        return django_split_identifier(identifier)
    except ImportError:
        try:
            namespace, name = identifier.split('"."')
        except ValueError:
            namespace, name = '', identifier
        return namespace.strip('"'), name.strip('"')


def func_lineno(func):
    """Get the line number of a function. First looks for
    compat_co_firstlineno, then func_code.co_first_lineno.
    """
    try:
        return func.compat_co_firstlineno
    except AttributeError:
        try:
            return func.func_code.co_firstlineno
        except AttributeError:
            return -1


def _getWrappedObject():
    """Return the object that was wrapped.

        This has a leading underscore to reduce the risk of clashing with
        an index or metadata column.
        """


def maximals(A, le=lambda x, y: x <= y):
    """ Find the maximal element(s) of a partially ordered sequence"""
    r = []
    for x in A:
        for a in A:
            if le(x, a) and not le(a, x):
                break
        else:
            for a in r:
                if le(x, a):
                    break
            else:
                r.append(x)
    return r


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


def istuple(val):
    """
    check if the entry is a tuple or is a string of tuple

    Parameters
    ----------
    val
        an entry of any type

    Returns
    -------
    bool
        True if the input is either a tuple or a string of tuple, False otherwise

    Notes
    -----
    please note that '(1)' is also a tuple, while (1) is not a tuple

    """
    text = str(val)
    if text[0] == '(' and text[len(text) - 1] == ')':
        return True
    else:
        return False


def writefile_log(output_logfile_name='lauepattern.log', linestowrite=[['']]):
    """
    TODO: maybe useless ?
    """
    filou = open(output_logfile_name, 'w')
    aecrire = linestowrite
    for line in aecrire:
        lineData = '\t'.join(line)
        filou.write(lineData)
        filou.write('\n')
    filou.close()


def assert_is_dict(var):
    """Assert variable is from the type dictionary."""
    if var is None or not isinstance(var, dict):
        return {}
    return var


def _init_a(D):
    """Initial guess for Dirichlet alpha parameters given data D

    Parameters
    ----------
    D : (N, K) shape array
        ``N`` is the number of observations, ``K`` is the number of
        parameters for the Dirichlet distribution.

    Returns
    -------
    (K,) shape array
        Crude guess for parameters of Dirichlet distribution."""
    E = D.mean(axis=0)
    E2 = (D ** 2).mean(axis=0)
    return (E[0] - E2[0]) / (E2[0] - E[0] ** 2) * E


def qualify_name(name_or_qname, to_kind):
    """
    Formats a name or qualified name (kind/name) into a qualified
    name of the specified target kind.
    :param name_or_qname: The name to transform
    :param to_kind: The kind to apply
    :return: A qualified name like: kind/name
    """
    if '/' in name_or_qname:
        name_or_qname = name_or_qname.split('/')[-1]
    return '{}/{}'.format(to_kind, name_or_qname)


@classmethod
def api_step(cls, deposition):
    """Workflow was halted during processing.

        The workflow task that halted processing is expected to provide a
        response to send back to the client.

        The default response code is 500 Internal Server Error. A workflow task
        is expected to use Deposition.set_render_context() with a dictionary
        which is returned to the client. Set the key 'status', to change the
        status code, e.g.::

            d.set_render_context(dict(status=400, message="Bad request"))

        If no response is provided by the workflow task, it is regarded as
        an internal server error.
        """
    ctx = deposition.get_render_context()
    if ctx:
        return ctx.get('response', {}), ctx.get('status', 500)
    return cls.api_error(deposition)


def write_bytes(fp, data):
    """
    Write bytes to the file object and returns bytes written.

    :return: written byte size
    """
    pos = fp.tell()
    fp.write(data)
    written = fp.tell() - pos
    assert written == len(data), 'written=%d, expected=%d' % (written, len(
        data))
    return written


@classmethod
def add_host_collection(cls, options=None):
    """Associate a resource"""
    cls.command_sub = 'add-host-collection'
    return cls.execute(cls._construct_command(options))


def get_protected_properties():
    """
    returns properties never be modified once request is created
    """
    return ['RequestName', '_id']


def agg_ignore_feature(feature_name):
    """Return True if the feature is one to be ignored when aggregating"""
    if feature_name.startswith('Description_'):
        return True
    if feature_name.startswith('ModuleError_'):
        return True
    if feature_name.startswith('TimeElapsed_'):
        return True
    if feature_name == 'Number_Object_Number':
        return True
    return False


def to_prefix(x):
    """
    Peak assignments with characters that are not compatible lmfit model naming
    are converted to lmfit "safe" names.

    :param x: Peak assignment to be used as prefix for lmfit model
    :type x: str

    :returns: lmfit model prefix (_Peak_assignment_)
    :rtype: str

    """
    if type(x) != str:
        x = str(x)
    prefix = '_' + x
    to_replace = [['.', '_'], [' ', ''], ['{', '_'], ['}', '_'], ['[', '_'],
        [']', '_'], ['-', ''], ['/', 'or'], ['?', 'maybe'], ['\\', ''], [
        '(', '_'], [')', '_']]
    for p in to_replace:
        prefix = prefix.replace(*p)
    return prefix + '_'


def l2_dissimilarity(a, b):
    """Compute dissimilarity between rows of  `a` and `b` as
    :math:`||a-b||_2^2`.

    """
    assert len(a.shape) == len(b.shape)
    return (a - b).norm(p=2, dim=-1) ** 2


def attach_measure_zlp(api, window):
    """Attaches the measure ZLP computation to the target data item in the window."""
    target_data_item = window.target_data_item
    if target_data_item and target_data_item.display_xdata.is_data_1d:
        api.library.create_computation('nion.eels_analysis.measure_zlp',
            inputs={'src': target_data_item}, outputs={'zlp_interval': None})


def to_bool(arg):
    """
    Return a boolean value based on `arg`.
    """
    if arg is None or isinstance(arg, bool):
        return arg
    if isinstance(arg, str):
        arg = arg.lower()
    if arg in ('yes', 'on', '1', 'true', 1):
        return True
    return False


def run_script(cursor, script, params=()):
    """Execute a series of statements in the database.

        params should be either an empty tuple (no parameters) or
        a map.

        The statements are transformed by run_script_stmt
        before execution.
        """


def get_code():
    """
        Wait for the wormhole code to be established, then return the code.
        This is really only useful on the initiating side, which needs to
        deliver the code to the user (so the user can dictate it to the other
        user, who can deliver it to their application with ``set_code`` or
        ``input_code``).  On the receiving side, merely submitting the code
        is sufficient.

        The wormhole code is always unicode (so ``str`` on py3, ``unicode``
        on py2).

        For ``allocate_code``, this must wait for the server to allocate a
        nameplate.  For ``input_code``, it waits for the final code to be
        submitted to the helper.  For ``set_code``, it fires immediately.

        :return: the wormhole code
        :rtype: ``Deferred[str]``
        """


def py_type_name(type_name):
    """Get the Python type name for a given model type.

        >>> py_type_name('list')
        'list'
        >>> py_type_name('structure')
        'dict'

    :rtype: string
    """
    return {'blob': 'bytes', 'character': 'string', 'double': 'float',
        'long': 'integer', 'map': 'dict', 'structure': 'dict', 'timestamp':
        'datetime'}.get(type_name, type_name)


def _get_responses(link):
    """ Returns an OpenApi-compliant response
    """
    template = link.response_schema
    template.update({'description': 'Success'})
    res = {(200): template}
    res.update(link.error_status_codes)
    return res


@staticmethod
def _decode_sketchy_utf16(raw_bytes):
    """Method for ignoring utf-16le chars"""
    s = raw_bytes.decode('utf-16le', 'ignore')
    try:
        n = s.index('\x00')
        s = s[:n]
    except ValueError:
        pass
    return s


def read_set_from_file(filename):
    """
    Extract a de-duped collection (set) of text from a file.
    Expected file format is one item per line.
    """
    collection = set()
    with open(filename, 'r', encoding='utf-8') as file_:
        for line in file_:
            collection.add(line.rstrip())
    return collection


@classmethod
def preprocess_rules_permissions(cls, perms):
    """May alter a permissions dict before it's processed further.

        Use this, for instance, to alter the supplied permissions or insert default
        values into the given dict.

        :param perms:
            Shallow-copied value of the rules_permissions model Meta option
        :type  perms: dict
        """


def get_comm_name(name, i):
    """Get the name of the ith comm in the series.

    Args:
        name (str): Name of the fork comm.
        i (int): Index of comm in fork bundle.

    Returns:
        str: Name of ith comm in fork bundle.

    """
    return '%s_%d' % (name, i)


def dow_as_string(date):
    """Return the day of week expressed as a string."""
    days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday',
        'Saturday', 'Sunday']
    return days[date.weekday()]


def _check_is_max_context(doc_spans, cur_span_index, position):
    """Check if this is the 'max context' doc span for the token."""
    best_score = None
    best_span_index = None
    for span_index, doc_span in enumerate(doc_spans):
        end = doc_span.start + doc_span.length - 1
        if position < doc_span.start:
            continue
        if position > end:
            continue
        num_left_context = position - doc_span.start
        num_right_context = end - position
        score = min(num_left_context, num_right_context
            ) + 0.01 * doc_span.length
        if best_score is None or score > best_score:
            best_score = score
            best_span_index = span_index
    return cur_span_index == best_span_index


def _name(state):
    """Makes a unique string for a given state"""
    (x, y), d, c = state
    a = ('X%d' if d & 1 else 'x%d') % x
    b = ('Y%d' if d & 2 else 'y%d') % y
    return b + a if c else a + b


def Fst(alt_freq_i, alt_freq_j):
    """
        Calculates Fst from alternate allele freqs
    """
    if alt_freq_i == alt_freq_j == 1:
        return 0
    if alt_freq_i == alt_freq_j == 0:
        return 0
    ref_freq_i = 1 - alt_freq_i
    ref_freq_j = 1 - alt_freq_j
    H_i = 2 * alt_freq_i * ref_freq_i
    H_j = 2 * alt_freq_j * ref_freq_j
    H_s = (H_i + H_j) / 2
    avg_alt_freq = (alt_freq_i + alt_freq_j) / 2
    avg_ref_freq = (ref_freq_i + ref_freq_j) / 2
    H_t = 2 * avg_alt_freq * avg_ref_freq
    return (H_t - H_s) / H_t


@staticmethod
def ts_delta_str(start, end):
    """
        start <datetime>
        end <datetime>

        returns <str> human readable elapsed time
        """
    delta = end - start
    ts = int(delta.total_seconds())
    hours, remainder = divmod(ts, 3600)
    minutes, seconds = divmod(remainder, 60)
    if hours > 0:
        delta_str = (
            f'{hours} hour(s), {minutes} minute(s), {seconds} second(s)')
    elif minutes > 0:
        delta_str = f'{minutes} minute(s), {seconds} second(s)'
    else:
        delta_str = f'{seconds} second(s)'
    return delta_str


@staticmethod
def _calc_decimaldegree(degree, minute, second):
    """
        Calculate decimal degree form degree, minute, second
        """
    return degree + minute / 60.0 + second / 3600.0


def red(text):
    """ Return this text formatted red """
    return '\x0304%s\x03' % text


def adjust_unit(original: dict, incoming: dict) ->dict:
    """
    Adjusts the original unit dictionary with the incoming dictionary

    :param dict original: original dictionary
    :param dict incoming: adjusting dictionary
    :return: adjusted dictionary
    :rtype: dict
    """
    out = dict(original)
    for unit in incoming:
        if unit in out:
            new = out[unit] + incoming[unit]
            if new == 0:
                del out[unit]
            else:
                out[unit] = new
        else:
            out[unit] = incoming[unit]
    return out


def strip_parameters(request_data, skip_parameters):
    """
    Helper method which will remove the dict items listed in skip_parameters
    @return - dict
    """
    parameters = {}
    for k, v in request_data.items():
        if k not in skip_parameters and v:
            parameters[str(k)] = v
    return parameters


def get_acc_id_dict(id_acc_dict):
    """Invert a dictionary.

    Receives a dictionary where Key = PhageID and Value = Accession.
    Returns a dictionary where Key = Accession and Value = List[PhageIDs]
    Accessions are not guaranteed to be unique.
    """
    new_dict = {}
    for key in id_acc_dict.keys():
        accession = id_acc_dict[key]
        if accession is not None and accession != '':
            if accession not in new_dict.keys():
                new_dict[accession] = [key]
            else:
                new_dict[accession] = new_dict[accession].append(accession)
    return new_dict


def bC_Mg_H2PO4_HFM89(T, P):
    """c-a: magnesium dihydrogen-phosphate [HFM89]."""
    b0 = -3.55
    b1 = 16.9
    b2 = 0
    C0 = 0
    C1 = 0
    alph1 = 2
    alph2 = -9
    omega = -9
    valid = T == 298.15
    return b0, b1, b2, C0, C1, alph1, alph2, omega, valid


def pvwatts_dc(g_poa_effective, temp_cell, pdc0, gamma_pdc, temp_ref=25.0):
    """
    Implements NREL's PVWatts DC power model. The PVWatts DC model [1]_ is:

    .. math::

        P_{dc} = \\frac{G_{poa eff}}{1000} P_{dc0} ( 1 + \\gamma_{pdc} (T_{cell} - T_{ref}))

    Note that the pdc0 is also used as a symbol in :py:func:`pvwatts_ac`. pdc0
    in this function refers to the DC power of the modules at reference
    conditions. pdc0 in :py:func:`pvwatts_ac` refers to the DC power input
    limit of the inverter.

    Parameters
    ----------
    g_poa_effective: numeric
        Irradiance transmitted to the PV cells in units of W/m**2. To be
        fully consistent with PVWatts, the user must have already
        applied angle of incidence losses, but not soiling, spectral,
        etc.
    temp_cell: numeric
        Cell temperature in degrees C.
    pdc0: numeric
        Power of the modules at 1000 W/m2 and cell reference temperature.
    gamma_pdc: numeric
        The temperature coefficient in units of 1/C. Typically -0.002 to
        -0.005 per degree C.
    temp_ref: numeric, default 25.0
        Cell reference temperature. PVWatts defines it to be 25 C and
        is included here for flexibility.

    Returns
    -------
    pdc: numeric
        DC power.

    References
    ----------
    .. [1] A. P. Dobos, "PVWatts Version 5 Manual"
           http://pvwatts.nrel.gov/downloads/pvwattsv5.pdf
           (2014).
    """
    pdc = g_poa_effective * 0.001 * pdc0 * (1 + gamma_pdc * (temp_cell -
        temp_ref))
    return pdc


def set_parameter_requires_grad(model, feature_extracting):
    """
    Utility function for setting parameters gradient collection to true (finetuning) or false (features extraction)
    :param model: pytorch nn.Module class or subclass
    :param feature_extracting: boolean. If True don't collect gradients for the module's parameters
    :return:
    """
    if feature_extracting:
        for param in model.parameters():
            param.requires_grad = False


def _find_next_link(root, current_joint, next_link_name):
    """
    Find the next link in the URDF tree

    Parameters
    ----------
    root
    current_joint: xml.etree.ElementTree
        The current URDF joint
    next_link_name: str
        Optional : The name of the next link. If not provided, find it automatically as the first child of the joint.
    """
    has_next = False
    next_link = None
    if next_link_name is None:
        next_link_name = current_joint.find('child').attrib['link']
    for urdf_link in root.findall('link'):
        if urdf_link.attrib['name'] == next_link_name:
            next_link = urdf_link
            has_next = True
    return has_next, next_link


@classmethod
def common_plot(cls, traces, base, plot_traces=True, plot_exploitabilities=
    True, palette=None, with_regret=True, title=None):
    """
        Create a Plotly plot with trace and exploitability subplots.
        """
    import plotly
    assert plot_exploitabilities or plot_traces
    if plot_traces and plot_exploitabilities:
        fig = plotly.tools.make_subplots(cols=2, print_grid=False,
            column_width=[0.6, 0.4])
    else:
        fig = plotly.graph_objs.Figure()
    if plot_traces:
        fig['layout']['yaxis']['scaleanchor'] = 'x'
    if palette is None:
        palette = plotly.colors.DEFAULT_PLOTLY_COLORS
    for ti, t in enumerate(traces):
        if plot_traces:
            fig.add_traces(t.plot_trace(base=base, color=palette[ti],
                with_regret=with_regret))
        if plot_exploitabilities:
            objs = t.plot_exploitabilities(color=palette[ti], showlegend=
                not plot_traces)
            if plot_traces:
                for o in objs:
                    o.xaxis = 'x2'
                    o.yaxis = 'y2'
            fig.add_traces(objs)
    fig['layout'].update(hovermode='x', title=dict(text=title))
    return fig


def _seasonID(x):
    """takes in 4-digit years and returns API formatted seasonID

    Input Values: YYYY

    Used in:

    """
    if len(str(x)) == 4:
        try:
            return ''.join(['2', str(x)])
        except ValueError:
            raise ValueError(
                'Enter the four digit year for the first half of the desired season'
                )
    else:
        raise ValueError(
            'Enter the four digit year for the first half of the desired season'
            )


@classmethod
def accepts_default_mpiprocs_per_machine(cls):
    """
        Return True if this JobResource accepts a 'default_mpiprocs_per_machine'
        key, False otherwise.
        """
    return False


def word_count(text):
    """ The word-count of the given text. Goes through the string exactly
    once and has constant memory usage. Not super sophisticated though.

    """
    if not text:
        return 0
    count = 0
    inside_word = False
    for char in text:
        if char.isspace():
            inside_word = False
        elif not inside_word:
            count += 1
            inside_word = True
    return count


def img(im, x=None, y=None, xlim=None, ylim=None, clim=[None, None], cmin=0,
    xinvert=False, yinvert=False, cbar_invert=False, clog=None, title=None,
    xlabel=None, ylabel=None, clabel=None, lab_loc=0, ax=None, grid=None,
    plot_kw={}, **kwargs):
    """2D pixel-based image plotting function.

	Parameters
	----------
	im : array-like
		Value for each pixel in an x-y 2D array, where the first dimension is the x-position and the second is
		the y-position.
	x : array-like, optional
		Position of data points in the x axis.
	y : array-like, optional
		Position of data points in the y axis.
	xlim : tuple-like, optional
		Defines the limits of the x-axis, it must contain two elements (lower and higer limits).
	ylim : tuple-like, optional
		Defines the limits of the y-axis, it must contain two elements (lower and higer limits).
	clim : list, optional
		Defines the limits of the colour map ranges, it must contain two elements (lower and higer limits).
	clog : bool, optional
		If True, the colour map is changed from linear to logarithmic.
	xinvert : bool, optional
		If True, inverts the x-axis.
	yinvert : bool, optional
		If True, inverts the y-axis.
	cbar_invert : bool, optional
		If True, inverts the direction of the colour bar (not the colour map).
	title : str, optional
		Sets the title of the plot
	xlabel : str, optional
		Sets the label of the x-axis.
	ylabel : str, optional
		Sets the label of the y-axis.
	clabel : str, optional
		Sets the legend for the colour axis.
	lab_loc : int, optional
		Defines the position of the legend
	ax : pyplot.Axes, optional
		Use the given axes to make the plot, defaults to the current axes.
	grid : boolean, optional
		If not given defaults to the value defined in splotch.Params.
	plot_kw : dict, optional
		Explicit dictionary of kwargs to be parsed to matplotlib pcolormesh function.
		Parameters will be overwritten if also given implicitly as a **kwarg.
	**kwargs : pcolormesh properties, optional
		kwargs are used to specify matplotlib specific properties such as `cmap`, `marker`, `norm`, etc.
		A list of available `pcolormesh` properties can be found here:
		https://matplotlib.org/api/_as_gen/matplotlib.pyplot.pcolormesh.html

	Returns
	-------
	None
	"""
    from numpy import arange, meshgrid
    from matplotlib.colors import LogNorm
    from matplotlib.pyplot import pcolormesh, colorbar
    from .base_func import axes_handler, plot_finalizer
    if ax is not None:
        old_axes = axes_handler(ax)
    if x is None:
        x = arange(len(im[:, (0)]) + 1)
    if y is None:
        y = arange(len(im[(0), :]) + 1)
    if clog is None:
        from .defaults import Params
        clog = Params.img_caxis_log
    X, Y = meshgrid(x, y)
    plot_par = plot_kw.copy()
    plot_par.update(kwargs)
    if clog:
        pcolormesh(X, Y, im.T, norm=LogNorm(vmin=clim[0], vmax=clim[1],
            clip=True), **plot_par)
    else:
        pcolormesh(X, Y, im.T, vmin=clim[0], vmax=clim[1], **plot_par)
    if clabel is not None:
        cbar = colorbar()
        cbar.set_label(clabel)
        if cbar_invert:
            cbar.ax.invert_yaxis()
    plot_finalizer(False, False, xlim, ylim, title, xlabel, ylabel, xinvert,
        yinvert, grid)
    if ax is not None:
        old_axes = axes_handler(old_axes)


def sign(x):
    """Return ``1.0`` if ``x`` is positive, ``-1.0`` otherwise."""
    if x > 0.0:
        return 1.0
    else:
        return -1.0


def n_sum(n: int):
    """Calculates sum of first `n` numbers, e.g. 1+2+3+...n"""
    return n * (n + 1) / 2


def get_values_from_dict_list(list_of_dicts):
    """Convert a list of dictionaries to a set of the dictionary values.

    :param list_of_dicts: List of dictionaries.
    :type list_of_dicts: list
    :returns: Set of values from all dictionaries in the list.
    :rtype: set
    """
    output_set = set()
    for dict in list_of_dicts:
        output_set = output_set | set(dict.values())
    return output_set


def find_missing_items(intList):
    """
    Returns missing integers numbers from a list of integers
    :param intList: list(int), list of integers
    :return: list(int),  sorted list of missing integers numbers of the original list
    """
    original_set = set(intList)
    smallest_item = min(original_set)
    largest_item = max(original_set)
    full_set = set(range(smallest_item, largest_item + 1))
    return sorted(list(full_set - original_set))


def list_dockerfiles_in_git():
    """
    clone provided repo and return all dockerfiles found in the repo

    :return:
    """


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

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

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


def make_cache_key(visitor_key):
    """ make the cache key for visitor """
    return 'visitor_%s' % visitor_key


@classmethod
def range(cls, from_=1, to=None, step=1):
    """
        Returns an iterator over specified comics.

        Use negative numbers to specify from the end.

        :param int from_: The comic to start from. Defaults to the first.
        :param Optional[int] to: The comic to end by (exclusive). Defaults to last + 1.
        :param int step: The step amount. Defaults to one.
        :return: A range over the requested comics.
        """
    if to is None:
        if step < 0:
            to = 0
        else:
            to = cls.latest() + 1
    return range(from_, to, step)


@classmethod
def get_jira_ticket_key_from_branch(cls, branch):
    """Construct a Jira ticket key based on the git branch name.

        For now it only replaces underscores with dashes and makes it uppercase.
        Eg. "proj_xxxx" -> "PROJ-XXXX"
        """
    if branch:
        jira_ticket_key = branch.upper().replace('_', '-')
    else:
        jira_ticket_key = None
    return jira_ticket_key


def is_jsfunc(func: str) ->bool:
    """Heuristically check function or expression."""
    func = func.strip()
    if func.startswith('function') or func.startswith('async '):
        return True
    elif '=>' in func:
        return True
    return False


def p_BooleanLiteral_true(p):
    """BooleanLiteral : true"""
    p[0] = True


@classmethod
def get_description(cls):
    """return description of the potential type"""
    return ''


def check_hotlinetimings(dump):
    """check to linetimings hotshot-profile datafile."""
    signature = 'yes'.encode()
    return True if dump.find(signature) > 0 else False


def parse_options(options):
    """Parse the analysis options field to a dictionary."""
    ret = {}
    for field in options.split(','):
        if '=' not in field:
            continue
        key, value = field.split('=', 1)
        ret[key.strip()] = value.strip()
    return ret


def set_vertex(idfObj, vertexNum: int, x: float=0, y: float=0, z: float=0):
    """Sets a single vertex of the passed idfObject (idfObj)
     to the specified x,y and z coordinates."""
    for val, name in zip((x, y, z), 'XYZ'):
        idfObj['Vertex_{}_{}coordinate'.format(vertexNum, name)] = round(val, 2
            )


def trim_data(ps, common_support, data):
    """This function trims the data below and above the common support."""
    data_trim = data[(data.ps >= common_support[0]) & (data.ps <=
        common_support[1])]
    ps_trim = ps[(ps >= common_support[0]) & (ps <= common_support[1])]
    return data_trim, ps_trim


def getMessageReferrers(message_id, reversed=True):
    """Returns a list of proxies for all messages that directly respond
           to the given message_id (i.e. the entire thread), ordered by date,
           optionally sorted in reverse with most recent reply first."""


def dist_ss_shear_bending(L, win, ain):
    """
    Shear Bending plot of distributed loads of a simply supported beam
    L = 10 # total length of beam
    win = [5]  # distributed load
    ain = [[3,4]]  # location of point load

    # or more multiple point moments
    L = 10
    win = [3,6]
    ain = [[0,3],[4,6]]
    """
    import numpy as np
    import matplotlib.pyplot as plt
    x = np.arange(0, L, L * 0.02)
    V = np.zeros(len(x))
    M = np.zeros(len(x))
    for a, w in zip(ain, win):
        P = w * (a[1] - a[0])
        l = (a[1] + a[0]) / 2
        i = [x < a[0]]
        V[i] += P * (1 - l / L)
        M[i] += x[i] * P * (1 - l / L)
        i = [x > a[1]]
        V[i] += -P * l / L
        M[i] += x[i] * -P * l / L + P * l
        i = [(a[0] <= x) & (x <= a[1])]
        V[i] += P * (1 - l / L) - w * (x[i] - a[0])
        M[i] += (P * (1 - l / L) - w * (x[i] - a[0])) * x[i] + w * (x[i] - a[0]
            ) * (a[0] + x[i]) / 2
    plt.figure()
    plt.title('Point Moment Loads')
    plt.subplot(2, 1, 1)
    plt.stem(x, V)
    plt.ylabel('V,shear')
    plt.subplot(2, 1, 2)
    plt.stem(x, M)
    plt.ylabel('M,moment')


def setup(args):
    """This method is provided for subclasses to override, to extract
        parameters from the 'args' dictionary. The default implementation does
        nothing. It will be called from __init__"""


@staticmethod
def _add_gaf_object_type(gaf_record: dict, featuretype: str) ->None:
    """Adds the feature type to a GAF record"""
    gaf_record['DB_Object_Type'] = featuretype


def parseTerms(text):
    """Pass the text through the pipeline.

        Return a list of words, normalized by the pipeline
        (e.g. stopwords removed, case normalized etc.).
        """


def _post_process_specs(specs):
    """Post-process specs after pure parsing

    Casts any number expected values into integers

    Parameters
    ----------
    specs :

    Note
    -----
    Modifies the specs object
    """
    integer_specs = ['DIMENSION', 'CAPACITY']
    for s in integer_specs:
        specs[s] = int(specs[s])


def serial_escape(value):
    """Escape string values that are elements of a list, for serialization."""
    return value.replace('\\', '\\\\').replace(' ', '\\ ')


def add_capacity_factor(variable_component_names, **kwargs):
    """Add capacity factor to :py:obj:`variable_component_to_load_names`.

    :param variable_component_names: Names of components to load per
      variable.
    :type variable_component_names: mapping from :py:class:`str`
      to collection

    :returns: Names of components to load per variable with
      capacity factor added.
    :rtype: mapping from :py:class:`str` to collection
    """
    variable_name = 'capacity_factor'
    variable_component_to_load_names = variable_component_names.copy()
    if variable_name in variable_component_names:
        variable_component_to_load_names.update({'generation':
            variable_component_names[variable_name], 'capacity':
            variable_component_names[variable_name]})
        del variable_component_to_load_names['capacity_factor']
    return variable_component_to_load_names


@classmethod
def line_tag_parse(cls, tagged_line, symbol_or_re=None, is_re=False,
    strip_comment=None):
    """Parse a line tag line into tag-symbol and argument parts.

        :returns: a tuple ``(tag-symbol, tag-arguments)``.

        See :meth:`adhoc_parse_line`.
        """
    return cls.adhoc_parse_line(tagged_line, symbol_or_re, cls.
        line_delimiters, is_re, strip_comment=strip_comment)


def formula_2006(foyer_fiscal, period, parameters):
    """
        Parts ou actions détenues par les salariés et mandataires sociaux
        """
    b1cl = foyer_fiscal('b1cl', period)
    P = parameters(period).taxation_capital.isf_ifi.droits_soc
    return b1cl * P.taux1


def symbols_from_xyz(xyz_list):
    """
        Takes a list of lists containing xyz file lines and the elemental symbols

        Parameters
        ----------
        xyz_list: List of lists
            Outer list is whole xyz file, each inner list is a line of the file containing
            the symbol and x,y,z coordinates

        Returns
        ----------
        symbols: List of strings
            List of atomic symbols
        """
    symbols = []
    for i in range(len(xyz_list)):
        symbols.append(str(xyz_list[i][0]))
    return symbols


def _info(text):
    """Colorize terminal output to bold blue."""
    return '\x1b[1m\x1b[34m{text}\x1b[0m'.format(text=text)


def enable_validate_multiframe_implicit():
    """
    Enable the validation that checks that data is not multiframe implicit again (DEFAULT ENABLED)
    """
    global validate_multiframe_implicit
    validate_multiframe_implicit = True


@classmethod
def get_codigo_especificacion():
    """Código asignado en especificaciones"""
    return -1


@classmethod
def from_components(cls, context, instance_uuid, image, flavor,
    numa_topology, pci_requests, filter_properties, instance_group,
    availability_zone, security_groups=None, project_id=None, user_id=None,
    port_resource_requests=None):
    """Returns a new RequestSpec object hydrated by various components.

        This helper is useful in creating the RequestSpec from the various
        objects that are assembled early in the boot process.  This method
        creates a complete RequestSpec object with all properties set or
        intentionally left blank.

        :param context: a context object
        :param instance_uuid: the uuid of the instance to schedule
        :param image: a dict of properties for an image or volume
        :param flavor: a flavor NovaObject
        :param numa_topology: InstanceNUMATopology or None
        :param pci_requests: InstancePCIRequests
        :param filter_properties: a dict of properties for scheduling
        :param instance_group: None or an instance group NovaObject
        :param availability_zone: an availability_zone string
        :param security_groups: A SecurityGroupList object. If None, don't
                                set security_groups on the resulting object.
        :param project_id: The project_id for the requestspec (should match
                           the instance project_id).
        :param user_id: The user_id for the requestspec (should match
                           the instance user_id).
        :param port_resource_requests: a list of RequestGroup objects
                                       representing the resource needs of the
                                       neutron ports
        """
    spec_obj = cls(context)
    spec_obj.num_instances = 1
    spec_obj.instance_uuid = instance_uuid
    spec_obj.instance_group = instance_group
    if spec_obj.instance_group is None and filter_properties:
        spec_obj._populate_group_info(filter_properties)
    spec_obj.project_id = project_id or context.project_id
    spec_obj.user_id = user_id or context.user_id
    spec_obj._image_meta_from_image(image)
    spec_obj._from_flavor(flavor)
    spec_obj._from_instance_pci_requests(pci_requests)
    spec_obj._from_instance_numa_topology(numa_topology)
    spec_obj.ignore_hosts = filter_properties.get('ignore_hosts')
    spec_obj.force_hosts = filter_properties.get('force_hosts')
    spec_obj.force_nodes = filter_properties.get('force_nodes')
    spec_obj._from_retry(filter_properties.get('retry', {}))
    spec_obj._from_limits(filter_properties.get('limits', {}))
    spec_obj._from_hints(filter_properties.get('scheduler_hints', {}))
    spec_obj.availability_zone = availability_zone
    if security_groups is not None:
        spec_obj.security_groups = security_groups
    spec_obj.requested_destination = filter_properties.get(
        'requested_destination')
    spec_obj.requested_resources = []
    if port_resource_requests:
        spec_obj.requested_resources.extend(port_resource_requests)
    spec_obj.obj_set_defaults()
    return spec_obj


def get_unitypackage_filename(project_name, version, configuration):
    """Generates .unitypackage file name using project name, version and configuration
    :param project_name: Project name
    :param version: Project version
    :param configuration: Build configuration (Debug/Release)
    :return: Name for .unitypackage file
    """
    return '{0}_{1}_{2}.unitypackage'.format(project_name, version,
        configuration)


def _check_valid(key, val, valid):
    """Helper to check valid options"""
    if val not in valid:
        raise ValueError('%s must be one of %s, not "%s"' % (key, valid, val))


def p_macro_def_arg_list_rec_empty(p):
    """macro_def_arg_list_rec : empty"""
    p[0] = []


def lookupNamingAuthorityPointer(name, timeout=None):
    """
        Perform a NAPTR 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 upcase(string):
    """Return an uppercase version of the string.

    Used for the type argument in argparse/
    """
    return string.upper()


def read_lines(filename):
    """Read all lines from a given file."""
    with open(filename) as fp:
        return fp.readlines()


def get_default_value(key):
    """ Gives default values according to the given key """
    default_values = {'instructions_file': 'instructions.in', 'gmx_path':
        'gmx', 'terms': ['Potential'], 'selection': 'System', 'xvg': 'none',
        'dista': False, 'method': 'linkage', 'cutoff': 0.1, 'fit_selection':
        'System', 'center_selection': 'System', 'output_selection':
        'System', 'pbc': 'mol', 'center': True, 'fit': 'none', 'ur':
        'compact', 'skip': 1, 'start': 0, 'end': 0, 'dt': 0, 'ot_str_ens':
        'pdb'}
    return default_values[key]


def usage():
    """
    Print command line help
    """
    print(
        """usage : flexi_splitter -f <inputfile1[,inputfile2...,inputfileN]> -o <outputfolder> -c <configfile> [OPTIONS]
"""
        )
    print(
        """mandatory parameters :
        -f, --fastqs   list of fastq files separated by a comma without whitespace
        -o, --ofolder  path to the output folder. Need to be empty or if not
                       exists, flexi_splitter creates it
        -c, --config   path to the config file in yaml format

options :
        -h, --help     print this message
        -v, --verbose  only usefull for debugging
        -m, --mismatch mismatches allowed per adaptor. By default, n-1
                       mismatches are allowed (n = adaptor length)
        -n, --ntuple   number of matched files. If not set, flexi_splitter try
                       to guess it from the config file
        --version      print flexi_splitter version """
        )


@classmethod
def unitSize(cls, value, typeCode=None):
    """Determine unit size of an array (if possible)"""
    try:
        return value.__class__.__min_dimension__
    except AttributeError as err:
        dim = cls.dims(value)[-1]
        value.__class__.__min_dimension__ = dim
        return dim


@staticmethod
def metaclassing(your_class, label=None, attributes=None):
    """
        Creating a class using metas.
        Very usefull for automatic algorithms.
        """
    methods = dict(your_class.__dict__)
    if attributes is not None and isinstance(attributes, dict):
        for key, value in attributes.items():
            methods.update({key: value})
    return type(label, (your_class,), methods)


@classmethod
def verify_logout_request(cls, logout_request, ticket):
    """verifies the single logout request came from the CAS server
        returns True if the logout_request is valid, False otherwise
        """
    try:
        session_index = cls.get_saml_slos(logout_request)
        session_index = session_index[0].text
        if session_index == ticket:
            return True
        else:
            return False
    except (AttributeError, IndexError):
        return False


def _parse_squad_name(team_id):
    """
    Parse and clean the team's name.

    To try and match requested team names with the master squad ID list, passed
    names should be parsed to remove the common 'FC' and 'CF' tags, as well as
    force all strings to be lowercase and excess whitespace removed.

    Parameters
    ----------
    team_id : string
        The requested team's name to be parsed.

    Returns
    -------
    string
        Returns a ``string`` of the parsed team's name.
    """
    name = team_id.replace(' FC', '')
    name = name.replace('FC ', '')
    name = name.replace(' CF', '')
    name = name.replace('CF ', '')
    name = name.lower()
    name = name.strip()
    return name


def density_filter(X, k=2, inverse=True, normalize=True, **kwargs):
    """ Return function that filters the data by codensity.

    Parameters
    ----------
    k: int
        * calculate distance to k-th nearest neighbor

    p: float
        * threshold percentage to keep

    Returns
    -------
    indices: tuple of np.ndarrays
        * indices of core points in the data set

    """
    from sklearn.neighbors import KDTree
    tree = KDTree(X, metric='minkowski', p=2, leaf_size=15)
    dist, ind = tree.query(X, k=k + 1)
    dens = dist[:, 1:]
    if inverse is True:
        dens = 1.0 / dens
    if normalize is True:
        dens /= dens.max(axis=0)
    return dens


def surfacedeform_bind(modifier: str=''):
    """Bind mesh to target in surface deform modifier

    :param modifier: Modifier, Name of the modifier to edit
    :type modifier: str
    """
    pass


def is_coordsys(obj):
    """ Test if `obj` has the CoordinateSystem API

    Parameters
    ----------
    obj : object
        Object to test

    Returns
    -------
    tf : bool
        True if `obj` has the coordinate system API

    Examples
    --------
    >>> is_coordsys(CoordinateSystem('xyz'))
    True
    >>> is_coordsys(CoordSysMaker('ikj'))
    False
    """
    if not hasattr(obj, 'coord_names'):
        return False
    if not hasattr(obj, 'name'):
        return False
    if not hasattr(obj, 'coord_dtype'):
        return False
    return not callable(obj)


def normalize_mac(mac):
    """Remove '-' and ':' characters and lowercase the MAC string.

    :param mac: MAC address to normalize.
    :return: Normalized MAC address string.
    """
    return mac.replace('-', '').replace(':', '').lower()


def make_hook(timing, stage, fn):
    """Inner decorator for making a function usable as a hook."""
    planterbox_hook_timing = getattr(fn, 'planterbox_hook_timing', set())
    planterbox_hook_timing.add((timing, stage))
    fn.planterbox_hook_timing = planterbox_hook_timing
    return fn


def linuxify(winSepStr, doubleBackslash=False):
    """
    Convert windows (path) string to the linux format.

    :param winSepStr: (path) string with windows-like "" separators
    :param doubleBackslash: if the slashes in the winSepStr are double (happens when you read a macro string raw. Ex.: "C:\\Program Files\\a.txt"
    :return: str with substituted "" -> "/"
    """
    if doubleBackslash:
        return winSepStr.replace('\\\\', '/')
    return winSepStr.replace('\\', '/')


@staticmethod
def __utf16_decode_surrogate_pair(leading, trailing):
    """Returns the unicode code point corresponding to leading surrogate
        'leading' and trailing surrogate 'trailing'.  The return value will not
        make any sense if 'leading' or 'trailing' are not in the correct ranges
        for leading or trailing surrogates."""
    w = leading >> 6 & 15
    u = w + 1
    x0 = leading & 63
    x1 = trailing & 1023
    return u << 16 | x0 << 10 | x1


def date2str(date, format='%Y-%m-%d'):
    """Convert a datetime object to a string"""
    return date.strftime(format)


@classmethod
def normalize(cls, obj):
    """Normalize an object, if possible, to conform to this type.

        Args:
            obj (object): Object to normalize.

        Returns:
            object: Normalized object.

        """
    if isinstance(obj, str):
        try:
            obj = cls.decode_data(obj, {'type': 'function'})
        except (ValueError, AttributeError):
            pass
    return obj


@classmethod
def get_default_connection_name(cls):
    """Return the name of current connection."""
    if cls._default_connection is None:
        raise ConnectionError("Haven't connected to Mongdb")
    return cls._default_connection


def getvar(storage, variable):
    """Retrieves a variable

        .. code-block:: xml

            $ variable
            $variable
        """
    return storage[variable]


def _alexander_sympy(crossings, variable=None, quadrant='lr'):
    """
    Sympy implementation of the Alexander polynomial, evaluated
    with the variable replaced by some sympy expression.
    """
    import sympy as sym
    if variable is None:
        variable = sym.var('t')
    num_crossings = int(len(crossings) / 2)
    matrix = sym.zeros(num_crossings)
    line_num = 0
    crossing_num_counter = 0
    crossing_dict = {}
    crossing_exists = False
    over_clock = 1 - 1 / variable
    under_clock_after = 1 / variable
    over_aclock = 1 - variable
    under_aclock_after = variable
    for i in range(len(crossings)):
        identifier, over, clockwise = crossings[i]
        if identifier in crossing_dict:
            crossing_num = crossing_dict.pop(identifier)
            crossing_exists = True
        if not crossing_exists:
            crossing_num = crossing_num_counter
            crossing_num_counter += 1
            crossing_dict[identifier] = crossing_num
        crossing_exists = False
        if over > 0.99999:
            mat_elt = over_clock if clockwise > 0.999 else over_aclock
            matrix[crossing_num, line_num % num_crossings] = mat_elt
        else:
            new_mat_elt = (under_clock_after if clockwise > 0.999 else
                under_aclock_after)
            matrix[crossing_num, line_num % num_crossings] = -1
            line_num += 1
            matrix[crossing_num, line_num % num_crossings] = new_mat_elt
    if quadrant == 'lr':
        poly_val = matrix[1:, 1:].det()
    elif quadrant == 'ur':
        poly_val = matrix[:-1, 1:].det()
    elif quadrant == 'ul':
        poly_val = matrix[:-1, :-1].det()
    elif quadrant == 'll':
        poly_val = matrix[1:, :-1].det()
    return poly_val


def get_bitfield_length(bit_count: int) ->int:
    """Return the length of the bitfield for a given number of attesters in bytes."""
    return (bit_count + 7) // 8


def use_rbg():
    """
    Swaps the Green and Blue channels on the LED backlight

    Use if you have a first batch Display-o-Tron 3K
    """
    global LED_R_G, LED_R_B
    global LED_M_G, LED_M_B
    global LED_L_G, LED_L_B
    LED_R_G, LED_R_B = LED_R_B, LED_R_G
    LED_M_G, LED_M_B = LED_M_B, LED_M_G
    LED_L_G, LED_L_B = LED_L_B, LED_L_G


@classmethod
def _get(cls, kwarg_name):
    """ Returns a Param Class Instance, by its kwarg or param name """
    param_classes = cls._discover_params()
    try:
        param_class = param_classes[kwarg_name]
    except KeyError:
        raise ValueError('invalid param keyword {}'.format(kwarg_name))
    else:
        return param_class


def displ2ea(scale, disp, base):
    """ displacement to effective address """
    dest = base + 4 + scale * disp
    if dest < 0:
        dest = -dest
        dest = dest ^ 18446744073709551615
        dest = dest + 1
    return dest


def was_damaged_by_user(info):
    """
        Process 'user was damaged by user' event.

        Input:
        `info`  # An object with information about event's time, user's
                # callsign and aircraft, attacker's callsign and aircraft,
                # position on map.
        """


def join_uri(uri, *segments):
    """Append segments to URI.

    Example: join_uri("/a/b", "c", "d")
    """
    sub = '/'.join(segments)
    if not sub:
        return uri
    return uri.rstrip('/') + '/' + sub


@staticmethod
def calc_depth_tor(mag: float, mechanism: str) ->float:
    """Calculate an estimate of the depth to top of rupture (km).

        Parameters
        ----------
        mag : float
            moment magnitude of the event (:math:`M_w`)
        mechanism : str
            fault mechanism. Valid options: "U", "SS", "NS",
            "RS".

        Returns
        -------
        depth_tor : float
            estimated depth to top of rupture (km)

        """
    if mechanism == 'RS':
        depth_tor = 2.704 - 1.226 * max(mag - 5.849, 0)
    else:
        depth_tor = 2.673 - 1.136 * max(mag - 4.97, 0)
    return max(depth_tor, 0) ** 2


@classmethod
def serialize_value(cls, _type, value):
    """Serialize the typed value as a string"""
    _type = cls.TYPE_ALIAS.get(_type, _type)
    if (_type in cls.INT_TYPES + cls.UINT_TYPES + cls.FLOAT_TYPES + cls.
        FRACTION_TYPES):
        return str(value)
    if _type in cls.BOOLEAN_TYPES:
        if value:
            return 'true'
        return 'false'
    if _type in cls.STRING_TYPES:
        if value is not None and type(value) is not str:
            value = value.encode('utf8')
        return cls.serialize_string(value)
    raise ValueError(
        'The type {} is unknown, so the value ({}) can not be serialized.'.
        format(_type, str(value)))


@classmethod
def export_obj(cls, mesh, filename):
    """
        Write a mesh instance to a Wavefront OBJ (.obj) mesh file.

        :param Mesh mesh: The Raysect mesh instance to write to OBJ.
        :param str filename: Mesh file path.

        .. code-block:: pycon

            >>> bunny_mesh
            <raysect.primitive.mesh.mesh.Mesh at 0x7f2c09eac2e8>
            >>> from raysect.primitive import export_obj
            >>> export_obj(bunny_mesh, 'my_mesh.obj')
        """
    with open(filename, 'w') as f:
        if mesh.name:
            f.write('# Generated by Raysect\n# Mesh name: {}\n'.format(mesh
                .name))
        else:
            f.write('# Exported Raysect Mesh\n')
        for vertex in mesh.data.vertices:
            f.write('v {:6e} {:6e} {:6e}\n'.format(vertex[0], vertex[1],
                vertex[2]))
        if mesh.data.vertex_normals is None:
            for triangle in mesh.data.triangles:
                triangle += 1
                f.write('f {:d} {:d} {:d}\n'.format(triangle[0], triangle[1
                    ], triangle[2]))
        else:
            for normal in mesh.data.vertex_normals:
                f.write('vn {:6e} {:6e} {:6e}\n'.format(normal[0], normal[1
                    ], normal[2]))
            for triangle in mesh.data.triangles:
                triangle += 1
                f.write('f {:d}//{:d} {:d}//{:d} {:d}//{:d}\n'.format(
                    triangle[0], triangle[3], triangle[1], triangle[4],
                    triangle[2], triangle[5]))


def unescape_html(chatbot, statement):
    """
    Convert escaped html characters into unescaped html characters.
    For example: "<b>" becomes "<b>".
    """
    import sys
    if sys.version_info[0] < 3:
        from HTMLParser import HTMLParser
        html = HTMLParser()
    else:
        import html
    statement.text = html.unescape(statement.text)
    return statement


@classmethod
def _from_et(cls, root, parent):
    """
        Create a :class:`Description` from a :code:`description` element.

        :param root: The element tree tree to parse.
        :param parent: :class:`EagleFilePart` that should hold the resulting :class:`EagleFilePart`
        :rtype: :class:`Description`
        """
    n = cls()
    n._init_from_et(root, parent)
    return n


def glLoadMatrix(m: 'Buffer'):
    """Replace the current matrix with the specified matrix

    :param m: Specifies a pointer to 16 consecutive values, which are used as the elements of a 4x4 column-major matrix.
    :type m: 'Buffer'
    """
    pass


def weightedUtest(g1, w1, g2, w2):
    """ Determines the confidence level of the assertion:
    'The values of g2 are higher than those of g1'.
    (adapted from the scipy.stats version)

    Twist: here the elements of each group have associated weights,
    corresponding to how often they are present (i.e. two identical entries with
    weight w are equivalent to one entry with weight 2w).
    Reference: "Studies in Continuous Black-box Optimization", Schaul, 2011 [appendix B].

    TODO: make more efficient for large sets.
    """
    from scipy.stats.distributions import norm
    import numpy
    n1 = sum(w1)
    n2 = sum(w2)
    u1 = 0.0
    for x1, wx1 in zip(g1, w1):
        for x2, wx2 in zip(g2, w2):
            if x1 == x2:
                u1 += 0.5 * wx1 * wx2
            elif x1 > x2:
                u1 += wx1 * wx2
    mu = n1 * n2 / 2.0
    sigu = numpy.sqrt(n1 * n2 * (n1 + n2 + 1) / 12.0)
    z = (u1 - mu) / sigu
    conf = norm.cdf(z)
    return conf


def getReactionFromCode(value):
    """
    The input value must be one of: 71, 72, 73, 74, 75
    Returns one of coherent, incoherent, photoelectric, pair, triplet
    according to the integer EPDL97 code of the reaction:
                    71 <-> coherent scattering
                    72 <-> incoherent scattering
                    73 <-> photoelectric effect
                    74 <-> pair production
                    75 <-> triplet production
                    93 <-> whole atom parameters
    """
    if value == 71:
        return 'coherent'
    if value == 72:
        return 'incoherent'
    if value in [73, 93]:
        return 'photoelectric'
    if value == 74:
        return 'pair'
    if value == 75:
        return 'triplet'
    raise ValueError('Invalid reaction descriptor code')


def add_chr(f):
    """
    Prepend "chr" to the beginning of chromosome names.

    Useful when passed to pybedtool.BedTool.each().
    """
    f.chrom = 'chr' + f.chrom
    return f


def get_listOfProducts(reaction):
    """
    return list of products of a reaction
    """
    listOfProducts = None
    for e in reaction:
        if e.tag[0] == '{':
            uri, tag = e.tag[1:].split('}')
        else:
            tag = e.tag
        if tag == 'listOfProducts':
            listOfProducts = e
            break
    return listOfProducts


def set_htl(A, a):
    """ Return the half-top-left of the given array.
    """
    nx, _ = A.shape
    li = int(nx / 2)
    A[:li, :li] = a


def is_digest_subscriber(subscriber):
    """
        Returns True or False based on whether or not the provided
        subscriber identifier represents a subscriber who receives in
        digest mode.
        """


def get_loaded_plugins():
    """Returns a list of plugins that have been loaded."""


def birch(V, E0, B0, BP, V0):
    """
    From Intermetallic compounds: Principles and Practice, Vol. I: Principles
    Chapter 9 pages 195-210 by M. Mehl. B. Klein, D. Papaconstantopoulos
    paper downloaded from Web

    case where n=0
    """
    E = E0 + 9 / 8 * B0 * V0 * ((V0 / V) ** (2 / 3) - 1
        ) ** 2 + 9 / 16 * B0 * V0 * (BP - 4) * ((V0 / V) ** (2 / 3) - 1) ** 3
    return E


def streq_const_time(s1, s2):
    """Constant-time string comparison.

    :params s1: the first string
    :params s2: the second string

    :return: True if the strings are equal.

    This function takes two strings and compares them.  It is intended to be
    used when doing a comparison for authentication purposes to help guard
    against timing attacks.
    """
    if len(s1) != len(s2):
        return False
    result = 0
    for a, b in zip(s1, s2):
        result |= ord(a) ^ ord(b)
    return result == 0


def add_zero(nb):
    """Converts a number to a string and adds a '0' if less than 10.

    .. code-block:: python

        pycof.add_zero(nb)

    :Parameters:
        * **nb** (:obj:`float`): Number to be converted to a string.

    :Example:
        >>> pycof.add_zero(2)
        ... '02'

    :Returns:
        * :obj:`str`: Converted number qs a string.
    """
    if nb < 10:
        return '0' + str(nb)
    else:
        return str(nb)


@staticmethod
def competence(s):
    """
        This function is used by Sampler to determine which step method class
        should be used to handle stochastic variables.

        Return value should be a competence
        score from 0 to 3, assigned as follows:

        0:  I can't handle that variable.
        1:  I can handle that variable, but I'm a generalist and
            probably shouldn't be your top choice (Metropolis
            and friends fall into this category).
        2:  I'm designed for this type of situation, but I could be
            more specialized.
        3:  I was made for this situation, let me handle the variable.

        In order to be eligible for inclusion in the registry, a sampling
        method's init method must work with just a single argument, a
        Stochastic object.

        If you want to exclude a particular step method from
        consideration for handling a variable, do this:

        Competence functions MUST be called 'competence' and be decorated by the
        '@staticmethod' decorator. Example:

            @staticmethod
            def competence(s):
                if isinstance(s, MyStochasticSubclass):
                    return 2
                else:
                    return 0

        :SeeAlso: pick_best_methods, assign_method
        """
    return 0


@staticmethod
def get_subtype(object_dictionary):
    """
        Given the hash representation of a subtype of this class,
        use the info in the hash to return the class of the subtype.
        """
    type = object_dictionary['type']
    if type == 'volumeGroupId':
        return 'VolumeGroupSourceFromVolumeGroupDetails'
    if type == 'volumeIds':
        return 'VolumeGroupSourceFromVolumesDetails'
    if type == 'volumeGroupBackupId':
        return 'VolumeGroupSourceFromVolumeGroupBackupDetails'
    else:
        return 'VolumeGroupSourceDetails'


def edit(newTitle, newBody, newAuthor, newTags):
    """
        Change the contents of this blurb to refer to a new body, title, and
        author.

        @param newTitle: the title of the new blurb.
        @type newTitle: L{unicode}

        @param newBody: the body text of the new blurb.
        @type newBody: L{unicode}

        @param newAuthor: the primary role of the entity which is attempting
        to create the child posting.
        @type newAuthor: L{xmantissa.sharing.Role}

        @param newTags: the tags of the new blurb
        @type newTags: sequence of C{unicode}
        """


def delete_egress_only_internet_gateway(DryRun=None,
    EgressOnlyInternetGatewayId=None):
    """
    Deletes an egress-only Internet gateway.
    See also: AWS API Documentation

    :example: response = client.delete_egress_only_internet_gateway(
        DryRun=True|False,
        EgressOnlyInternetGatewayId='string'
    )

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

    :type EgressOnlyInternetGatewayId: string
    :param EgressOnlyInternetGatewayId: [REQUIRED]
            The ID of the egress-only Internet gateway.

    :rtype: dict
    :return: {
        'ReturnCode': True|False
    }

    """
    pass


def to_sql(selection):
    """
    Convert selection to a SQL condition (i.e., something that may be used in a
    where clause).
    """
    if hasattr(selection, 'to_sql'):
        return selection.to_sql()
    return str(selection)


def six_hump_camel_func(x):
    """
    Definition of the six-hump camel
    """
    x1 = x[0]
    x2 = x[1]
    term1 = (4 - 2.1 * x1 ** 2 + x1 ** 4 / 3) * x1 ** 2
    term2 = x1 * x2
    term3 = (-4 + 4 * x2 ** 2) * x2 ** 2
    return term1 + term2 + term3


def debianize_name(name):
    """make name acceptable as a Debian (binary) package name"""
    name = name.replace('_', '-')
    name = name.lower()
    return name


def _extract_prefix(filename):
    """
	>>> _extract_prefix("some_long_filename_without_hyphen.jpg")
	>>> _extract_prefix("-first_char_is_hyphen.jpg")
	>>> _extract_prefix("some_long_filename_with-stuff.jpg") # doctest: +ALLOW_UNICODE
	'some_long_filename_with'
	"""
    pos = filename.rfind('-')
    if not pos or pos < 0:
        return None
    return filename[:pos]


def sort_by_numGlyphs_and_PostScriptName1(fontlist):
    """
	Returns a new list that is first sorted by the font's numGlyphs,
	and secondly by the font's PostScriptName1.
	"""
    return sorted(fontlist, key=lambda font: (font.numGlyphs, font.
        PostScriptName1))


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

    @param argv list of commandline parameters (list of strings)
    @return reference to the main widget (QWidget)
    """
    from Tools.TRPreviewer import TRPreviewer
    if len(argv) > 1:
        files = argv[1:]
    else:
        files = []
    previewer = TRPreviewer(files, None, 'TRPreviewer')
    return previewer


def split_encoded(data, encoding, max_split=None):
    """Split ID3v2 frame data according to encoding."""
    remainder = data
    values = []
    num_split = 0
    while True:
        try:
            if encoding in ['iso-8859-1', 'utf-8']:
                head, tail = remainder.split(b'\x00', 1)
            else:
                if len(remainder) % 2 != 0:
                    remainder += b'\x00'
                head, tail = remainder.split(b'\x00\x00', 1)
                if len(head) % 2 != 0:
                    head, tail = remainder.split(b'\x00\x00\x00', 1)
                    head += b'\x00'
        except ValueError:
            if remainder:
                values.append(remainder)
            break
        else:
            values.append(head)
            remainder = tail
            num_split += 1
            if max_split and num_split >= max_split:
                values.append(tail)
                break
    return values


def divide(n, iterable):
    """Divide the elements from *iterable* into *n* parts, maintaining
    order.

        >>> group_1, group_2 = divide(2, [1, 2, 3, 4, 5, 6])
        >>> list(group_1)
        [1, 2, 3]
        >>> list(group_2)
        [4, 5, 6]

    If the length of *iterable* is not evenly divisible by *n*, then the
    length of the returned iterables will not be identical:

        >>> children = divide(3, [1, 2, 3, 4, 5, 6, 7])
        >>> [list(c) for c in children]
        [[1, 2, 3], [4, 5], [6, 7]]

    If the length of the iterable is smaller than n, then the last returned
    iterables will be empty:

        >>> children = divide(5, [1, 2, 3])
        >>> [list(c) for c in children]
        [[1], [2], [3], [], []]

    This function will exhaust the iterable before returning and may require
    significant storage. If order is not important, see :func:`distribute`,
    which does not first pull the iterable into memory.

    """
    if n < 1:
        raise ValueError('n must be at least 1')
    seq = tuple(iterable)
    q, r = divmod(len(seq), n)
    ret = []
    for i in range(n):
        start = i * q + (i if i < r else r)
        stop = (i + 1) * q + (i + 1 if i + 1 < r else r)
        ret.append(iter(seq[start:stop]))
    return ret


def break_iterable(iterable, pred):
    """Break a iterable on the item that matches the predicate into lists.

    The item that matched the predicate is not included in the result.

    >>> list(break_iterable([1, 2, 3, 4], lambda x: x == 3))
    [[1, 2], [4]]
    """
    sublist = []
    for i in iterable:
        if pred(i):
            yield sublist
            sublist = []
        else:
            sublist.append(i)
    yield sublist


@staticmethod
def prompt_user(message):
    """
        Get command line input from the user
        :param message: str: message to show user
        :return: str: value user entered
        """
    return input(message)


def _regexp_has_newline(r):
    """Expressions that may indicate newlines in a regexp:
        - newlines (
)
        - escaped newline (\\n)
        - anything but ([^...])
        - any-char (.) when the flag (?s) exists
    """
    return '\n' in r or '\\n' in r or '[^' in r or '(?s' in r and '.' in r


@staticmethod
def timeSlice(slices):
    """
        Carry out forward modelling and return time slices.
        """
    raise NotImplementedError


def psi_Mg_Na_Cl_PK74(T, P):
    """c-c'-a: magnesium sodium chloride [PK74]."""
    psi = 0.0
    valid = T == 298.15
    return psi, valid


def p_comp_operator(p):
    """comp_operator : restricted_comp_operator
                     | IN
                     | NOT IN """
    if len(p) == 3:
        p[0] = 'not in'
    else:
        p[0] = p[1]


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 _get_super_id(line: str, uline: str) ->int:
    """
    parses the superelement header::

        BEGIN SUPER=2
        BEGIN BULK SUPER=2
        BEGIN BULK SUPER = 2
        BEGIN BULK SUPER 2

    """
    if '=' in uline:
        sline = uline.split('=')
        super_id_str = sline[1]
        if len(sline) != 2:
            msg = 'expected "BEGIN SUPER=1"\nline = %s' % line
            raise SyntaxError(msg)
    else:
        sline = uline.split()
        if len(sline) not in [3, 4]:
            msg = 'expected "BEGIN SUPER=1"\nline = %s' % line
            raise SyntaxError(msg)
        if len(sline) == 3:
            super_id_str = sline[2]
        elif len(sline) == 4:
            super_id_str = sline[3]
    try:
        super_id = int(super_id_str)
    except (IndexError, ValueError):
        msg = 'expected "BEGIN SUPER=1"\nline = %s' % line
        raise SyntaxError(msg)
    if super_id < 0:
        raise SyntaxError('super_id=%i must be greater than 0; line=%s' % (
            super_id, line))
    return super_id


def __new__(mcs, name, bases, namespace, **kwargs):
    """Create new class object instance and alter its namespace."""
    namespace[mcs._params_storage_key] = mcs._get_params(bases, namespace)
    return super().__new__(mcs, name, bases, dict(namespace))


def getDocumentComparisons(max=10, filterComment=0):
    """Get history as unified diff
        """


def describe_flow_logs(FlowLogIds=None, Filters=None, NextToken=None,
    MaxResults=None):
    """
    Describes one or more flow logs. To view the information in your flow logs (the log streams for the network interfaces), you must use the CloudWatch Logs console or the CloudWatch Logs API.
    See also: AWS API Documentation

    :example: response = client.describe_flow_logs(
        FlowLogIds=[
            'string',
        ],
        Filters=[
            {
                'Name': 'string',
                'Values': [
                    'string',
                ]
            },
        ],
        NextToken='string',
        MaxResults=123
    )

    :type FlowLogIds: list
    :param FlowLogIds: One or more flow log IDs.
            (string) --

    :type Filters: list
    :param Filters: One or more filters.
            deliver-log-status - The status of the logs delivery (SUCCESS | FAILED ).
            flow-log-id - The ID of the flow log.
            log-group-name - The name of the log group.
            resource-id - The ID of the VPC, subnet, or network interface.
            traffic-type - The type of traffic (ACCEPT | REJECT | ALL )
            (dict) --A filter name and value pair that is used to return a more specific list of results. Filters can be used to match a set of resources by various criteria, such as tags, attributes, or IDs.
            Name (string) --The name of the filter. Filter names are case-sensitive.
            Values (list) --One or more filter values. Filter values are case-sensitive.
            (string) --

    :type NextToken: string
    :param NextToken: The token to retrieve the next page of results.

    :type MaxResults: integer
    :param MaxResults: The maximum number of results to return for the request in a single page. The remaining results can be seen by sending another request with the returned NextToken value. This value can be between 5 and 1000; if MaxResults is given a value larger than 1000, only 1000 results are returned. You cannot specify this parameter and the flow log IDs parameter in the same request.

    :rtype: dict
    :return: {
        'FlowLogs': [
            {
                'CreationTime': datetime(2015, 1, 1),
                'FlowLogId': 'string',
                'FlowLogStatus': 'string',
                'ResourceId': 'string',
                'TrafficType': 'ACCEPT'|'REJECT'|'ALL',
                'LogGroupName': 'string',
                'DeliverLogsStatus': 'string',
                'DeliverLogsErrorMessage': 'string',
                'DeliverLogsPermissionArn': 'string'
            },
        ],
        'NextToken': 'string'
    }

    """
    pass


def is_namedtuple(obj):
    """
    >>> p0 = collections.namedtuple("Point", "x y")(1, 2)
    >>> is_namedtuple(p0)
    True
    >>> is_namedtuple(tuple(p0))
    False
    """
    return isinstance(obj, tuple) and hasattr(obj, '_asdict')


@classmethod
def new(cls):
    """Create a new promise.

        Returns a tuple containing the activated promise and the function to
        fulfill it.

        Available at the module level as new() for convenience.

        """
    p = cls()
    f = p.activate()
    return p, f


def primitive_nurbs_surface_circle_add(radius: float=1.0, view_align: bool=
    False, enter_editmode: bool=False, location: float=(0.0, 0.0, 0.0),
    rotation: float=(0.0, 0.0, 0.0), layers: bool=(False, False, False,
    False, False, False, False, False, False, False, False, False, False,
    False, False, False, False, False, False, False)):
    """Construct a Nurbs surface Circle

    :param radius: Radius
    :type radius: float
    :param view_align: Align to View, Align the new object to the view
    :type view_align: bool
    :param enter_editmode: Enter Editmode, Enter editmode when adding this object
    :type enter_editmode: bool
    :param location: Location, Location for the newly added object
    :type location: float
    :param rotation: Rotation, Rotation for the newly added object
    :type rotation: float
    :param layers: Layer
    :type layers: bool
    """
    pass


def b_func(*, X, v_r):
    """
    Compute the value of the variable b
    """
    return -X * v_r / 2


def get_node_name_fout(name, fout, i, pc, hpc='slurm'):
    """Make a node name and fout unique to the run name, year, and node number.

    Parameters
    ----------
    name : str
        Base node/job name
    fout : str
        Base file output name (no path) (with or without .h5 extension)
    i : int | None
        Node number. If None, only a single node is being used and no
        enumeration is necessary.
    pc : reV.config.PointsControl
        A PointsControl instance that i is enumerated from.
    hpc : str
        HPC job submission tool name (e.g. slurm or pbs). Affects job name.

    Returns
    -------
    node_name : str
        Base node name with _00 tag. 16 char max.
    fout_node : str
        Base file output name with _node00 tag.
    """
    if name.endswith('.h5'):
        name = name.replace('.h5', '')
    if not fout.endswith('.h5'):
        fout += '.h5'
    if i is None or len(pc) == 1:
        fout_node = fout
        node_name = fout
    else:
        if hpc == 'slurm':
            node_name = '{0}_{1:02d}'.format(name, i)
        elif hpc == 'pbs':
            node_name = '{0}_{1:02d}'.format(name[:13], i)
        fout_node = fout.replace('.h5', '_node{0:02d}.h5'.format(i))
    if node_name.endswith('.h5'):
        node_name = node_name.replace('.h5', '')
    return node_name, fout_node


def status(s):
    """Prints things in bold."""
    print('\x1b[1m{0}\x1b[0m'.format(s))


def dictizeMeta(m):
    """
    Convert the plain metadata into a dictionary.

    Parameters
    ----------
    m : list
        A list of lines with colon-separated metadata.
    Returns
    -------
    meta : dict
        The dictionary-fied metadata.
    """
    meta = []
    for i in m:
        s = i.split(': ', 1)
        d = {s[0]: s[1]}
        meta.append(d)
    result = {}
    for d in meta:
        result.update(d)
    meta = result
    return meta


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

        :param TeamFolderCreateType val:
        :rtype: EventType
        """
    return cls('team_folder_create', val)


def clean_graph(graph):
    """
    Check the missing attributes of every node, and add a "No" when it is not
    present. With this you can, for example, use the attribute for graph
    partitioning in Gephi
    """
    for i in graph.nodes():
        graph.node[i]['Label'] = str(i)
        if 'owner' not in graph.node[i]:
            graph.node[i]['owner'] = 'No'
        if 'committer' not in graph.node[i]:
            graph.node[i]['committer'] = 'No'
        if 'forker' not in graph.node[i]:
            graph.node[i]['forker'] = 'No'
        if 'stargazer' not in graph.node[i]:
            graph.node[i]['stargazer'] = 'No'
        if 'contributor' not in graph.node[i]:
            graph.node[i]['contributor'] = 'No'
        if 'collaborator' not in graph.node[i]:
            graph.node[i]['collaborator'] = 'No'
        if 'watcher' not in graph.node[i]:
            graph.node[i]['watcher'] = 'No'
        if 'subscriber' not in graph.node[i]:
            graph.node[i]['subscriber'] = 'No'
        if 'issue creator' not in graph.node[i]:
            graph.node[i]['issue creator'] = 'No'
        if 'issue commenter' not in graph.node[i]:
            graph.node[i]['issue commenter'] = 'No'
        if 'pull request assignee' not in graph.node[i]:
            graph.node[i]['pull request assignee'] = 'No'
        if 'issue assignee' not in graph.node[i]:
            graph.node[i]['issue assignee'] = 'No'
        if 'email' not in graph.node[i]:
            graph.node[i]['email'] = 'None'
        if 'avatar_url' not in graph.node[i]:
            graph.node[i]['avatar_url'] = 'None'
    for v in graph.nodes_iter(data=True):
        for attrib in v[1]:
            if v[1][attrib] is None:
                graph.node[v[0]][attrib] = 'None'
        if v[0] == 'None' or v[0] is None:
            graph.remove_node(v[0])
    return graph


def get_cityid_trackpoint_pairs(cursor, unknown_only):
    """
    Get a list of trackpoint ids and the location id of that
    trackpoint from the citydefs table
    """
    sql = (
        'SELECT citydefs.citydef_uid, trackpoints.trkpt_uid FROM citydefs, trackpoints WHERE within(trackpoints.geom, citydefs.geom)'
        )
    if unknown_only is True:
        sql += ' AND trackpoints.citydef_uid = 1'
    results = cursor.execute(sql)
    locations_list = results.fetchall()
    return locations_list


def __new__(cls, *args, **kwargs):
    """BaseVector cannot be created"""
    raise NotImplementedError('Please specify Vector2 or Vector3')


def smash():
    """flatten deeply nested incoming things"""


def __prepare_request_arguments(**options):
    """Return a dict representing default request arguments."""
    options = options.copy()
    headers = {'Content-Type': 'application/json', 'Accept':
        'application/json', 'Accept-Encoding': 'deflate'}
    params = options.pop('params') if 'params' in options else ''
    timeout = options.pop('timeout') if 'timeout' in options else 5
    if 'headers' in options:
        headers.update(options.pop('headers'))
    request_arguments = {'headers': headers, 'params': params, 'timeout':
        timeout}
    request_arguments.update(options)
    return request_arguments


def x_y_by_col_lbl_inplace(df, y_col_lbl):
    """Breaks the given dataframe into  an X frame and a y series by the given
    column name.

    The original frame is returned, without the y series column, as the X
    frame, so no new dataframes are created.

    Parameters
    ----------
    df : pandas.DataFrame
        The dataframe to split.
    y_col_lbl : object
        The label of the y column.

    Returns
    -------
    X, y : pandas.DataFrame, pandas.Series
        A dataframe made up of all columns but the column with the given name
        and a series made up of the same column, respectively.

    Example
    -------
    >>> import pandas as pd
    >>> data = [[23, 'Jo', 4], [19, 'Mi', 3]]
    >>> df = pd.DataFrame(data, [1, 2] , ['Age', 'Name', 'D'])
    >>> X, y = x_y_by_col_lbl(df, 'D')
    >>> X
       Age Name
    1   23   Jo
    2   19   Mi
    >>> y
    1    4
    2    3
    Name: D, dtype: int64
    """
    y = df[y_col_lbl]
    df.drop(labels=y_col_lbl, axis=1, inplace=True)
    return df, y


def validate_url(url):
    """Checks if URL is valid
    :param url: URL
    :return: True if URL is valid, otherwise false
    """
    try:
        from urlparse import urlparse
    except:
        from urllib.parse import urlparse
    try:
        result = urlparse(url)
        return result.scheme
    except:
        return False


def logical_and(image1, image2):
    """Logical AND between two images. At least one of the images must have
    mode "1".

    .. code-block:: python

        out = ((image1 and image2) % MAX)

    :rtype: :py:class:`~PIL.Image.Image`
    """
    image1.load()
    image2.load()
    return image1._new(image1.im.chop_and(image2.im))


@classmethod
def get_backend(cls):
    """Get protected member"""
    return cls._backend


def get_effective_theme(rattail_config, theme=None, session=None):
    """
    Validates and returns the "effective" theme.  If you provide a theme, that
    will be used; otherwise it is read from database setting.
    """
    from rattail.db import api
    if not theme:
        theme = api.get_setting(session, 'tailbone.theme') or 'default'
    available = rattail_config.getlist('tailbone', 'themes', default=['bobcat']
        )
    available.append('default')
    if theme not in available:
        raise ValueError('theme not available: {}'.format(theme))
    return theme