@staticmethod
def encode_large_value(value):
    """
        Inverse function of :py:meth:`~.ObjectIdentifier.decode_large_value`
        """
    if value <= 127:
        return [value]
    output = [value & 127]
    value = value >> 7
    while value:
        output.append(value & 127 | 128)
        value = value >> 7
    output.reverse()
    return output


@classmethod
def _get_default_options(cls, options='default'):
    """ Default options structure for Collocation. """
    if options == 'default':
        return [1, 10]
    elif options == 'quiet':
        return [0, 10]


def section(iterator, end, firstline=None):
    """
    Generates lines from the iterator until `end` is matched or iterator stops

    :param:

     - `iterator`: An iterator of lines
     - `end`: A regular expression to match the last line in the section

    :yield: lines up to and including the end match
    """
    ended = False
    if firstline is not None:
        yield firstline
    while not ended:
        try:
            line = iterator.next()
            if end.search(line):
                ended = True
            yield line
        except StopIteration:
            return


def promote_read_replica_db_cluster(DBClusterIdentifier=None):
    """
    Promotes a Read Replica DB cluster to a standalone DB cluster.
    See also: AWS API Documentation

    :example: response = client.promote_read_replica_db_cluster(
        DBClusterIdentifier='string'
    )

    :type DBClusterIdentifier: string
    :param DBClusterIdentifier: [REQUIRED]
            The identifier of the DB cluster Read Replica to promote. This parameter is not case-sensitive.
            Constraints:
            Must contain from 1 to 63 alphanumeric characters or hyphens.
            First character must be a letter.
            Cannot end with a hyphen or contain two consecutive hyphens.
            Example: my-cluster-replica1

    :rtype: dict
    :return: {
        'DBCluster': {
            'AllocatedStorage': 123,
            'AvailabilityZones': [
                'string',
            ],
            'BackupRetentionPeriod': 123,
            'CharacterSetName': 'string',
            'DatabaseName': 'string',
            'DBClusterIdentifier': 'string',
            'DBClusterParameterGroup': 'string',
            'DBSubnetGroup': 'string',
            'Status': 'string',
            'PercentProgress': 'string',
            'EarliestRestorableTime': datetime(2015, 1, 1),
            'Endpoint': 'string',
            'ReaderEndpoint': 'string',
            'MultiAZ': True|False,
            'Engine': 'string',
            'EngineVersion': 'string',
            'LatestRestorableTime': datetime(2015, 1, 1),
            'Port': 123,
            'MasterUsername': 'string',
            'DBClusterOptionGroupMemberships': [
                {
                    'DBClusterOptionGroupName': 'string',
                    'Status': 'string'
                },
            ],
            'PreferredBackupWindow': 'string',
            'PreferredMaintenanceWindow': 'string',
            'ReplicationSourceIdentifier': 'string',
            'ReadReplicaIdentifiers': [
                'string',
            ],
            'DBClusterMembers': [
                {
                    'DBInstanceIdentifier': 'string',
                    'IsClusterWriter': True|False,
                    'DBClusterParameterGroupStatus': 'string',
                    'PromotionTier': 123
                },
            ],
            'VpcSecurityGroups': [
                {
                    'VpcSecurityGroupId': 'string',
                    'Status': 'string'
                },
            ],
            'HostedZoneId': 'string',
            'StorageEncrypted': True|False,
            'KmsKeyId': 'string',
            'DbClusterResourceId': 'string',
            'DBClusterArn': 'string',
            'AssociatedRoles': [
                {
                    'RoleArn': 'string',
                    'Status': 'string'
                },
            ],
            'IAMDatabaseAuthenticationEnabled': True|False,
            'ClusterCreateTime': datetime(2015, 1, 1)
        }
    }

    :returns:
    CreateDBCluster
    DeleteDBCluster
    FailoverDBCluster
    ModifyDBCluster
    RestoreDBClusterFromSnapshot
    RestoreDBClusterToPointInTime

    """
    pass


def get_appropriated_part_size(file_size):
    """
    Gets the appropriated part size when uploading or downloading files,
    given an initial file size.
    """
    if file_size <= 104857600:
        return 128
    if file_size <= 786432000:
        return 256
    if file_size <= 1572864000:
        return 512
    raise ValueError('File size too large')


def _py_interpreter_range(py_version):
    """
    Yield Python versions in descending order.

    After the latest version, the major-only version will be yielded, and then
    all following versions up to 'end'.
    """
    yield 'py{major}{minor}'.format(major=py_version[0], minor=py_version[1])
    yield 'py{major}'.format(major=py_version[0])
    for minor in range(py_version[1] - 1, -1, -1):
        yield 'py{major}{minor}'.format(major=py_version[0], minor=minor)


def pad_rectangle(rect, dx, dy):
    """
    Increase width of the rectangle by dx, and height by dy.
    """
    x, y, w, h = rect
    w_new = int(w + 2 * dx)
    h_new = int(h + 2 * dy)
    x_new = max(0, int(x - dx))
    y_new = max(0, int(y - dy))
    return x_new, y_new, w_new, h_new


@staticmethod
def _select_row_by_column_value(tree_view, list_store, column, value):
    """Helper method to select a tree view row

        :param Gtk.TreeView tree_view: Tree view who's row is to be selected
        :param Gtk.ListStore list_store: List store of the tree view
        :param int column: Column in which the value is searched
        :param value: Value to search for
        :returns: Row of list store that has selected
        :rtype: int
        """
    for row_num, iter_elem in enumerate(list_store):
        if iter_elem[column] == value:
            tree_view.set_cursor(row_num)
            return row_num


def is_status(byte):
    """Return True if the given byte is a MIDI status byte, False otherwise."""
    return byte & 128 == 128


@classmethod
def enable(cls):
    """Enables DOM snapshot agent for the given page.
        """
    return cls.build_send_payload('enable', {}), None


def nl2br(s):
    """Related to string operation

    >>> nl2br('abc
xyz')
    'abc
xyz'
    """
    return '
'.join(s.split('\n'))


def sort(_list):
    """
    Insertion sort algorithm

    :param _list: list or values to sort
    :return: sort values
    """
    for i in range(1, len(_list)):
        current_number = _list[i]
        for j in range(i - 1, -1, -1):
            if _list[j] > current_number:
                _list[j], _list[j + 1] = _list[j + 1], _list[j]
            else:
                _list[j + 1] = current_number
                break
    return _list


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 request_subscription(content, email):
    """Request a subscription to the given content by the given
        email.
        """


def manage_exportObject(id='', download=None, RESPONSE=None, REQUEST=None):
    """Exports an object to a file and returns that file."""


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

        :param TeamMergeToDetails val:
        :rtype: EventDetails
        """
    return cls('team_merge_to_details', val)


@staticmethod
def supportedViews():
    """Overrides :meth:`.ControlMixin.supportedViews`. The
        ``OverlayDisplayPanel`` is only intended to be added to
        :class:`.OrthoPanel`, :class:`.LightBoxPanel`, or
        :class:`.Scene3DPanel` views.
        """
    from fsleyes.views.orthopanel import OrthoPanel
    from fsleyes.views.lightboxpanel import LightBoxPanel
    from fsleyes.views.scene3dpanel import Scene3DPanel
    return [OrthoPanel, LightBoxPanel, Scene3DPanel]


def time_human(x):
    """ Gets time as human readable """
    x = round(x, 2)
    for number, unit in [(60, 's'), (60, 'min'), (24, 'h'), (365, 'days')]:
        if abs(x) < number:
            return f'{x:.2f} {unit}'
        x /= number
    return f'{x:.2f} years'


def nextpow2(i: int) ->int:
    """returns the first P such that 2**P >= abs(N)"""
    return i.bit_length()


def getNodes():
    """ Returns list of all nodes.

        @return: a deferred that returns a C{list} of node ids.
        """


def use(app=None, gl=None):
    """ Set the usage options for vispy

    Specify what app backend and GL backend to use.

    Parameters
    ----------
    app : str
        The app backend to use (case insensitive). Standard backends:
            * 'PyQt4': use Qt widget toolkit via PyQt4.
            * 'PyQt5': use Qt widget toolkit via PyQt5.
            * 'PySide': use Qt widget toolkit via PySide.
            * 'PyGlet': use Pyglet backend.
            * 'Glfw': use Glfw backend (successor of Glut). Widely available
              on Linux.
            * 'SDL2': use SDL v2 backend.
            * 'osmesa': Use OSMesa backend
        Additional backends:
            * 'ipynb_vnc': render in the IPython notebook via a VNC approach
              (experimental)
    gl : str
        The gl backend to use (case insensitive). Options are:
            * 'gl2': use Vispy's desktop OpenGL API.
            * 'pyopengl2': use PyOpenGL's desktop OpenGL API. Mostly for
              testing.
            * 'es2': (TO COME) use real OpenGL ES 2.0 on Windows via Angle.
              Availability of ES 2.0 is larger for Windows, since it relies
              on DirectX.
            * 'gl+': use the full OpenGL functionality available on
              your system (via PyOpenGL).

    Notes
    -----
    If the app option is given, ``vispy.app.use_app()`` is called. If
    the gl option is given, ``vispy.gloo.use_gl()`` is called.

    If an app backend name is provided, and that backend could not be
    loaded, an error is raised.

    If no backend name is provided, Vispy will first check if the GUI
    toolkit corresponding to each backend is already imported, and try
    that backend first. If this is unsuccessful, it will try the
    'default_backend' provided in the vispy config. If still not
    succesful, it will try each backend in a predetermined order.

    See Also
    --------
    vispy.app.use_app
    vispy.gloo.gl.use_gl
    """
    if app is None and gl is None:
        raise TypeError('Must specify at least one of "app" or "gl".')
    if app == 'ipynb_webgl':
        app = 'headless'
        gl = 'webgl'
    if app == 'osmesa':
        from ..util.osmesa_gl import fix_osmesa_gl_lib
        fix_osmesa_gl_lib()
        if gl is not None:
            raise ValueError('Do not specify gl when using osmesa')
    if gl:
        from .. import gloo, config
        config['gl_backend'] = gl
        gloo.gl.use_gl(gl)
    if app:
        from ..app import use_app
        use_app(app)


def fix_multi_T1w_source_name(in_files):
    """
    Make up a generic source name when there are multiple T1s

    >>> fix_multi_T1w_source_name([
    ...     '/path/to/sub-045_ses-test_T1w.nii.gz',
    ...     '/path/to/sub-045_ses-retest_T1w.nii.gz'])
    '/path/to/sub-045_T1w.nii.gz'

    """
    import os
    from nipype.utils.filemanip import filename_to_list
    base, in_file = os.path.split(filename_to_list(in_files)[0])
    subject_label = in_file.split('_', 1)[0].split('-')[1]
    return os.path.join(base, 'sub-%s_T1w.nii.gz' % subject_label)


def get_device_info(bigip):
    """Get device information for the current device being queried

    :param bigip: ManagementRoot object --- device to query
    :returns: ManagementRoot object
    """
    coll = bigip.tm.cm.devices.get_collection()
    device = [device for device in coll if device.selfDevice == 'true']
    return device[0]


def announce(zelf, txt):
    """ announce txt on all fleet bots. """
    from midz import fleet
    for bot in fleet.bots:
        bot.announce(txt)


@staticmethod
def is_match(item, expressions):
    """Check if item matches expressions.

        :param item: Item
        :type item: byte.model.Model

        :param expressions: Expressions
        :type expressions: list of byte.base.BaseExpression
        """
    for expression in expressions:
        if not expression.execute(item):
            return False
    return True


def describe_reserved_cache_nodes_offerings(ReservedCacheNodesOfferingId=
    None, CacheNodeType=None, Duration=None, ProductDescription=None,
    OfferingType=None, MaxRecords=None, Marker=None):
    """
    Lists available reserved cache node offerings.
    See also: AWS API Documentation

    :example: response = client.describe_reserved_cache_nodes_offerings(
        ReservedCacheNodesOfferingId='string',
        CacheNodeType='string',
        Duration='string',
        ProductDescription='string',
        OfferingType='string',
        MaxRecords=123,
        Marker='string'
    )

    :type ReservedCacheNodesOfferingId: string
    :param ReservedCacheNodesOfferingId: The offering identifier filter value. Use this parameter to show only the available offering that matches the specified reservation identifier.
            Example: 438012d3-4052-4cc7-b2e3-8d3372e0e706

    :type CacheNodeType: string
    :param CacheNodeType: The cache node type filter value. Use this parameter to show only the available offerings matching the specified cache node type.
            Valid node types are as follows:
            General purpose:
            Current generation: cache.t2.micro , cache.t2.small , cache.t2.medium , cache.m3.medium , cache.m3.large , cache.m3.xlarge , cache.m3.2xlarge , cache.m4.large , cache.m4.xlarge , cache.m4.2xlarge , cache.m4.4xlarge , cache.m4.10xlarge
            Previous generation: cache.t1.micro , cache.m1.small , cache.m1.medium , cache.m1.large , cache.m1.xlarge
            Compute optimized: cache.c1.xlarge
            Memory optimized:
            Current generation: cache.r3.large , cache.r3.xlarge , cache.r3.2xlarge , cache.r3.4xlarge , cache.r3.8xlarge
            Previous generation: cache.m2.xlarge , cache.m2.2xlarge , cache.m2.4xlarge

            Notes:
            All T2 instances are created in an Amazon Virtual Private Cloud (Amazon VPC).
            Redis backup/restore is not supported for Redis (cluster mode disabled) T1 and T2 instances. Backup/restore is supported on Redis (cluster mode enabled) T2 instances.
            Redis Append-only files (AOF) functionality is not supported for T1 or T2 instances.
            For a complete listing of node types and specifications, see Amazon ElastiCache Product Features and Details and either Cache Node Type-Specific Parameters for Memcached or Cache Node Type-Specific Parameters for Redis .

    :type Duration: string
    :param Duration: Duration filter value, specified in years or seconds. Use this parameter to show only reservations for a given duration.
            Valid Values: 1 | 3 | 31536000 | 94608000

    :type ProductDescription: string
    :param ProductDescription: The product description filter value. Use this parameter to show only the available offerings matching the specified product description.

    :type OfferingType: string
    :param OfferingType: The offering type filter value. Use this parameter to show only the available offerings matching the specified offering type.
            Valid Values: 'Light Utilization'|'Medium Utilization'|'Heavy Utilization'

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

    :type Marker: string
    :param Marker: An optional marker returned from a prior request. Use this marker for pagination of results from this operation. If this parameter is specified, the response includes only records beyond the marker, up to the value specified by MaxRecords .

    :rtype: dict
    :return: {
        'Marker': 'string',
        'ReservedCacheNodesOfferings': [
            {
                'ReservedCacheNodesOfferingId': 'string',
                'CacheNodeType': 'string',
                'Duration': 123,
                'FixedPrice': 123.0,
                'UsagePrice': 123.0,
                'ProductDescription': 'string',
                'OfferingType': 'string',
                'RecurringCharges': [
                    {
                        'RecurringChargeAmount': 123.0,
                        'RecurringChargeFrequency': 'string'
                    },
                ]
            },
        ]
    }

    :returns:
    General purpose:
    Current generation: cache.t2.micro , cache.t2.small , cache.t2.medium , cache.m3.medium , cache.m3.large , cache.m3.xlarge , cache.m3.2xlarge , cache.m4.large , cache.m4.xlarge , cache.m4.2xlarge , cache.m4.4xlarge , cache.m4.10xlarge
    Previous generation: cache.t1.micro , cache.m1.small , cache.m1.medium , cache.m1.large , cache.m1.xlarge

    Compute optimized: cache.c1.xlarge
    Memory optimized:
    Current generation: cache.r3.large , cache.r3.xlarge , cache.r3.2xlarge , cache.r3.4xlarge , cache.r3.8xlarge
    Previous generation: cache.m2.xlarge , cache.m2.2xlarge , cache.m2.4xlarge

    """
    pass


@classmethod
def from_wire(cls, header, payload_bytes, *, sender_address=None, validate=
    False):
    """
        Use header.dbr_type to pack payload bytes into the right strucutre.

        Some Command types allocate a different meaning to the header.dbr_type
        field, and these override this method in their subclass.
        """
    return cls.from_components(header, b'', payload_bytes, sender_address=
        sender_address, validate=validate)


def ensure_subset_of(collection, superset):
    """Raise ValueError if collection is no subset of superset

    Only distinct elements are considered. For mappings, only the keys are
    considered.

    Args:
        collection: An iterable container.

        superset: A set of allowed elements.

    Raises:
        ValueError: If *collection* contains more than one (distinct) element
            of *elements*.

    """
    excess = set(collection) - set(superset)
    if excess:
        raise ValueError('Excess element(s): {!r}'.format(excess))


def describe_spot_datafeed_subscription(DryRun=None):
    """
    Describes the data feed for Spot instances. For more information, see Spot Instance Data Feed in the Amazon Elastic Compute Cloud User Guide .
    See also: AWS API Documentation

    Examples
    This example describes the Spot Instance datafeed subscription for your AWS account.
    Expected Output:

    :example: response = client.describe_spot_datafeed_subscription(
        DryRun=True|False
    )

    :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 .

    :rtype: dict
    :return: {
        'SpotDatafeedSubscription': {
            'OwnerId': 'string',
            'Bucket': 'string',
            'Prefix': 'string',
            'State': 'Active'|'Inactive',
            'Fault': {
                'Code': 'string',
                'Message': 'string'
            }
        }
    }

    """
    pass


@staticmethod
def auth_header(token, basic_auth):
    """
        Create an auth header that optionally includes a bearer token or basic auth.

        Args:
            auth (str): Bearer token or Basic auth to use in header

        Returns:
            dictionary: containing Authorization headers or {} if Authorizationis is None.

        """
    if token is not None:
        return {'Authorization': 'Bearer {token}'.format(token=token)}
    elif basic_auth is not None:
        return {'Authorization': basic_auth}
    return {}


def data(package):
    """ Return the PackageData for the given package."""
    return package.__rdata__


def back(length):
    """
    Returns the command string to move the
    cursor back by <length> places
    """
    return '\x08' * length


@classmethod
def signed_from_df(cls, df, sign_dict=None, flattening_method=None,
    weight_mapping=None):
    """Create a signed graph from a pandas DataFrame."""
    net = cls.from_df(df)
    return net.to_signed_graph(sign_dict=sign_dict, flattening_method=
        flattening_method, weight_mapping=weight_mapping)


@staticmethod
def change_contact_modattr(contact, value):
    """Change contact modified attribute value
        Format of the line that triggers function call::

        CHANGE_CONTACT_MODATTR;<contact_name>;<value>

        :param contact: contact to edit
        :type contact: alignak.objects.contact.Contact
        :param value: new value to set
        :type value: str
        :return: None
        """
    contact.modified_attributes = int(value)


def join_patterns(pattern1, pattern2):
    """
    Joins URL patterns
    """
    if pattern1.endswith('$'):
        return pattern1
    try:
        if pattern2.startswith('^'):
            return pattern1 + pattern2[1:]
        if pattern2:
            return pattern1 + '.' + pattern2
    except AttributeError:
        if str(pattern2).startswith('^'):
            return pattern1 + str(pattern2)[1:]
        if pattern2:
            return pattern1 + '.' + str(pattern2)
    return pattern1


def get_bank_name(account_number):
    """
    Returns the bank name based on the account number
    @param account_number: a Finnish bank account number (BBAN).
    @return: Bank name or 'Tuntematon'.
    """
    banks = {'1': u'Nordea', '2': u'Nordea', '31': u'Handelsbanken', '33':
        u'SEB', '34': u'Danske Bank', '36': u'Tapiola', '37': u'DnB NOR',
        '38': u'Swedbank', '39': u'S-Pankki', '4': u'Säästöpankki', '47':
        u'Pop', '5': u'Osuuspankki', '6': u'Ålandsbanken', '8': u'Sampo'}
    if account_number == '500001':
        return 'OKO pankki'
    elif account_number[0:4] in ('4055', '4050', '4970'):
        return 'Aktia'
    elif account_number[0:2] in banks:
        return banks[account_number[0:2]]
    elif account_number[0] in banks:
        return banks[account_number[0]]
    else:
        return u'Tuntematon'


def _strip_prefix(cmd_line):
    """Strip an OS operating prefix from a command line.
    """
    if cmd_line.startswith('cmd.exe /c '):
        return cmd_line[11:].strip('"')
    if cmd_line.startswith('cmd /c '):
        return cmd_line[7:].strip('"')
    if cmd_line.startswith('/bin/bash -c '):
        return cmd_line[13:]
    if cmd_line.startswith('/bin/sh -c '):
        return cmd_line[11:]
    return cmd_line


def clean_output_text(_text):
    """clean_output_text: Clean msgstr's text after translates

    :_text: list of msgid's text
    :returns: clean text, with 'msgstr "' and double quotes
    """
    _temp = ''
    _templist = _text.splitlines()
    _templistlen = len(_templist) - 1
    for i, l in enumerate(_templist):
        _temptext = l.rstrip()
        _temptext = _temptext.replace('\\', '\\\\').replace('\t', '\\t'
            ).replace('\r', '\\r').replace('\n', '\\n').replace('"', '\\"')
        if i == 0 and i == _templistlen:
            _temp += 'msgstr "' + _temptext + '"\n'
        elif i == 0 and i != _templistlen and len(_temptext) > 0:
            _temp += 'msgstr "' + _temptext + ' "\n'
        elif i == 0 and i != _templistlen and len(_temptext) == 0:
            _temp += 'msgstr "' + _temptext + '"\n'
        elif i != 0 and i == _templistlen:
            _temp += '"' + _temptext + '"\n'
        else:
            _temp += '"' + _temptext + ' "\n'
    return _temp


def capture_screen():
    """
    Captures the screen to a Pillow Image object
    """
    from PIL import Image
    import mss
    with mss.mss() as sct:
        for monitor in sct.monitors:
            if monitor['left'] == 0 and monitor['top'] == 0:
                break
        sct_img = sct.grab(monitor)
    img = Image.frombytes('RGB', sct_img.size, sct_img.bgra, 'raw', 'BGRX')
    return img


@staticmethod
def _draw_graph_edge(parent, child):
    """Generates a Graphviz edge between `parent` and `child` modules."""
    import pydot
    return pydot.Edge(parent, child, dir='back')


def get_order(account, order_url):
    """
    Retrieve order data.
    """
    return account.get_request(order_url, parse_json_result=True,
        fail_on_error=True)[0]


def finishes_inv(epsilon=0):
    """Returns a function that computes whether a temporal interval has the
    same end time as another interval (+/- epsilon), and starts after it.
    This is the inverse of the ``finishes`` predicate; it checks whether the
    second interval finishes the first interval.

    The output function expects two temporal intervals (dicts with keys 't1'
    and 't2' for the start and end times, respectively). It returns ``True`` if
    the second interval ends at the same time as the first interval (+/-
    ``epsilon``), and the second interval starts after the first interval.

    Args:
        epsilon: The maximum difference between the end time of the second
            interval and the end time of the first interval.

    Returns:
        An output function that takes two temporal intervals and returns
        ``True`` if the second interval ends at the same time as the first
        interval, and starts after the first interval starts.
    """
    return lambda intrvl1, intrvl2: abs(intrvl1['t2'] - intrvl2['t2']
        ) <= epsilon and intrvl2['t1'] > intrvl1['t1']


def get_callable(path):
    """Return a callable from a given dotted path."""
    try:
        module_path, callable_name = path.rsplit('.', 1)
    except ValueError:
        raise ImportError("%s doesn't look like a callable path" % path)
    module = __import__(module_path, fromlist=[''])
    try:
        return getattr(module, callable_name)
    except AttributeError:
        raise ImportError('Could not import %s from module %s' % (
            callable_name, module_path))


def CreateDefaultGUI(appClass=None):
    """Creates a default GUI environment
	"""
    if appClass is None:
        from . import intpyapp
        appClass = intpyapp.InteractivePythonApp
    appClass().InitInstance()


def assign_property_defaults(process_data: bool=True, process_bones: bool=True
    ):
    """Assign the current values of custom properties as their defaults, for use as part of the rest pose state in NLA track mixing

    :param process_data: Process data properties
    :type process_data: bool
    :param process_bones: Process bone properties
    :type process_bones: bool
    """
    pass


def is_tuple(obj):
    """Helper method to see if the object is a Python tuple.

    >>> is_tuple((1,))
    True
    """
    return type(obj) is tuple


def Idelchik(dp, voidage, vs, rho, mu, L=1):
    """Calculates pressure drop across a packed bed of spheres as in [2]_,
    originally in [1]_.

    .. math::
        \\frac{\\Delta P}{L\\rho v_s^2} d_p  = \\frac{0.765}{\\epsilon^{4.2}}
        \\left(\\frac{30}{Re_l} + \\frac{3}{Re_l^{0.7}} + 0.3\\right)

    .. math::
        Re_l = (0.45/\\epsilon^{0.5})Re_{Erg}

    .. math::
        Re_{Erg} = \\frac{\\rho v_s  D_p}{\\mu(1-\\epsilon)}

    Parameters
    ----------
    dp : float
        Particle diameter of spheres [m]
    voidage : float
        Void fraction of bed packing [-]
    vs : float
        Superficial velocity of the fluid (volumetric flow rate/cross-sectional
        area)[m/s]
    rho : float
        Density of the fluid [kg/m^3]
    mu : float
        Viscosity of the fluid, [Pa*s]
    L : float, optional
        Length the fluid flows in the packed bed [m]

    Returns
    -------
    dP : float
        Pressure drop across the bed [Pa]

    Notes
    -----
    :math:`0.001 < Re_{Erg} <1000`
    This equation is valid for void fractions between 0.3 and 0.8. Cited as
    by Bernshtein.

    Examples
    --------
    >>> Idelchik(dp=8E-4, voidage=0.4, vs=1E-3, rho=1E3, mu=1E-3)
    1571.909125999067

    References
    ----------
    .. [1] Idelchik, I. E. Flow Resistance: A Design Guide for Engineers.
       Hemisphere Publishing Corporation, New York, 1989.
    .. [2] Allen, K. G., T. W. von Backstrom, and D. G. Kroger. "Packed Bed
       Pressure Drop Dependence on Particle Shape, Size Distribution, Packing
       Arrangement and Roughness." Powder Technology 246 (September 2013):
       590-600. doi:10.1016/j.powtec.2013.06.022.
    """
    Re = rho * vs * dp / mu / (1 - voidage)
    Re = 0.45 / voidage ** 0.5 * Re
    right = 0.765 / voidage ** 4.2 * (30.0 / Re + 3.0 / Re ** 0.7 + 0.3)
    left = dp / L / rho / vs ** 2
    return right / left


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

        :param PermanentDeleteChangePolicyType val:
        :rtype: EventType
        """
    return cls('permanent_delete_change_policy', val)


def _is_user_context(context):
    """Indicates if the request context is a normal user."""
    if not context:
        return False
    if context.is_admin:
        return False
    if not context.user_id or not context.project_id:
        return False
    return True


@classmethod
def iter_nice_to_pegasus(cls, nlist):
    """Return an iterator converting a sequence of 5-term nice coordinates
        to 4-term Pegasus coordinates.

        Note that this method does not depend on the size of the Pegasus
        lattice.
        """
    for n in nlist:
        yield cls.nice_to_pegasus(n)


def split_conflicting(mas, agents, agent, eqclass):
    """
    Split the given equivalence class for agent into non conflicting subsets.

    mas -- a multi-agents system;
    agents -- a subset of agents of mas;
    agent -- an agent of agents;
    eqclass -- a subset of moves for agents composed of states equivalent for
               agent.

    Generate all splitted non conflicting subsets.
    """
    others_cube = mas.bddEnc.inputsCube - mas.inputs_cube_for_agents({agent})
    while eqclass.isnot_false():
        si = mas.pick_one_state_inputs(eqclass)
        ncss = eqclass & si.forsome(mas.bddEnc.statesCube | others_cube)
        eqclass = eqclass - ncss
        yield ncss


def is_mnp_job(job):
    """
    Check if the given job is an MNP job.

    :param job: the job dictionary returned by AWS Batch api
    :return: true if the job is mnp, false otherwise
    """
    return 'nodeProperties' in job and 'numNodes' in job['nodeProperties']


def index_names():
    """the names of available indexes."""


def addComment(body, in_reply_to=None, renderer=None, tags=None):
    """Add a new comment"""


def sort_link(context, text, sort_field, visible_name=None):
    """Usage: {% sort_link "text" "field_name" %}
    Usage: {% sort_link "text" "field_name" "Visible name" %}
    """
    sorted_fields = False
    ascending = None
    class_attrib = 'sortable'
    orig_sort_field = sort_field
    if context.get('current_sort_field') == sort_field:
        sort_field = '-%s' % sort_field
        visible_name = '-%s' % (visible_name or orig_sort_field)
        sorted_fields = True
        ascending = False
        class_attrib += ' sorted descending'
    elif context.get('current_sort_field') == '-' + sort_field:
        visible_name = '%s' % (visible_name or orig_sort_field)
        sorted_fields = True
        ascending = True
        class_attrib += ' sorted ascending'
    if visible_name:
        if 'request' in context:
            request = context['request']
            request.session[visible_name] = sort_field
    if 'request' in context:
        url = context['request'].path
    else:
        url = './'
    url += '?sort_by='
    if visible_name is None:
        url += sort_field
    else:
        url += visible_name
    if 'getsortvars' in context:
        extra_vars = context['getsortvars']
    elif 'request' in context:
        request = context['request']
        getvars = request.GET.copy()
        if 'sort_by' in getvars:
            del getvars['sort_by']
        if len(getvars.keys()) > 0:
            context['getsortvars'] = '&%s' % getvars.urlencode()
        else:
            context['getsortvars'] = ''
        extra_vars = context['getsortvars']
    url += extra_vars
    return {'text': text, 'url': url, 'ascending': ascending,
        'sorted_fields': sorted_fields, 'class_attrib': class_attrib}


@classmethod
def _get_title(cls, string, key='TITLE'):
    """ Process the title field.

        Note there is no standard for storing metadata in here, so specialised
        extraction is risky for compatibility with other peoples datasets.
        """
    return cls._split_kvline(key, string)


def _select_confounds(confounds_file, selected_confounds):
    """Process and return selected confounds from the confounds file

    Parameters
    ----------
    confounds_file : str
        File that contains all usable confounds
    selected_confounds : list
        List containing all desired confounds.
        confounds can be listed as regular expressions (e.g., "motion_outlier.*")

    Returns
    -------
    desired_confounds : DataFrame
        contains all desired (processed) confounds.
    """
    import pandas as pd
    import numpy as np
    import re
    confounds_df = pd.read_csv(confounds_file, sep='\t', na_values='n/a')
    confound_expr = re.compile('|'.join(selected_confounds))
    expanded_confounds = list(filter(confound_expr.fullmatch, confounds_df.
        columns))
    imputables = ('framewise_displacement', 'std_dvars', 'dvars',
        '.*derivative1.*')
    impute_expr = re.compile('|'.join(imputables))
    expanded_imputables = list(filter(impute_expr.fullmatch,
        expanded_confounds))
    for imputable in expanded_imputables:
        vals = confounds_df[imputable].values
        if not np.isnan(vals[0]):
            continue
        confounds_df[imputable][0] = np.nanmean(vals[vals != 0])
    desired_confounds = confounds_df[expanded_confounds]
    if desired_confounds.isna().values.any():
        msg = 'The selected confounds contain nans: {conf}'.format(conf=
            expanded_confounds)
        raise ValueError(msg)
    return desired_confounds


@classmethod
def construct(cls, result, ipstr, *args):
    """ If we need additional parsing, do it here.
            By omission do nothing.
        """
    return cls(**result)


def update(observable, arg):
    """Called when the observed object is
        modified. You call an Observable object's
        notifyObservers method to notify all the
        object's observers of the change."""
    pass


def parse_stock_code(code: str):
    """Parses a stock code. NOTE: Only works for the Shinhan HTS"""
    if code.startswith('A'):
        return code[1:]
    elif code == '':
        return None
    else:
        return code


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


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

        :param EmmCreateUsageReportType val:
        :rtype: EventType
        """
    return cls('emm_create_usage_report', val)


def check_permissions(user, *args):
    """Check the permissions store for user and level"""
    return True


@staticmethod
def _negotiate_integer_value(client_value, server_value):
    """Negotiates two values. If either of them is 0 or None,
        returns the other one. If both are positive integers, returns the
        smallest one.

        :param int client_value: The client value
        :param int server_value: The server value
        :rtype: int

        """
    if client_value is None:
        client_value = 0
    if server_value is None:
        server_value = 0
    if client_value == 0 or server_value == 0:
        val = max(client_value, server_value)
    else:
        val = min(client_value, server_value)
    return val


def octetFromIP(ip, n):
    """Returns the nth octet (0-indexed) of the given ip string"""
    return ip.split('.')[n]


def iter_array_split(part_index, N, M):
    """
    Returns an iterator giving the indices of `part` below:
        part = np.array_split(np.arange(N), M)[part_index]

    This mimics the behavior of array_split without having to make
    the whole array that will be split.
    """
    Neach_section, extras = divmod(N, M)
    if part_index < extras:
        length = Neach_section + 1
        start = part_index * length
        end = start + length
    else:
        length = Neach_section
        start = extras * (Neach_section + 1) + (part_index - extras) * length
        end = start + length
    return range(start, end), end - start


@classmethod
def make(cls, path, data, stat):
    """Creates a new NodeData tuple.

        :returns: A :class:`~kazoo.recipe.cache.NodeData` instance.
        """
    return cls((path, data, stat))


def read_int(module, file_path):
    """Read a file and convert its value to int.

    Raise ansible failure otherwise.
    """
    try:
        with open(file_path) as f:
            file_contents = f.read()
        return int(file_contents)
    except IOError:
        module.fail_json(msg="Cannot open '%s'" % file_path)
    except ValueError:
        module.fail_json(msg=
            "The '%s' file doesn't contain an integer value" % file_path)


def _get_frame_op_default_axis(name):
    """
    Only DataFrame cares about default_axis, specifically:
    special methods have default_axis=None and flex methods
    have default_axis='columns'.

    Parameters
    ----------
    name : str

    Returns
    -------
    default_axis: str or None
    """
    if name.replace('__r', '__') in ['__and__', '__or__', '__xor__']:
        return 'columns'
    elif name.startswith('__'):
        return None
    else:
        return 'columns'


def normalize_xc(xc: str) ->str:
    """
    Normalize the notation for xc
    """
    if xc.lower() == 'pbe':
        return 'PBE'
    elif xc.lower() in ['beef', 'beef-vdw']:
        return 'BEEF'
    elif xc.lower() == 'rpbe':
        return 'RPBE'
    elif xc.lower() == 'mbeef':
        return 'mBEEF'
    elif xc.lower() == 'hse':
        return 'HSE'
    elif xc.lower() == 'lda':
        return 'LDA'
    else:
        raise ValueError('weird xc: ', xc)


@classmethod
def get_descriptions(cls):
    """
        Gets descriptions.

        :return: The descriptions.
        :rtype: dict
        """
    return cls.descriptions


def parse_bool_str(bool_str):
    """
    Convert string to boolean.

    :param bool_str: str
    :return: Bool
    """
    if bool_str.lower() == 'false':
        return False
    elif bool_str.lower() == 'true':
        return True
    else:
        raise ValueError('Unable to parse "{}"'.format(bool_str))


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_ref_path(openapi_major_version):
    """Return the path for references based on the openapi version

    :param int openapi_major_version: The major version of the OpenAPI standard
        to use. Supported values are 2 and 3.
    """
    ref_paths = {(2): 'definitions', (3): 'components/schemas'}
    return ref_paths[openapi_major_version]


def is_good_srr(filepath):
    """Tests whether the file path only contains / and none
	of the other illegal characters: \\/:*?"<>| in Windows.

	Stored files in SRRs contain forward slashes.
	RAR uses backward slashes."""
    ILLEGAL_WINDOWS_CHARACTERS = '\\:*?"<>|'
    for char in ILLEGAL_WINDOWS_CHARACTERS:
        if char in filepath:
            return False
    return True


def _detect_notebook() ->bool:
    """Detect if code is running in a Jupyter Notebook.

    This isn't 100% correct but seems good enough

    Returns
    -------
    bool
        True if it detects this is a notebook, otherwise False.

    """
    try:
        from IPython import get_ipython
        from ipykernel import zmqshell
    except ImportError:
        return False
    kernel = get_ipython()
    try:
        from spyder.utils.ipython.spyder_kernel import SpyderKernel
        if isinstance(kernel.kernel, SpyderKernel):
            return False
    except (ImportError, AttributeError):
        pass
    return isinstance(kernel, zmqshell.ZMQInteractiveShell)


def unindex():
    """Un-index a content from the catalog.
        """


def unbox(obj):
    """
    General unbox helper.
    """
    if hasattr(obj, 'unbox'):
        return obj.unbox()
    return obj


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 set_attribute(library, session, attribute, attribute_state):
    """Sets the state of an attribute.

    Corresponds to viSetAttribute function of the VISA library.

    :param library: the visa library wrapped by ctypes.
    :param session: Unique logical identifier to a session.
    :param attribute: Attribute for which the state is to be modified. (Attributes.*)
    :param attribute_state: The state of the attribute to be set for the specified object.
    :return: return value of the library call.
    :rtype: :class:`pyvisa.constants.StatusCode`
    """
    return library.viSetAttribute(session, attribute, attribute_state)


def schedule(project, spider_name, **spider_args):
    """Schedule a spider for the given project"""


def process_data_format_value(value):
    """
    Computes a standardized label for a data format.

    Args:
        value (str): Name of a data format

    Returns:
        Formatted string if successful, None otherwise.
    """
    if value:
        return str(value).lower().strip().replace(' ', '_')
    return None


def render_longest_xsection_to_svg(mesh, plane, filename, look=None, **kwargs):
    """
    Rectangle of specified height and width along the plane normal,
    with given up vector, centered on the plane's reference point.

    When width or height is not provided, automatically set based on the data
    with 10% padding.
    """
    from .mesh import longest_xsection
    from .svg import write_polyline_3d
    if look is None:
        look = plane.normal
    xs = longest_xsection(mesh, plane)
    write_polyline_3d(polyline=xs, filename=filename, look=look, **kwargs)
    return xs


@classmethod
def from_registry(cls, schema_type, schema_classes, **kwargs):
    """Construct a ComponentSchema from a registry entry.

        Args:
            schema_type (str): Name of component type to build.
            schema_classes (list): List of classes for the component type.
            **kwargs: Additional keyword arguments are passed to the class
                __init__ method.

        Returns:
            ComponentSchema: Schema with information from classes.

        """
    out = cls(schema_type, **kwargs)
    for x in schema_classes:
        out.append(x)
    return out


@staticmethod
def _validate_reserved(to_check: list):
    """Checks if any base key is reserved"""
    check_list = []
    for item in to_check:
        if isinstance(item, str):
            check_list.append(item)
        elif isinstance(item, list):
            check_list += item
        elif isinstance(item, dict):
            check_list = list(item.keys())
    if 'manager' in check_list or 'contract' in check_list:
        raise KeyError(
            "The reserved words 'manager' and 'contract' can not be used as base property references"
            )


def scp_file(file, ip, path, ssh_key=None):
    """scp file to remote machine
    """
    if ssh_key is None:
        scp_cmd_str = 'scp %s %s:%s' % (file, ip, path)
    else:
        scp_cmd_str = 'scp -i %s %s %s:%s' % (ssh_key, file, ip, path)
    return scp_cmd_str


def merge_configs(*configs):
    """Merge configs in special format.

    It supports merging of configs in the following format:
    applicable_target -> config_name -> config_value

    """
    result = {}
    for config in configs:
        if config:
            for a_target in config:
                if a_target not in result or not result[a_target]:
                    result[a_target] = {}
                result[a_target].update(config[a_target])
    return result


def log_warning(msg, *args, **kwargs):
    """Log message with level WARNING."""
    import logging
    logging.getLogger(__name__).warning(msg, *args, **kwargs)


def expanding_mean(df, shift=1):
    """Calculate expanding mean of all numeric columns of a pandas dataframe

    Function can be used by ApplyFunc module.

    :param pd.DataFrame df: input pandas dataframe
    :param int shift: size of shift. default is 1.
    :return: df with expanding means of columns
    """
    return df.shift(shift).expanding().mean()


def pytest_saltfactories_master_verify_configuration(request, master_config,
    username):
    """
    This hook is called to vefiry the provided master configuration
    """


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

        :param TfaResetType val:
        :rtype: EventType
        """
    return cls('tfa_reset', val)


def get_schema():
    """Schema structure of this resource

    :return: schema dictionary
    :rtype: dict
    """
    return {'schema': {'schema_version': {'type': 'integer', 'default': 1},
        'imported_from': {'schema_version': 1, 'title': 'Imported from',
        'comment': 'Item importation source (alignak-backend-import, ...)',
        'type': 'string', 'default': 'unknown'}, 'definition_order': {
        'schema_version': 1, 'title': 'Definition order', 'comment':
        'Priority level if several elements have the same name', 'type':
        'integer', 'default': 100}, 'name': {'schema_version': 1, 'title':
        'Host dependency name', 'type': 'string', 'empty': False, 'unique':
        True}, 'alias': {'schema_version': 1, 'title': 'Alias', 'comment':
        'Element friendly name used by the Web User Interface.', 'type':
        'string', 'default': ''}, 'notes': {'schema_version': 1, 'title':
        'Notes', 'comment':
        'Element notes. Free text to store element information.', 'type':
        'string', 'default': ''}, 'dependent_hosts': {'schema_version': 1,
        'title': 'Dependent hosts', 'comment':
        'List of the hosts that are depending.', 'type': 'list', 'schema':
        {'type': 'objectid', 'data_relation': {'resource': 'host',
        'embeddable': True}}}, 'dependent_hostgroups': {'schema_version': 1,
        'title': 'Dependent hosts groups', 'comment':
        'List of the hosts groups that are depending.', 'type': 'list',
        'schema': {'type': 'objectid', 'data_relation': {'resource':
        'hostgroup', 'embeddable': True}}}, 'hosts': {'schema_version': 1,
        'title': 'Hosts', 'comment':
        'List of the hosts involved in the dependency.', 'type': 'list',
        'schema': {'type': 'objectid', 'data_relation': {'resource': 'host',
        'embeddable': True}}}, 'hostgroups': {'schema_version': 1, 'title':
        'Hosts groups', 'comment':
        'List of the hosts groups involved in the dependency.', 'type':
        'list', 'schema': {'type': 'objectid', 'data_relation': {'resource':
        'hostgroup', 'embeddable': True}}}, 'inherits_parent': {
        'schema_version': 1, 'title': 'Parent inheritance', 'comment':
        'See Alginak doc about dependency checks.', 'type': 'boolean',
        'default': False}, 'execution_failure_criteria': {'schema_version':
        1, 'title': 'Execution criteria', 'comment':
        'See Alginak doc about dependency checks.', 'type': 'list',
        'default': ['n'], 'allowed': ['o', 'd', 'x', 'p', 'n']},
        'notification_failure_criteria': {'schema_version': 1, 'title':
        'Notification criteria', 'comment':
        'See Alginak doc about dependency checks.', 'type': 'list',
        'default': ['d', 'u', 'p'], 'allowed': ['o', 'd', 'x', 'p', 'n']},
        'dependency_period': {'schema_version': 1, 'title':
        'Dependency period', 'comment':
        'Time period during which the dependency checks are done.', 'type':
        'objectid', 'data_relation': {'resource': 'timeperiod',
        'embeddable': True}, 'required': True}, '_realm': {'schema_version':
        1, 'title': 'Realm', 'comment': 'Realm this element belongs to.',
        'type': 'objectid', 'data_relation': {'resource': 'realm',
        'embeddable': True}, 'required': True}, '_sub_realm': {
        'schema_version': 1, 'title': 'Sub-realms', 'comment':
        'Is this element visible in the sub-realms of its realm?', 'type':
        'boolean', 'default': True}, '_users_read': {'schema_version': 1,
        'type': 'list', 'schema': {'type': 'objectid', 'data_relation': {
        'resource': 'user', 'embeddable': True}}}, '_users_update': {
        'schema_version': 1, 'type': 'list', 'schema': {'type': 'objectid',
        'data_relation': {'resource': 'user', 'embeddable': True}}},
        '_users_delete': {'schema_version': 1, 'type': 'list', 'schema': {
        'type': 'objectid', 'data_relation': {'resource': 'user',
        'embeddable': True}}}}, 'schema_deleted': {}}


def pdb2selection(pdbfile):
    """
    Create selection strings from pdbfile data.

    A little utility function to convert 'mask' pdb files into
    MDTraj-style selection strings. Basically it reads the second column
    (atom number) and uses it to construct 'index' selections. Runs
    of consecutive numbers are expressed in 'start to stop' form.

    Args:
        pdbfile (str): Name of a PDB file

    Returns:
        selection (str): MDtraj format selection string
    """
    sel = ''
    i = 0
    j = 0
    with open(pdbfile, 'r') as f:
        for line in f:
            if line.find('ATOM') == 0 or line.find('HETATM') == 0:
                k = int(line.split()[1])
                if i == 0:
                    i = k
                    j = k - 1
                if k == j + 1:
                    j = k
                else:
                    sel = sel + ' index {0} to {1} or'.format(i, j)
                    i = k
                    j = k
    if i > 0 and j > 0:
        sel = sel + ' index {0} to {1} or'.format(i, j)
    if len(sel) > 3:
        sel = sel[:-3]
    return sel


def safe_isinstance(obj, cls_str):
    """
    Checks whether a given obj implements the class who's name is in the cls_str parameter.
    This means that the isinstance check is performed without looking at the object's type hierarchy, but rather
    by class name.
    """
    if cls_str and obj:
        return cls_str in str(type(obj))
    return False


@staticmethod
def default_helper_c_code_args():
    """
        Returns a dictionary of default arguments to helper_c_code.

        """
    return {'c_prefix': 'PyArray', 'strides_mul': 1}


@classmethod
def unregister(cls, name):
    """Remove a codec from the registry.

        Unregisters the codec with the given `name` (a string).  If the codec
        is not registered, a `KeyError` is raised.

        >>> import binascii
        >>> CodecReg.register('uu', binascii.b2a_uu, binascii.a2b_uu)
        >>> 'uu' in CodecReg
        True
        >>> CodecReg.unregister('uu')
        >>> 'uu' in CodecReg
        False
        """
    del cls._codecs[name]


@staticmethod
def _get_next_marker_from_response_object(response_object):
    """Get the marker that should be used to retrieve the next page.

        When we've just retrieved the last page, the API is inconsistent about
        what it returns. Some endpoints return "next_marker":"", some return
        "next_marker":null, some don't give any "next_marker" value. In all of
        these cases, this method will return `None`.

        Otherwise, this method returns the string value of the "next_marker"
        field.

        :rtype:
            `unicode` or `None`
        """
    return response_object.get('next_marker') or None


@classmethod
def rvs(this, *params, size=1, random_state):
    """Generate random variates.

        Parameters
        ----------
        param1, param2, ... : array_like
            Parameter(s) of the distribution
        size : int or tuple of ints, optional
        random_state : RandomState

        Returns
        -------
        rvs : ndarray
            Random variates of given size.

        """
    raise NotImplementedError


def write_index_line(feat, chrom, start, stop, sign, fh):
    """ Write a new line in an index file. """
    feat_by_biotype = []
    for biot, cat in feat.items():
        feat_by_biotype.append(':'.join((str(biot), ','.join(sorted(cat)))))
    fh.write('\t'.join((chrom, start, stop, sign)) + '\t' + '\t'.join(
        feat_by_biotype) + '\n')


def binomial(n, k):
    """
    Calculate the binomial coefficient nCr(n,k).
    Input: n, k -- non-negative integers
    Output: Integer
    Examples:
    >>> binomial(30,12)
    86493225
    """
    nt = 1
    for t in range(min(k, n - k)):
        nt *= n - t
        nt //= t + 1
    return nt


def create_instance_profile(InstanceProfileName=None, Path=None):
    """
    Creates a new instance profile. For information about instance profiles, go to About Instance Profiles .
    For information about the number of instance profiles you can create, see Limitations on IAM Entities in the IAM User Guide .
    See also: AWS API Documentation

    Examples
    The following command creates an instance profile named Webserver that is ready to have a role attached and then be associated with an EC2 instance.
    Expected Output:

    :example: response = client.create_instance_profile(
        InstanceProfileName='string',
        Path='string'
    )

    :type InstanceProfileName: string
    :param InstanceProfileName: [REQUIRED]
            The name of the instance profile to create.
            This parameter allows (per its regex pattern ) a string of characters consisting of upper and lowercase alphanumeric characters with no spaces. You can also include any of the following characters: =,.@-

    :type Path: string
    :param Path: The path to the instance profile. For more information about paths, see IAM Identifiers in the IAM User Guide .
            This parameter is optional. If it is not included, it defaults to a slash (/).
            This paramater allows (per its regex pattern ) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes, containing any ASCII character from the ! (u0021) thru the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters.

    :rtype: dict
    :return: {
        'InstanceProfile': {
            'Path': 'string',
            'InstanceProfileName': 'string',
            'InstanceProfileId': 'string',
            'Arn': 'string',
            'CreateDate': datetime(2015, 1, 1),
            'Roles': [
                {
                    'Path': 'string',
                    'RoleName': 'string',
                    'RoleId': 'string',
                    'Arn': 'string',
                    'CreateDate': datetime(2015, 1, 1),
                    'AssumeRolePolicyDocument': 'string',
                    'Description': 'string'
                },
            ]
        }
    }

    """
    pass


def add_composition(node, composition, part=None):
    """Add composition to node"""
    if part is None:
        raise ValueError("'part' must be a function that returns a node")
    node.add_attr(composition.type, part(composition), position=composition
        .position, extra=composition.extra)


def reverse_complement(seq):
    """Converts a nucleotide sequence to reverse complement.

    The base characters in the nucleotide string (A, C, G and T) are converted to the following: A <-> T and C <-> G. The
    combined uppercase string is returned.

    Parameters
    ----------
    seq : str
        A nucleotide sequence string.

    Returns
    -------
    str
        The reverse complemented nucleotide sequence.

    """
    reverse_complement_seq = []
    for i in seq.upper():
        if i == 'A':
            reverse_complement_seq.append('T')
        elif i == 'C':
            reverse_complement_seq.append('G')
        elif i == 'G':
            reverse_complement_seq.append('C')
        elif i == 'T':
            reverse_complement_seq.append('A')
    return ''.join(reverse_complement_seq)


def syncreq(proxy, handler, *args):
    """Performs a synchronous request on the given proxy object.
    Not intended to be invoked directly.

    :param proxy: the proxy on which to issue the request
    :param handler: the request handler (one of the ``HANDLE_XXX`` members of
                    ``rpyc.protocol.consts``)
    :param args: arguments to the handler

    :raises: any exception raised by the operation will be raised
    :returns: the result of the operation
    """
    conn = object.__getattribute__(proxy, '____conn__')
    return conn.sync_request(handler, proxy, *args)


def iqr(series):
    """
    Extract inter-quantile range
    (25%-75%)

    Input
    ---
        series : pandas series

    Returns
    ---
        inter-quantile range
        (25-75%)
    """
    Q1 = series.quantile(0.25)
    Q3 = series.quantile(0.75)
    IQR = Q3 - Q1
    return IQR


def set_dimension(tensor, axis, value):
    """Set the length of a tensor along the specified dimension.

  Args:
    tensor: Tensor to define shape of.
    axis: Dimension to set the static shape for.
    value: Integer holding the length.

  Raises:
    ValueError: When the tensor already has a different length specified.
  """
    shape = tensor.shape.as_list()
    if shape[axis] not in (value, None):
        message = 'Cannot set dimension {} of tensor {} to {}; is already {}.'
        raise ValueError(message.format(axis, tensor.name, value, shape[axis]))
    shape[axis] = value
    tensor.set_shape(shape)


def register(mlist, email, msg, context=None):
    """Register a bounce event.

        :param mlist: The mailing list that the bounce occurred on.
        :type mlist: IMailingList
        :param email: The email address that is bouncing.
        :type email: str
        :param msg: The bounce message.
        :type msg: email.message.Message
        :param context: In what context was the bounce detected?  The default
            is 'normal' context (i.e. we received a normal bounce for the
            address).
        :type context: BounceContext
        :return: The registered bounce event.
        :rtype: IBounceEvent
        """


def register_event(event):
    """Register event type.

        :param event: Event name as string.
        """


def celsius2fahrenheit(c):
    """Convert temperatures."""
    return c * 1.8 + 32


def test(req, author, content, ip):
    """Test the given content submission.

        Should return a `(points, reason)` tuple to affect the score of the
        submission, where `points` is an integer, and `reason` is a brief
        description of why the score is being affected.

        If the filter strategy does not want (or is not able) to effectively
        test the submission, it should return `None`.
        """


def open_if_filename(file_or_path, mode='rb'):
    """
    file_or_path can be either a string or a file-like object.
    if it is a string, a file will be opened with mode.
    Returns a tuple (file, should_be_closed).
    """
    if isinstance(file_or_path, str):
        return open(file_or_path, mode), True
    else:
        return file_or_path, False


def atom_extract(Mask_3D, atom):
    """
    Given (a list of) 3D Mask, extract the coord's of needed atom.
    """
    xyz_list = []
    if type(Mask_3D) is list:
        for i in Mask_3D:
            for x, y in enumerate(i.des):
                if y == atom:
                    if i.values.size == 3:
                        i.values = i.values.reshape(1, 3)
                    xyz_list.append(i.values[x])
    else:
        for x, y in enumerate(Mask_3D.des):
            if y == atom:
                if Mask_3D.values.size == 3:
                    Mask_3D.values = Mask_3D.values.reshape(1, 3)
                xyz_list.append(Mask_3D.values[x])
    return xyz_list


def prepare_params(params):
    """
    Prepare params before the http request is dispatched.

    The return value must be a list of doubles (tuples of lenght 2). By now,
    the preparation step basically transforms `params` to the right return type
    sorted by keys.

    In cases where `params` is None, None must be returned.

    :param params: Is key/value pair or `None`.
    """
    if params is None:
        return None
    if hasattr(params, 'items'):
        params = params.items()
    return sorted(params)


def create_random_orthonormal_matrix(A):
    """returns a orthonormal matrix, just a wrapper for scipy.stats.ortho_group.rvs()"""
    from scipy.stats import ortho_group
    return ortho_group.rvs(A)


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

    The ".dev0" means dirty.

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


def sigma_Bird_Stewart_Lightfoot_melting(Vm):
    """Calculates Lennard-Jones molecular diameter.
    Uses molar volume of a liquid at its melting point. CSP method by [1]_.

    .. math::
        \\sigma = 1.222 V_{m,sol}^{1/3}

    Parameters
    ----------
    Vm : float
        Melting molar volume of a liquid at its melting point [m^3/mol]

    Returns
    -------
    sigma : float
        Lennard-Jones molecular diameter, [Angstrom]

    Notes
    -----
    Original units of Vm are mL/mol.

    Examples
    --------
    >>> sigma_Bird_Stewart_Lightfoot_melting(8.8e-05)
    5.435407341351406

    References
    ----------
    .. [1] Bird, R. Byron, Warren E. Stewart, and Edwin N. Lightfoot.
       Transport Phenomena, Revised 2nd Edition. New York:
       John Wiley & Sons, Inc., 2006
    """
    Vm = Vm * 1000000.0
    sigma = 1.222 * Vm ** (1 / 3.0)
    return sigma


def compute_flux_points_ul(quantity, quantity_errp):
    """Compute UL value for fermi flux points.

    See https://arxiv.org/pdf/1501.02003.pdf (page 30)
    """
    return 2 * quantity_errp + quantity


def decrypt_data(cipher, data):
    """
    Returns decrypted data.
    :param cipher: AES cipher
    :param data: Encrypted Data
    :return: Decrypted Data
    """
    return cipher.decrypt(data[:16]) + cipher.decrypt(data[16:])


def create_DMPlex_from_box(minX, maxX, minY, maxY, resX, resY, refinement=None
    ):
    """
    Create a box and fill with triangles up to a specified refinement
    - This only works if PETSc was configured with triangle
    """
    from petsc4py import PETSc
    nx = int((maxX - minX) / resX)
    ny = int((maxY - minY) / resY)
    dm = PETSc.DMPlex().create()
    dm.setDimension(1)
    boundary = dm.createSquareBoundary([minX, minY], [maxX, maxY], [nx, ny])
    dm.generate(boundary, name='triangle')
    if refinement:
        dm.setRefinementLimit(refinement)
        dm = dm.refine()
    dm.markBoundaryFaces('boundary')
    pStart, pEnd = dm.getChart()
    origSect = dm.createSection(1, [1, 0, 0])
    origSect.setFieldName(0, 'points')
    origSect.setUp()
    dm.setDefaultSection(origSect)
    origVec = dm.createGlobalVec()
    if PETSc.COMM_WORLD.size > 1:
        sf = dm.distribute(overlap=1)
        newSect, newVec = dm.distributeField(sf, origSect, origVec)
        dm.setDefaultSection(newSect)
    dm.stratify()
    return dm


def model_from_yaml(yaml_string, custom_objects=None):
    """Parses a yaml model configuration file
    and returns a model instance.
    """
    import yaml
    from keras.utils.layer_utils import layer_from_config
    config = yaml.load(yaml_string)
    return layer_from_config(config, custom_objects=custom_objects)


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


def enumerate_groups(id=None, exact_match=False, **kw):
    """Return an iterable of group info that match the given id exactly
        (if exact_match is given), or partially (if not). Group info is a dict
        with keys id, title.
        """


def remove_user_from_group(GroupName=None, UserName=None):
    """
    Removes the specified user from the specified group.
    See also: AWS API Documentation

    Examples
    The following command removes the user named Bob from the IAM group named Admins.
    Expected Output:

    :example: response = client.remove_user_from_group(
        GroupName='string',
        UserName='string'
    )

    :type GroupName: string
    :param GroupName: [REQUIRED]
            The name of the group to update.
            This parameter allows (per its regex pattern ) a string of characters consisting of upper and lowercase alphanumeric characters with no spaces. You can also include any of the following characters: =,.@-

    :type UserName: string
    :param UserName: [REQUIRED]
            The name of the user to remove.
            This parameter allows (per its regex pattern ) a string of characters consisting of upper and lowercase alphanumeric characters with no spaces. You can also include any of the following characters: =,.@-

    :return: response = client.remove_user_from_group(
        GroupName='Admins',
        UserName='Bob',
    )

    print(response)

    """
    pass


def rename_settings(apps, schema_editor):
    """Rename settings."""
    LocalConfig = apps.get_model('core', 'LocalConfig')
    lc = LocalConfig.objects.first()
    condition = (lc and 'admin' in lc._parameters and
        'default_domain_quota' in lc._parameters['admin'])
    if condition:
        lc._parameters['admin']['default_mailbox_quota'] = lc._parameters[
            'admin']['default_domain_quota']
        del lc._parameters['admin']['default_domain_quota']
        lc.save(update_fields=['_parameters'])


def get_scaled_distance(distance_tpl):
    """Scale distances from 0 to 1.

    Given tuple of (seq length, Hamming distance)
    return proportion of different sites
    unless one of the sequences was missing.
    """
    eff_seq_len, distance = distance_tpl
    if distance != 'NaN':
        if eff_seq_len > 0 and distance > 0:
            scaled_distance = distance / eff_seq_len
        else:
            scaled_distance = 0
    else:
        scaled_distance = 'NaN'
    return scaled_distance


def parse_mask(value, mask_enum):
    """Parse a mask into indivitual mask values from enum.

    :params ``int`` value:
        (Combined) mask value.
    :params ``enum.IntEnum`` mask_enum:
        Enum of all possible mask values.
    :returns:
        ``list`` - List of enum values and optional remainder.
    """
    masks = []
    for mask in mask_enum:
        if value & mask:
            masks.append(mask.name)
            value ^= mask
    if value:
        masks.append(hex(value))
    return masks


def function1(individual, position, height, width):
    """The function1 peak function to be used with scenario 1.

    :math:`f(\\mathbf{x}) = \\frac{h}{1 + w \\sqrt{\\sum_{i=1}^N (x_i - p_i)^2}}`

    """
    value = 0.0
    for x, p in zip(individual, position):
        value += (x - p) ** 2
    return height / (1 + width * value)


def read_access_token(token_file='access_token_file'):
    """ Extracts the access token from an external file

    Returns the extracted access token
    """
    f = open(token_file)
    token = f.readlines()[0]
    return token


def view_zoom_in(location: float=(0.0, 0.0)):
    """Zoom in the view

    :param location: Location, Cursor location in screen coordinates
    :type location: float
    """
    pass


def identity():
    """
    Identity mapper. Returns the values from the regular expression
    directly.
    """
    return lambda value: value


def markers_make_local():
    """Move selected scene markers to the active Action as local ‘pose’ markers

    """
    pass


@staticmethod
def add_common_args(parser, arglist=None, required_override=True):
    """Parse the common command line arguments """
    pass


def getdiffmeta(diff):
    """get commit metadata (date, node, user, p1) from a diff object

    The metadata could be "hg:meta", sent by phabsend, like:

        "properties": {
          "hg:meta": {
            "branch": "default",
            "date": "1499571514 25200",
            "node": "98c08acae292b2faf60a279b4189beb6cff1414d",
            "user": "Foo Bar <foo@example.com>",
            "parent": "6d0abad76b30e4724a37ab8721d630394070fe16"
          }
        }

    Or converted from "local:commits", sent by "arc", like:

        "properties": {
          "local:commits": {
            "98c08acae292b2faf60a279b4189beb6cff1414d": {
              "author": "Foo Bar",
              "authorEmail": "foo@example.com"
              "branch": "default",
              "commit": "98c08acae292b2faf60a279b4189beb6cff1414d",
              "local": "1000",
              "message": "...",
              "parents": ["6d0abad76b30e4724a37ab8721d630394070fe16"],
              "rev": "98c08acae292b2faf60a279b4189beb6cff1414d",
              "summary": "...",
              "tag": "",
              "time": 1499546314,
            }
          }
        }

    Note: metadata extracted from "local:commits" will lose time zone
    information.
    """
    props = diff.get(b'properties') or {}
    meta = props.get(b'hg:meta')
    if not meta:
        if props.get(b'local:commits'):
            commit = sorted(props[b'local:commits'].values())[0]
            meta = {}
            if b'author' in commit and b'authorEmail' in commit:
                meta[b'user'] = b'%s <%s>' % (commit[b'author'], commit[
                    b'authorEmail'])
            if b'time' in commit:
                meta[b'date'] = b'%d 0' % int(commit[b'time'])
            if b'branch' in commit:
                meta[b'branch'] = commit[b'branch']
            node = commit.get(b'commit', commit.get(b'rev'))
            if node:
                meta[b'node'] = node
            if len(commit.get(b'parents', ())) >= 1:
                meta[b'parent'] = commit[b'parents'][0]
        else:
            meta = {}
    if b'date' not in meta and b'dateCreated' in diff:
        meta[b'date'] = b'%s 0' % diff[b'dateCreated']
    if b'branch' not in meta and diff.get(b'branch'):
        meta[b'branch'] = diff[b'branch']
    if b'parent' not in meta and diff.get(b'sourceControlBaseRevision'):
        meta[b'parent'] = diff[b'sourceControlBaseRevision']
    return meta


def grid_calc(grid_obj, potential_name, ff_obj, rmass=None, T=None):
    """
          Calculates the energy grid using 'numba' , vectorized over the cpu

          :type grid_obj: instance of the grid object from the grid3D module.
          :param grid_obj: contains al the details for the energy grid calculation.

          :type potential_name: str
          :param potential_name: Name of the potential 'lj' or 'ljfh'

          :type ff_obj: Instance of the force field object from the forcefields module
          :param ff_obj: Contains all the mixing rules for a give functional form

          :raises: TypeError, NameError

          :rtype: Returns the 3D energy grid
          """
    import numpy as np
    import pyIsoP.potentials as potentials
    from tqdm import tqdm
    p = potentials.potentials()
    potential_form = getattr(p, str(potential_name))
    for k in tqdm(range(grid_obj.nz), desc=
        'Calculating grid: Current Z position'):
        for j in range(grid_obj.ny):
            for i in range(grid_obj.nx):
                grid_point = np.array([grid_obj.x_grid[i], grid_obj.y_grid[
                    j], grid_obj.z_grid[k]])
                diff_vec = grid_obj.coord - grid_point
                diff_vec = diff_vec - np.round(diff_vec)
                pbc_vec = np.dot(grid_obj.A, diff_vec.T).T
                rsq = np.sum(pbc_vec ** 2, axis=1)
                if potential_name == 'lj':
                    E = np.sum(potential_form(rsq, ff_obj.epsilon_array,
                        ff_obj.sigma_array))
                elif potential_name == 'ljfh' and T is not None and rmass is not None:
                    E = np.sum(potential_form(rsq, ff_obj.epsilon_array,
                        ff_obj.sigma_array, rmass, T))
                elif potential_name == 'ljfh' and (T is None or rmass is None):
                    raise TypeError(
                        'Missing T and rmass for Feynman-Hibbs correction')
                else:
                    raise NameError(
                        'Unknown potential: Add yours to potentials.py if need be'
                        )
                grid_obj.pot[i][j][k] = E
    grid_obj.pot_repeat = np.tile(grid_obj.pot, (grid_obj.nx_cells,
        grid_obj.ny_cells, grid_obj.nz_cells))
    return grid_obj


def round_ste(data=None, name=None, attr=None, out=None, **kwargs):
    """Straight-through-estimator of `round()`.

    In forward pass, returns element-wise rounded value to the nearest integer of the input (same as `round()`).

    In backward pass, returns gradients of ``1`` everywhere (instead of ``0`` everywhere as in `round()`):
    :math:`\\frac{d}{dx}{round\\_ste(x)} = 1` vs. :math:`\\frac{d}{dx}{round(x)} = 0`.
    This is useful for quantized training.

    Reference: Estimating or Propagating Gradients Through Stochastic Neurons for Conditional Computation.

    Example::
      x = round_ste([-1.5, 1.5, -1.9, 1.9, 2.7])
      x.backward()
      x = [-2.,  2., -2.,  2.,  3.]
      x.grad() = [1.,  1., 1.,  1.,  1.]

    The storage type of ``round_ste`` output depends upon the input storage type:
      - round_ste(default) = default
      - round_ste(row_sparse) = row_sparse
      - round_ste(csr) = csr

    Defined in src/operator/contrib/stes_op.cc:L55

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

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

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


def retrieve_task_id(context):
    """Helper to retrieve the `Task` identifier from the message `body`.
    This helper supports Protocol Version 1 and 2. The Protocol is well
    detailed in the official documentation:
    http://docs.celeryproject.org/en/latest/internals/protocol.html
    """
    headers = context.get('headers')
    body = context.get('body')
    if headers:
        return headers.get('id')
    else:
        return body.get('id')


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


def normalize_path(path):
    """Resolve given path from relative into absolute form."""
    if './' not in path:
        return path
    atoms = []
    for atom in path.split('/'):
        if atom == '.':
            pass
        elif atom == '..':
            if atoms:
                atoms.pop()
        elif atom:
            atoms.append(atom)
    newpath = '/'.join(atoms)
    if path.startswith('/'):
        newpath = '/' + newpath
    return newpath


@classmethod
def get_alert_type(cls):
    """Return alert_type when we only have the alert class"""
    return cls(cls.slug).alert_type


def _is_first_or_last_exon(row_list, row_index):
    """Determine if it is the first or the last coding exon."""
    start_exon = False
    end_exon = False
    n_rows = len(row_list)
    if row_index == 0:
        start_exon = True
    elif row_index == n_rows - 1:
        end_exon = True
    else:
        row = row_list[row_index]
        identical_to_previous = row_list[row_index - 1]['TranscriptID'] == row[
            'TranscriptID']
        identical_to_next = row_list[row_index + 1]['TranscriptID'] == row[
            'TranscriptID']
        if not identical_to_previous or row['StartPhase'] == -1:
            start_exon = True
        if not identical_to_next or row['EndPhase'] == -1:
            end_exon = True
    return start_exon, end_exon


def _fastq_head(buf, end=None):
    """
    Search for the end of the last complete *two* FASTQ records in buf[:end].

    Two FASTQ records are required to ensure that read pairs in interleaved
    paired-end data are not split.
    """
    linebreaks = buf.count(b'\n', 0, end)
    right = end
    for _ in range(linebreaks % 8 + 1):
        right = buf.rfind(b'\n', 0, right)
    return right + 1


def get_device_pool(arn=None):
    """
    Gets information about a device pool.
    See also: AWS API Documentation

    Examples
    The following example returns information about a specific device pool, given a project ARN.
    Expected Output:

    :example: response = client.get_device_pool(
        arn='string'
    )

    :type arn: string
    :param arn: [REQUIRED]
            The device pool's ARN.

    :rtype: dict
    :return: {
        'devicePool': {
            'arn': 'string',
            'name': 'string',
            'description': 'string',
            'type': 'CURATED'|'PRIVATE',
            'rules': [
                {
                    'attribute': 'ARN'|'PLATFORM'|'FORM_FACTOR'|'MANUFACTURER'|'REMOTE_ACCESS_ENABLED'|'APPIUM_VERSION',
                    'operator': 'EQUALS'|'LESS_THAN'|'GREATER_THAN'|'IN'|'NOT_IN'|'CONTAINS',
                    'value': 'string'
                },
            ]
        }
    }

    :returns:
    ARN: The ARN.
    FORM_FACTOR: The form factor (for example, phone or tablet).
    MANUFACTURER: The manufacturer.
    PLATFORM: The platform (for example, Android or iOS).
    REMOTE_ACCESS_ENABLED: Whether the device is enabled for remote access.
    APPIUM_VERSION: The Appium version for the test.

    """
    pass


def describe_snapshot_attribute(DryRun=None, SnapshotId=None, Attribute=None):
    """
    Describes the specified attribute of the specified snapshot. You can specify only one attribute at a time.
    For more information about EBS snapshots, see Amazon EBS Snapshots in the Amazon Elastic Compute Cloud User Guide .
    See also: AWS API Documentation

    Examples
    This example describes the createVolumePermission attribute on a snapshot with the snapshot ID of snap-066877671789bd71b.
    Expected Output:

    :example: response = client.describe_snapshot_attribute(
        DryRun=True|False,
        SnapshotId='string',
        Attribute='productCodes'|'createVolumePermission'
    )

    :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 SnapshotId: string
    :param SnapshotId: [REQUIRED]
            The ID of the EBS snapshot.

    :type Attribute: string
    :param Attribute: [REQUIRED]
            The snapshot attribute you would like to view.

    :rtype: dict
    :return: {
        'SnapshotId': 'string',
        'CreateVolumePermissions': [
            {
                'UserId': 'string',
                'Group': 'all'
            },
        ],
        'ProductCodes': [
            {
                'ProductCodeId': 'string',
                'ProductCodeType': 'devpay'|'marketplace'
            },
        ]
    }

    """
    pass


def setTcpKeepAlive(enabled):
    """
        Enable/disable C{SO_KEEPALIVE}.

        Enabling C{SO_KEEPALIVE} sends packets periodically when the connection
        is otherwise idle, usually once every two hours. They are intended
        to allow detection of lost peers in a non-infinite amount of time.
        """


def get_status(mod_instances):
    """Creates the JSON dictionary representing the status"""
    ret = []
    for m, o in mod_instances:
        result = o.get_status()
        if not result:
            result = {}
        result['name'] = m
        ret.append(result)
    ret = {'data': ret, 'version': 0}
    return ret


def stop():
    """Stop the runner on the next iteration through the loop."""


def color_hide(unselected: bool=False):
    """Hide selected/unselected Grease Pencil colors

    :param unselected: Unselected, Hide unselected rather than selected colors
    :type unselected: bool
    """
    pass


@classmethod
def get_meta_tag(cls, nsmap):
    """Helper method to get the full name for <meta:user-defined> tags."""
    return '{{{}}}{}'.format(nsmap[cls.META_VAR_TAG_NS], cls.META_VAR_TAG_NAME)


def checkKeywords(dic, legalKeywords, what='argument'):
    """Verify no illegal keyword arguments were passed to a function.

    in : dic, dictionary (**kw in the calling routine).
         legalKeywords, list of strings, the keywords that are allowed.
         what, string, suffix for error message (see function source).
    out: None.
    exc: TypeError if 'dic' contains a key not in 'legalKeywords'.
    called by: Cheetah.Template.__init__()
    """
    for k in dic:
        if k not in legalKeywords:
            raise TypeError("'%s' is not a valid %s" % (k, what))


def hex8_to_u32be(data):
    """! @brief Build 32-bit register value from big-endian 8-digit hexadecimal string"""
    return int(data[6:8] + data[4:6] + data[2:4] + data[0:2], 16)


def to_bool(bool_str: str):
    """Convert str to bool."""
    bool_str_lc = bool_str.lower()
    if bool_str_lc in ('true', '1', 't'):
        return True
    if bool_str_lc in ('false', '0', 'f', ''):
        return False
    raise ValueError(f'cannot interpret {bool_str} as a bool')


def isiterable(obj):
    """
    Returns `True` if the given object is iterable;
    borrowed from :mod:`astropy.cosmology.core`
    """
    try:
        iter(obj)
        return True
    except TypeError:
        return False


@staticmethod
def permalink(mlist, msg):
    """See `IArchiver`."""
    return None


def sanitize_cloud(cloud: str) ->str:
    """
    Fix rare cloud layer issues
    """
    if len(cloud) < 4:
        return cloud
    if not cloud[3].isdigit() and cloud[3] not in ('/', '-'):
        if cloud[3] == 'O':
            cloud = cloud[:3] + '0' + cloud[4:]
        elif cloud[3] != 'U':
            cloud = cloud[:3] + cloud[4:] + cloud[3]
    return cloud


def get_mangled_ignore(model):
    """returns a mangled attribute name specific to the model"""
    return '_{opt.model_name}__{opt.app_label}_cleanup_ignore'.format(opt=
        model._meta)


def fix_frequency(frequency):
    """
    Fixes the frequency format for RS-UV3.
    """
    return frequency.replace('.', '')


def _build_simple_row(padded_cells, rowfmt):
    """Format row according to DataRow format without padding."""
    begin, sep, end = rowfmt
    return (begin + sep.join(padded_cells) + end).rstrip()


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

        :param AccountCaptureMigrateAccountType val:
        :rtype: EventType
        """
    return cls('account_capture_migrate_account', val)


def loadConfig(filename, clear=False):
    """Load a configuration file. If clear is set to false the
        configuration will be merged into the current configuration. If clear
        is true the current configuration will be replaced."""


@staticmethod
def get_geofence_coordinates(policy_contract_dict):
    """
        Extract geofence coordinates from supplied policy contract.

        :param policy_contract_dict: The contract of interest
        :type policy_contract_dict: dict
        :return: latitude of geofence center
        :return: longitude of geofence center
        :return: radius of geofence
        :rtype: string
        :rtype: string
        :rtype: string
        """
    try:
        lat = policy_contract_dict['geofence']['candidate_config']['lat']
        lng = policy_contract_dict['geofence']['candidate_config']['lng']
        radius = policy_contract_dict['geofence']['candidate_config']['radius']
        return lat, lng, radius
    except KeyError:
        return None, None, None


def dolly(delta: int=0, mx: int=0, my: int=0):
    """Dolly in/out in the view

    :param delta: Delta
    :type delta: int
    :param mx: Zoom Position X
    :type mx: int
    :param my: Zoom Position Y
    :type my: int
    """
    pass


def s3_isfile(filepath, bucket):
    """
    @doc: check a file for existence in an S3 bucket
    @args: filepath is a str
           bucket is a boto3.resource.Bucket object
    @return: boolean whether or not the file exists
    """
    if bucket is None:
        return False
    objs = list(bucket.objects.filter(Prefix=filepath))
    return len(objs) > 0 and objs[0].key == filepath


@classmethod
def sum(cls, heat_utilities):
    """
        Return a HeatUtility object that reflects the sum of heat
        utilities.
        """
    heat_utility = cls()
    heat_utility.mix_from(heat_utilities)
    return heat_utility


def to_list(x, allow_tuple=False):
    """Normalizes a list/tensor into a list.

    If a tensor is passed, we return
    a list of size 1 containing the tensor.

    # Arguments
        x: target object to be normalized.
        allow_tuple: If False and x is a tuple,
            it will be converted into a list
            with a single element (the tuple).
            Else converts the tuple to a list.

    # Returns
        A list.
    """
    if isinstance(x, list):
        return x
    if allow_tuple and isinstance(x, tuple):
        return list(x)
    return [x]


def get_attribute(obj, key):
    """
    Get an attribute from an object, regardless of whether it is a dict or an object
    """
    if not isinstance(obj, dict):
        return getattr(obj, key)
    return obj[key]


def extrude_vertices_move(MESH_OT_extrude_verts_indiv=None,
    TRANSFORM_OT_translate=None):
    """Extrude vertices and move result

    :param MESH_OT_extrude_verts_indiv: Extrude Only Vertices, Extrude individual vertices only
    :param TRANSFORM_OT_translate: Move, Move selected items
    """
    pass


def one_hot_encoding(x, allowable_set, encode_unknown=False):
    """One-hot encoding.

    Parameters
    ----------
    x
        Value to encode.
    allowable_set : list
        The elements of the allowable_set should be of the
        same type as x.
    encode_unknown : bool
        If True, map inputs not in the allowable set to the
        additional last element.

    Returns
    -------
    list
        List of boolean values where at most one value is True.
        The list is of length ``len(allowable_set)`` if ``encode_unknown=False``
        and ``len(allowable_set) + 1`` otherwise.
    """
    if encode_unknown and allowable_set[-1] is not None:
        allowable_set.append(None)
    if encode_unknown and x not in allowable_set:
        x = None
    return list(map(lambda s: x == s, allowable_set))


def getLevel(unique_name):
    """Returns a ILevel in the hierarchy with the given unique name."""


def p_rel_expr_5(p):
    """RelationalExpr : RelationalExpr GTE AdditiveExpr"""
    p[0] = 'comp', '>=', p[1], p[3]


def showOperandLines(rh):
    """
    Produce help output related to operands.

    Input:
       Request Handle
    """
    if rh.function == 'HELP':
        rh.printLn('N', '  For the MigrateVM function:')
    else:
        rh.printLn('N', 'Sub-Functions(s):')
    rh.printLn('N', '      cancel   - ' +
        'cancels the relocation of the specified virtual machine.')
    rh.printLn('N', '      help     - Displays this help information.')
    rh.printLn('N', '      modify   - ' +
        'modifies the time limits associated with the relocation already')
    rh.printLn('N', '                 in progress .')
    rh.printLn('N', '      move     - ' +
        'moves the specified virtual machine, while it continues to run,')
    rh.printLn('N', '                 ' +
        'to the specified system within the SSI cluster.')
    rh.printLn('N', '      status   - requests information about ' +
        'relocations currently in progress.')
    rh.printLn('N', '      test     - tests the specified virtual machine ' +
        'and reports whether or not')
    rh.printLn('N', '                 ' +
        'it is eligible to be relocated to the specified system.')
    rh.printLn('N', '      version  - show the version of the power function')
    if rh.subfunction != '':
        rh.printLn('N', 'Operand(s):')
    rh.printLn('N', '      --all                  - All relocations')
    rh.printLn('N', '      --destination <dest>   - ' +
        'Specifies the SSI name of the target destination')
    rh.printLn('N', '                               z/VM system ')
    rh.printLn('N', '      --forcearch            - ' +
        'force relocations past architecture checks.')
    rh.printLn('N', '      --forcedomain          - ' +
        'force relocations past domain checks.')
    rh.printLn('N', '      --forcestorage         - ' +
        'force relocations past storage checks.')
    rh.printLn('N', '      --immediate            - ' +
        'causes the VMRELOCATE command to do one early')
    rh.printLn('N', '                               ' +
        'pass through virtual machine storage and then go')
    rh.printLn('N', '                               ' +
        'directly to the quiesce stage.')
    rh.printLn('N', '      --incoming             - Incoming relocations')
    rh.printLn('N', '      --maxquiesce <maxQVal> - ' +
        'indicates the maximum quiesce time (in seconds)')
    rh.printLn('N', '                               for this relocation.')
    rh.printLn('N', '      --maxtotal <maxVal>    - ' +
        'indicates the maximum total time (in seconds)')
    rh.printLn('N', '                               ' +
        'for relocation to complete.')
    rh.printLn('N', '      --outgoing             - Out-going relocations')
    rh.printLn('N', '      <userid>               - ' +
        'Userid of the target virtual machine')
    return


@staticmethod
def set_node_border_width_property(node_properties, border_width):
    """Set the border width in node_properties.

		Args:
			node_properties (dict): Dictionary of node attributes. Key-value pairs will be used to set data associated with the node.
			border_width (int): Width of border.

		Returns:
			dict: Dictionary of node attributes.
		"""
    node_properties.update({'border-width': border_width})
    return node_properties


def dict2tuple(d):
    """Build a tuple from a dict.

    :param d: The dict to coherence into a tuple.
    :returns: The dict d in tuple form.
    """
    items = list(d.items())
    items.sort()
    return tuple(items)


@classmethod
def from_str(cls, s):
    """Creates scope from string.
        """
    if s == 'grp':
        return cls.GROUP
    if s == 'ent':
        return cls.ENTITY
    if s == 'attr':
        return cls.ATTRIBUTE
    raise Exception('Unknown scope')


def is_datasource(tool_xml):
    """Returns true if the tool is a datasource tool"""
    return tool_xml.getroot().attrib.get('tool_type', '') == 'data_source'


@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['validatorType']
    if type == 'DEFAULT':
        return 'DefaultTagDefinitionValidator'
    if type == 'ENUM':
        return 'EnumTagDefinitionValidator'
    else:
        return 'BaseTagDefinitionValidator'


@classmethod
def direct_studies(cls):
    """Options for direct studies.

        In particular this classmethod will set options below:
        irradiance_calc (-I) = True
        ambient_bounces (-ab) = 0
        direct_certainty (-dc) = 1
        direct_threshold (-dt) = 0
        direct_jitter (-dj) = 0
        direct_sec_relays (-dr) = 0
        """
    cls_ = cls()
    cls_.I = True
    cls_.ab = 0
    cls_.dc = 1
    cls_.dt = 0
    cls_.dj = 0
    cls_.dr = 0
    return cls_


@classmethod
def create_router_interface(cls, router_id, subnet_id):
    """Wrapper utility that returns a router interface."""
    interface = cls.client.add_router_interface_with_subnet_id(router_id,
        subnet_id)
    return interface


@classmethod
def parseKwargs(cls, config_outliers, logger=None):
    """Parse the outliers field of a configuration dict and return the kwargs to use for
        initializing an instance of the class.

        The base class implementation just returns the kwargs as they are, but derived classes
        might want to override this if they need to do something more sophisticated with them.

        :param config_outliers: The outliers field of the configuration dict, config['outliers']
        :param logger:          A logger object for logging debug info. [default: None]

        :returns: a kwargs dict to pass to the initializer
        """
    kwargs = {}
    kwargs.update(config_outliers)
    kwargs.pop('type', None)
    return kwargs


def transposed(table):
    """Returns the transposition of the table."""
    if table == None:
        return None
    t_table = []
    for i in table:
        while len(i) > len(t_table):
            t_table.append([])
    for column in table:
        for i in range(len(column)):
            t_table[i].append(column[i])
    return t_table


def weighted_sum(pdf, col_name):
    """
    Return weighted sum of Pandas DataFrame col_name items.
    """
    return (pdf[col_name] * pdf['s006']).sum()


@classmethod
def print_unimplemented(cls):
    """Show warning that method is not yet implemented."""
    print('not implemented yet (see things.sh for a more complete CLI)')


@staticmethod
def document_to_object(document):
    """
        Document_to_object.

        Translate document to python object
        removes _id from document.
        """
    if document:
        document.pop('_id', None)
    else:
        document = None
    return document


@classmethod
def dict_from_object(cls, entity_obj):
    """Convert from object representation to dict representation."""
    return cls.from_obj(entity_obj).to_dict()


@staticmethod
def _readMeta(fd):
    """Read meta array from the top of a file. Read lines until a blank line is reached.
        This function should ideally work for ALL versions of MetaArray.
        """
    meta = ''
    while True:
        line = fd.readline().strip()
        if line == '':
            break
        meta += line
    ret = eval(meta)
    return ret


def compress_user(path: str, tilde_expand: bool, tilde_val: str) ->str:
    """Does the opposite of expand_user, with its outputs.
    """
    if tilde_expand:
        return path.replace(tilde_val, '~')
    else:
        return path


def stroke_merge_by_distance(threshold: float=0.001, use_unselected: bool=False
    ):
    """Merge points by distance

    :param threshold: Threshold
    :type threshold: float
    :param use_unselected: Unselected, Use whole stroke, not only selected points
    :type use_unselected: bool
    """
    pass


@staticmethod
def deserialize_boolean(read):
    """Return a boolean"""
    if type(read) is bool:
        return read
    if type(read) is int and read in (0, 1):
        return bool(read)
    if read.lower() in ('true', 't', 'yes', '1'):
        return True
    if read.lower() in ('false', 'f', 'no', '0'):
        return False
    raise ValueError('Unknown boolean value {!s}'.format(read))


def ocean_bake(modifier: str='', free: bool=False):
    """Bake an image sequence of ocean data

    :param modifier: Modifier, Name of the modifier to edit
    :type modifier: str
    :param free: Free, Free the bake, rather than generating it
    :type free: bool
    """
    pass


def get_service_name(userName):
    """Return the service name for the given user"""
    simpleUserName = userName.rsplit('\\', 1)[-1]
    svc_name = 'chalmers:manager:%s' % simpleUserName
    return svc_name