def string(var, var_name):
    """
    Check if parameter *var* is a string.

    :raises TypeError: Parameter *var* must be a string.
    """
    if var is None:
        return
    if not isinstance(var, str):
        raise TypeError('\n\nParameter {} must be a string.\n'.format(var_name)
            )


def earth_rates(ATTITUDE):
    """return angular velocities in earth frame"""
    from math import sin, cos, tan, fabs
    p = ATTITUDE.rollspeed
    q = ATTITUDE.pitchspeed
    r = ATTITUDE.yawspeed
    phi = ATTITUDE.roll
    theta = ATTITUDE.pitch
    psi = ATTITUDE.yaw
    phiDot = p + tan(theta) * (q * sin(phi) + r * cos(phi))
    thetaDot = q * cos(phi) - r * sin(phi)
    if fabs(cos(theta)) < 1e-20:
        theta += 1e-10
    psiDot = (q * sin(phi) + r * cos(phi)) / cos(theta)
    return phiDot, thetaDot, psiDot


def to_degree(value):
    """Helper function to convert the GPS coordinates
    stored in the EXIF to degress in float format"""
    d0 = value[0][0]
    d1 = value[0][1]
    d = float(d0) / float(d1)
    m0 = value[1][0]
    m1 = value[1][1]
    m = float(m0) / float(m1)
    s0 = value[2][0]
    s1 = value[2][1]
    s = float(s0) / float(s1)
    return d + m / 60.0 + s / 3600.0


def chunk_iter(chunk_size, upperbound):
    """Yields back chunk size pieces from zero to upperbound - 1."""
    chunk = []
    for i in range(0, upperbound):
        chunk.append(i)
        if len(chunk) == chunk_size:
            yield chunk
            chunk = []


def descendant(class_or_instance, class_):
    """
    This function takes a class or instance and determines if it is either a
    subclass or instance of *class_*. This is useful if you allow either a class
    or an instance to serve as a template for a function.

    :param class_or_instance: The class or instance to check against *class_*

    :param class\\_: The class being checked for an inheritance relationship.

    :returns: Boolean True if *class_or_instance* is in some way a descendant
        of *class_*, False otherwise.
    """
    if type(class_or_instance) == type:
        return issubclass(class_or_instance, class_)
    else:
        return isinstance(class_or_instance, class_)


def strip_leading_numbers(s):
    """
    Return a string removing leading words made only of numbers.
    """
    s = s.split()
    while s and s[0].isdigit():
        s = s[1:]
    return u' '.join(s)


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


def renderBody():
    """Render the table body."""


def portrait_for(username, use_default=False):
    """
        Get portrait object for username, or return None (if use_default
        is False).  If use_default is True and no portrait exists,
        return the default.
        """


def p_fplist_star_2(p):
    """fplist_star : fplist_star COMMA fpdef"""
    p[1].elts.append(p[3])
    p[0] = p[1]


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

        :param MemberAccessLevelResult val:
        :rtype: RemoveFileMemberError
        """
    return cls('no_explicit_access', val)


def AsList(arg):
    """return the given argument unchanged if already a list or tuple, otherwise return a single
    element list"""
    return arg if isinstance(arg, (tuple, list)) else [arg]


def filename2id(path):
    """Convert a filepath to and ID."""
    if path[:6] == '/file.':
        return int(path[6:], 16)
    return int(path.split('/')[-1], 16)


@classmethod
def get_default_database_name(cls):
    """Return the name of current database."""
    if cls._default_db is None:
        raise ConnectionError("Haven't set default database.")
    return cls._default_db


@classmethod
def parse(cls, params):
    """
        Parses a WebSocket extension response for `permessage-snappy` provided by a server to a client.

        :param params: Output from :func:`autobahn.websocket.WebSocketProtocol._parseExtensionsHeader`.
        :type params: list

        :returns: A new instance of :class:`autobahn.compress.PerMessageSnappyResponse`.
        :rtype: obj
        """
    client_no_context_takeover = False
    server_no_context_takeover = False
    for p in params:
        if len(params[p]) > 1:
            raise Exception(
                "multiple occurrence of extension parameter '%s' for extension '%s'"
                 % (p, cls.EXTENSION_NAME))
        val = params[p][0]
        if p == 'client_no_context_takeover':
            if val is not True:
                raise Exception(
                    "illegal extension parameter value '%s' for parameter '%s' of extension '%s'"
                     % (val, p, cls.EXTENSION_NAME))
            else:
                client_no_context_takeover = True
        elif p == 'server_no_context_takeover':
            if val is not True:
                raise Exception(
                    "illegal extension parameter value '%s' for parameter '%s' of extension '%s'"
                     % (val, p, cls.EXTENSION_NAME))
            else:
                server_no_context_takeover = True
        else:
            raise Exception(
                "illegal extension parameter '%s' for extension '%s'" % (p,
                cls.EXTENSION_NAME))
    response = cls(client_no_context_takeover, server_no_context_takeover)
    return response


def dec2ddmmss(deg):
    """Convert DEC coordinate (in degrees) to DD MM SS"""
    from math import modf
    sign = -1 if deg < 0 else 1
    x, dd = modf(abs(deg))
    x, ma = modf(x * 60)
    sa = x * 60
    return int(dd), int(ma), sa, sign


def check_error_div(data, error_div):
    """
    Dunno about this, it was created long time ago and I have no idea.
    """
    if error_div in data:
        data = data.split(error_div)[1]
        data = data.split('</div>')[0]
        raise ValueError(data)


def convert_bool(s):
    """Convert input string to boolean.

    Input string must either be ``True`` or ``False``.
    """
    if s == 'True':
        return True
    elif s == 'False':
        return False
    else:
        raise ValueError('Cannot convert bool: %r' % s)


@classmethod
def add_operatingsystem(cls, options=None):
    """Adds operating system, requires "id" and "operatingsystem-id"."""
    cls.command_sub = 'add-operatingsystem'
    result = cls.execute(cls._construct_command(options), output_format='csv')
    return result


@staticmethod
def _setReturnValuesForPromises(target, returnValues, jobStore):
    """
        Sets the values for promises using the return values from the target's
        run function.
        """
    for i in target._rvs.keys():
        if isinstance(returnValues, tuple):
            argToStore = returnValues[i]
        else:
            if i != 0:
                raise RuntimeError(
                    'Referencing return value index (%s) that is out of range: %s'
                     % (i, returnValues))
            argToStore = returnValues
        target._rvs[i]._storeValue(argToStore, jobStore)


def istupleoftuples(x):
    """Is an object a python list of lists x=[[1,2], [3,4]]"""
    return type(x) is tuple and type(x[0]) is tuple


def intr(n):
    """Returns a correctly rounded integer"""
    return int(round(n))


def psi_Li_Cl_NO3_PK74(T, P):
    """c-a-a': lithium chloride nitrate [PK74]."""
    psi = -0.003
    valid = T == 298.15
    return psi, valid


def split_scenarios(scentime, scencmd):
    """ Split the contents of a batch file into individual scenarios. """
    start = 0
    for i in range(1, len(scencmd) + 1):
        if i == len(scencmd) or scencmd[i][:4] == 'SCEN':
            scenname = scencmd[start].split()[1].strip()
            yield dict(name=scenname, scentime=scentime[start:i], scencmd=
                scencmd[start:i])
            start = i


@staticmethod
def match(dftCase, *matches):
    """
        Perform matching clause
        """
    for m in matches:
        if m.cond is None:
            return m.rst() if callable(m.rst) else m.rst
        elif m.cond():
            return m.rst() if callable(m.rst) else m.rst
    return dftCase.rst() if callable(dftCase.rst) else dftCase.rst


def num_transfer(df):
    """Total number of track transfer."""
    return df.extra.Type.isin(['TRANSFER']).sum()


@staticmethod
def action(*args, **kwargs):
    """Default: do nothing when fsm.action() is called
        """
    pass


def makedirs(name, mode=None, exist_ok=False):
    """Forward ports `exist_ok` flag for Py2 makedirs. Retains mode defaults"""
    from os import makedirs
    mode = mode if mode is not None else 511
    makedirs(name, mode, exist_ok)


def get_namespaces(parent):
    """parse the first element of a datastream xml tree for namespaces"""
    namespace = {}
    for child in parent.get_elements():
        for attrib_name in child._attributes:
            if 'xmlns:' in attrib_name:
                namespace[attrib_name[6:]] = child[attrib_name]
    print(namespace)
    return namespace


@staticmethod
def xml_bins_name_dec(name, suffix=u'pylal_rate_bins'):
    """
		For internal use by XML I/O code.  Subclasses should not
		override this method.
		"""
    name = name.rsplit(u':', 1)
    if name[-1] != suffix:
        raise ValueError(name)
    return name[0]


def u16le_list_to_byte_list(data):
    """! @brief Convert a halfword array into a byte array"""
    byteData = []
    for h in data:
        byteData.extend([h & 255, h >> 8 & 255])
    return byteData


def do_nothing_vib(image, dirname):
    """Explanation of the initialization function needed for the vibrational
    analysis in class *Dissociation*.

    This function can be used to set a cell and a calculator.

    Parameters
    ----------
    image: Atoms object
        Configuration used.
    dirname: str
        Path of the directory where output files of the vibrational analysis
        will be saved.

    """
    pass


def _generate(item_counts):
    """
    item_counts is a list of counts of "types" of items. E.g., [3, 1, 0, 2] represents
    a list containing [1, 1, 1, 2, 4, 4] (3 types of items/distinct values). Generate
    a new list with evenly spaced values.
    """
    item_counts.sort(reverse=True)
    unplaced = sum(item_counts)
    placements = [None] * unplaced
    for item_type, item_count in enumerate(item_counts):
        instance = 0
        blank_count = -1
        for position in range(len(placements)):
            if placements[position] is None:
                blank_count += 1
                if blank_count * item_count // unplaced == instance:
                    placements[position] = item_type
                    instance += 1
        unplaced -= item_count
    return placements


@classmethod
def from_empty(cls, mem, size=0):
    """From empty device array
        """
    return cls(mem, size=size, capacity=mem.size)


@classmethod
def get_urlpatterns(cls):
    """Method called by load_urlpatterns, makes it more simpel to get model urlpatterns"""
    return cls.URL_PATTERNS


@classmethod
def register_rule(cls, **kwargs):
    """
        Use it as a class decorator::

            normalizer = Normalizer('grammar', 'config')
            @normalizer.register_rule(value='foo')
            class MyRule(Rule):
                error_code = 42
        """
    return cls._register_rule(**kwargs)


def _itemsview_isdisjoint(view, other):
    """Return True if two sets have a null intersection."""
    for v in other:
        if v in view:
            return False
    return True


@classmethod
def from_mesh(cls, context, mesh):
    """Construct a :class:`compas.files.GLTFMesh` object from a compas mesh.

        Parameters
        ----------
        context : :class:`compas.files.GLTFContent`
        mesh : :class:`compas.datastructures.Mesh`

        Returns
        -------
        :class:`compas.files.GLTFMesh`
        """
    vertices, faces = mesh.to_vertices_and_faces()
    return cls.from_vertices_and_faces(context, vertices, faces)


def quantity_to_tuple(quantity, unit_str):
    """
    Splits a quantity into a tuple of (value,unit) where unit is FITS complient.

    Useful to write FITS header keywords with units in a comment.

    Parameters
    ----------
    quantity : astropy quantity
        The Astropy quantity to split.
    unit_str: str
        Unit string representation readable by astropy.units (e.g. 'm', 'TeV', ...)

    Returns
    -------
    tuple
        A tuple containing the value and the quantity.
    """
    return quantity.to(unit_str).value, quantity.to(unit_str).unit.to_string(
        format='FITS')


def chunks(l, n):
    """Yield successive n-sized chunks from l."""
    for i in range(0, len(l), n):
        yield l[i:i + n]


def run_code(code):
    """Execute the code string `code`.

    Intended to be used in conjunction with :func:`call`.
    """
    exec(code)


def drain_eta(re, mu_function, *args, **kwargs):
    """Calculate the vertical drain eta parameter for a specific smear zone

    eta = 2 / re**2 / (mu+muw)

    eta is used in radial consolidation equations u= u0 * exp(-eta*kh/gamw*t)

    Parameters
    ----------
    re : float
        Drain influence radius.
    mu_function : obj or string
        The mu_funtion to use. e.g. mu_ideal, mu_constant, mu_linear,
        mu_overlapping_linear, mu_parabolic, mu_piecewise_constant,
        mu_piecewise_linear. This can either be the function object itself
        or the name of the function e.g. 'mu_ideal'.
    muw : float, optional
        Well resistance mu term, default=0.
    *args, **kwargs : various
        The arguments to pass to the mu_function.

    Returns
    -------
    eta : float
        Value of eta parameter

    Examples
    --------

    >>> drain_eta(1.5, mu_ideal, 10)
    0.563178340433...
    >>> drain_eta(1.5, 'mu_ideal', 10)
    0.5631783404334...
    >>> drain_eta(1.5, mu_constant, 5, 1.5, 1.6, muw=1)
    0.4115837724144...

    """
    try:
        mu_fn = globals()[mu_function]
    except KeyError:
        mu_fn = mu_function
    muw = kwargs.pop('muw', 0)
    eta = 2 / re ** 2 / (mu_fn(*args, **kwargs) + muw)
    return eta


def revoke_permission(username, action):
    """Revokes the permission of the given user to perform an action."""


def get_details_from_gplaycli(handle):
    """
    Get the details from gpc like creator, number of downloads, etc
    :param handle: application handle
    :return: application details dictionary
    """
    return None


def pilot_pos(data):
    """
        Parse string containing information about pilot's position coordinates.

        Input:
        `data`      # A string in '{id}:user{id}_{id};{x};{y};{z}' format,
                    # where x, y, z are integer values of pilot's coordinates.
                    # Example:
                    # "0:user0_0;100;200;300"

        Output:
        An object containing information about pilot's callsign and
        coordinates.
        """


def actor_system_already_running(ip='127.0.0.1'):
    """
    Determines whether an actor system is already running by opening a socket connection.

    Note: It may be possible that another system is running on the same port.
    """
    import socket
    s = socket.socket()
    try:
        s.connect((ip, 1900))
        s.close()
        return True
    except Exception:
        return False


def duplicate():
    """Make copies of the selected bones within the same armature

    """
    pass


def _decoded_str_len(l):
    """
    Compute how long an encoded string of length *l* becomes.
    """
    rem = l % 4
    if rem == 3:
        last_group_len = 2
    elif rem == 2:
        last_group_len = 1
    else:
        last_group_len = 0
    return l // 4 * 3 + last_group_len


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

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


def copySubKeywords(inhdr, outhdr, subarray):
    """Copy the subarray keywords from one header to another.

    This is for copying the subarray keywords from the input extension
    header to the primary header of the csum file.

    Parameters
    ----------
    inhdr: pyfits Header Object
        Input header.

    outhdr: pyfits Header Object
        Output header.

    subarray: boolean
        True if the exposure used one or more subarrays.
    """
    if subarray:
        outhdr['nsubarry'] = inhdr.get('nsubarry', 0)
    else:
        outhdr['nsubarry'] = 0
    for i in range(8):
        x_corner_kwd = 'corner%1dx' % i
        y_corner_kwd = 'corner%1dy' % i
        x_size_kwd = 'size%1dx' % i
        y_size_kwd = 'size%1dy' % i
        outhdr[x_corner_kwd] = inhdr.get(x_corner_kwd, -1)
        outhdr[y_corner_kwd] = inhdr.get(y_corner_kwd, -1)
        outhdr[x_size_kwd] = inhdr.get(x_size_kwd, -1)
        outhdr[y_size_kwd] = inhdr.get(y_size_kwd, -1)


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 is_vcf(fname):
    """Convenience method to check if a file is a vcf file.

    >>> is_vcf("./foo")
    False
    >>> is_vcf("./foo.vcf")
    True
    >>> is_vcf("./foo.vcf.GZ")
    True
    """
    return fname.lower().endswith('.vcf') or fname.lower().endswith('.vcf.gz')


@classmethod
def update(cls):
    """
        Update model objects, used to map some external behavior
        from the system. This method will be called everytime the
        objects are accessed. This way you can update  objects after
        system changes (for example network interfaces)
        """
    pass


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

        :param GuestAdminSignedOutViaTrustedTeamsDetails val:
        :rtype: EventDetails
        """
    return cls('guest_admin_signed_out_via_trusted_teams_details', val)


def edges(ax, **kw):
    """
    Plot regular edges and rays (edges whose one endpoint is at infinity)
    """
    verts = kw['vertices']
    edges = kw['edges']
    for beg, end in edges:
        x0, y0 = verts[(beg), :]
        x1, y1 = verts[(end), :]
        ax.fill([x0, x1], [y0, y1], facecolor='none', edgecolor='k',
            linewidth=0.5)
    if 'ray_origins' not in kw or 'ray_directions' not in kw:
        return
    lim = ax.axis()
    ray_origin = kw['ray_origins']
    ray_direct = kw['ray_directions']
    for beg, (vx, vy) in zip(ray_origin.flatten(), ray_direct):
        x0, y0 = verts[(beg), :]
        scale = 100.0
        x1, y1 = x0 + scale * vx, y0 + scale * vy
        ax.fill([x0, x1], [y0, y1], facecolor='none', edgecolor='k',
            linewidth=0.5)
    ax.axis(lim)


def p_class_entry_type(p):
    """class_entry_type : CLASS
                        | ABSTRACT CLASS
                        | FINAL CLASS"""
    if len(p) == 3:
        p[0] = p[1].lower()


def islower(text):
    """
    Checks if  all cased characters in ``text`` are lowercase and there is at least one cased character.

    Cased characters are defined by the Unicode standard.  All alphabetic characters in the
    ASCII character set are cased.

    :param text: The string to check
    :type text:  ``str``

    :return: True if all cased characters in ``text`` are lowercase and there is at least one cased character, False otherwise.
    :rtype:  ``bool``
    """
    assert isinstance(text, str), '%s is not a string' % text
    return text.islower()


def getArguments(parser):
    """Provides additional validation of the arguments collected by argparse."""
    return parser.parse_args()


def get_ghost(coll_name, oid):
    """Get the ghosted version of the object.
        """


def modify_target_group_attributes(TargetGroupArn=None, Attributes=None):
    """
    Modifies the specified attributes of the specified target group.
    See also: AWS API Documentation

    Examples
    This example sets the deregistration delay timeout to the specified value for the specified target group.
    Expected Output:

    :example: response = client.modify_target_group_attributes(
        TargetGroupArn='string',
        Attributes=[
            {
                'Key': 'string',
                'Value': 'string'
            },
        ]
    )

    :type TargetGroupArn: string
    :param TargetGroupArn: [REQUIRED]
            The Amazon Resource Name (ARN) of the target group.

    :type Attributes: list
    :param Attributes: [REQUIRED]
            The attributes.
            (dict) --Information about a target group attribute.
            Key (string) --The name of the attribute.
            deregistration_delay.timeout_seconds - The amount time for Elastic Load Balancing to wait before changing the state of a deregistering target from draining to unused . The range is 0-3600 seconds. The default value is 300 seconds.
            stickiness.enabled - Indicates whether sticky sessions are enabled. The value is true or false .
            stickiness.type - The type of sticky sessions. The possible value is lb_cookie .
            stickiness.lb_cookie.duration_seconds - The time period, in seconds, during which requests from a client should be routed to the same target. After this time period expires, the load balancer-generated cookie is considered stale. The range is 1 second to 1 week (604800 seconds). The default value is 1 day (86400 seconds).
            Value (string) --The value of the attribute.

    :rtype: dict
    :return: {
        'Attributes': [
            {
                'Key': 'string',
                'Value': 'string'
            },
        ]
    }

    :returns:
    deregistration_delay.timeout_seconds - The amount time for Elastic Load Balancing to wait before changing the state of a deregistering target from draining to unused . The range is 0-3600 seconds. The default value is 300 seconds.
    stickiness.enabled - Indicates whether sticky sessions are enabled. The value is true or false .
    stickiness.type - The type of sticky sessions. The possible value is lb_cookie .
    stickiness.lb_cookie.duration_seconds - The time period, in seconds, during which requests from a client should be routed to the same target. After this time period expires, the load balancer-generated cookie is considered stale. The range is 1 second to 1 week (604800 seconds). The default value is 1 day (86400 seconds).

    """
    pass


def sock_type(sock):
    """
    We can thank Linux for this abomination of a function.

    As of Linux 2.6.27, bits 11-32 of the socket type are flags. This
    change was made with a complete lack of consideration for the fact
    that socket types are not flags, but are in fact "symbolic
    constants" represented on all major operating systems by sequential
    numbers. It is impossible to distinguish between some types (i.e.
    SOCK_STREAM and SOCK_RAW) using a simple bitwise AND, as one would
    expect from a flag value.

    To get around this, we treat the first 9 bits as the "real" type.
    """
    return sock.type & 1023


def get_camn(results, cam, remote_timestamp=None, frame=None):
    """helper function to get camn given timestamp or frame number

    last used 2006-05-17

    """
    if not isinstance(cam, str):
        camn = cam
        return camn
    this_cam_id = cam
    possible_camns = []
    for row in results.root.cam_info:
        if row['cam_id'] == this_cam_id:
            possible_camns.append(row['camn'])
    table = results.root.data2d_camera_summary
    for row in table.where('cam_id==this_cam_id'):
        camn = None
        if row['camn'] in possible_camns:
            if remote_timestamp is not None:
                if row['start_timestamp'] <= remote_timestamp <= row[
                    'stop_timestamp']:
                    if camn is not None:
                        if camn != row['camn']:
                            raise RuntimeError(
                                'Found camn already! (Is frame from different run than timestamp?)'
                                )
                    camn = row['camn']
            if frame is not None:
                if row['start_frame'] <= frame <= row['stop_frame']:
                    if camn is not None:
                        if camn != row['camn']:
                            raise RuntimeError(
                                'Found camn already! (Is frame from different run than timestamp?)'
                                )
                    camn = row['camn']
    if camn is None:
        raise RuntimeError('could not find frame or timestamp')
    return camn


@classmethod
def get_list(cls, id_list):
    """Get a list of instance of an entity by a list of IDs or slugs.

        Args:
            id_list (list):
                List of sD or slugs of entities in the catalog to retrieve instances.

        Raises:
            CatalogError: if there's a problem when connecting to the catalog or no entities are found.

        """
    return cls._entity_repo.get_by_id_list(id_list)


def ascii_lower(string):
    """Transform (only) ASCII letters to lower case: A-Z is mapped to a-z.

    :param string: An Unicode string.
    :returns: A new Unicode string.

    This is used for `ASCII case-insensitive
    <http://whatwg.org/C#ascii-case-insensitive>`_ matching.

    This is different from the :meth:`~py:str.lower` method of Unicode strings
    which also affect non-ASCII characters,
    sometimes mapping them into the ASCII range:

    >>> keyword = u'Bac\\N{KELVIN SIGN}ground'
    >>> assert keyword.lower() == u'background'
    >>> assert ascii_lower(keyword) != keyword.lower()
    >>> assert ascii_lower(keyword) == u'bac\\N{KELVIN SIGN}ground'

    """
    return string.encode('utf8').lower().decode('utf8')


def max_inmask(maxima, mask, withvalue=1.0):
    """Get the maxima located where the mask have a specific value (e.g., 1)

    Parameters
    ----------
    maxima : pd.DataFrame
        Pandas DataFrame with the information of the maxima. Has to contain at least the column 'Pixel number'.
    mask : np.ndarray
        A Healpix map to be used as mask. **Its ``nside`` should be the same as the original map.**
    withvalue : float, optional
        Value to be matched. Only maxima that have this value on the ``mask`` will be returned.

    Returns
    -------
    pd.DataFrame
        The same Pandas DataFrame as the input ``maxima``, but containing only the maxima located at points where the
        ``mask`` has the value ``withvalue`` (1 by default).
    """
    filtered_maxima = maxima.loc[mask[maxima['Pixel number']] == withvalue]
    return filtered_maxima


def qn(namespace, tag_name):
    """Return the qualified name for a given namespace and tag name

    This is the ElementTree representation of a qualified name
    """
    return '{%s}%s' % (namespace, tag_name)


def elsymb_to_Z(elsymb):
    """
  Converts element symbol to nuclear charge, e.g. "C" -> 6

  Parameters
  ----------

  elsymb : str
    Element symbol, e.g. "C". Case insensitive.

  Returns
  -------
  int
    Z for the ion. (e.g. 6 for C)
  """
    ellist = ('h', 'he', 'li', 'be', 'b', 'c', 'n', 'o', 'f', 'ne', 'na',
        'mg', 'al', 'si', 'p', 's', 'cl', 'ar', 'k', 'ca', 'sc', 'ti', 'v',
        'cr', 'mn', 'fe', 'co', 'ni', 'cu', 'zn', 'ga', 'ge', 'as', 'se',
        'br', 'kr', 'rb', 'sr', 'y', 'zr', 'nb', 'mo', 'tc', 'ru', 'rh',
        'pd', 'ag', 'cd', 'in', 'sn', 'sb', 'te', 'i ', 'xe', 'cs', 'ba',
        'la', 'ce', 'pr', 'nd', 'pm', 'sm', 'eu', 'gd', 'tb', 'dy', 'ho',
        'er', 'tm', 'yb', 'lu', 'hf', 'ta', 'w', 're', 'os', 'ir', 'pt',
        'au', 'hg', 'tl', 'pb', 'bi', 'po', 'at', 'rn', 'fr', 'ra', 'ac',
        'th', 'pa', 'u')
    try:
        ind = ellist.index(elsymb.lower().strip())
    except ValueError:
        print("elsymb_to_z0 error: invalid element symbol '" + elsymb +
            "', returning -1")
        ind = -1
    return ind + 1


def _new_IntervalIndex(cls, d):
    """
    This is called upon unpickling, rather than the default which doesn't have
    arguments and breaks __new__.
    """
    return cls.from_arrays(**d)


def describe_egress_only_internet_gateways(DryRun=None,
    EgressOnlyInternetGatewayIds=None, MaxResults=None, NextToken=None):
    """
    Describes one or more of your egress-only Internet gateways.
    See also: AWS API Documentation

    :example: response = client.describe_egress_only_internet_gateways(
        DryRun=True|False,
        EgressOnlyInternetGatewayIds=[
            'string',
        ],
        MaxResults=123,
        NextToken='string'
    )

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

    :type EgressOnlyInternetGatewayIds: list
    :param EgressOnlyInternetGatewayIds: One or more egress-only Internet gateway IDs.
            (string) --

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

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

    :rtype: dict
    :return: {
        'EgressOnlyInternetGateways': [
            {
                'EgressOnlyInternetGatewayId': 'string',
                'Attachments': [
                    {
                        'VpcId': 'string',
                        'State': 'attaching'|'attached'|'detaching'|'detached'
                    },
                ]
            },
        ],
        'NextToken': 'string'
    }

    """
    pass


def _maybeint(maybe):
    """
    If it is an int, make it an int.  otherwise leave it as a string.

    >>> _maybeint("12")
    12

    >>> _maybeint("cow")
    'cow'
    """
    try:
        maybe = int(maybe)
    except ValueError:
        pass
    return maybe


def add_task_name(apps, schema_editor):
    """
    This function loops through all ScheduledTask objects and sets the task_name to a unique value, based on the
    existing task attribute, e.g.
    myapp.mytasks.hello-world
    myapp.mytasks.hello-world-1
    myapp.mytasks.hello-world-2
    """
    ScheduledTask = apps.get_model('carrot', 'ScheduledTask')
    db_alias = schema_editor.connection.alias
    index = 0
    for t in ScheduledTask.objects.using(db_alias).filter(task_name=''):
        index += 1
        task_name = '%s-%i' % (t.task, index)
        t.task_name = task_name
        t.save()


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 backtrack(end, start, visited):
    """ Return a tuple of nodes from `start` to `end` by recursively looking up
    the current node in `visited`. `visited` is a dictionary of one-way edges
    between nodes.
    """
    path = [end]
    node = end
    while node != start:
        node = visited[node]
        path.append(node)
    return tuple(reversed(path))


@classmethod
def zeros(cls, *shape):
    """Return a sparse N-dim array of zeros."""
    return cls({}, shape)


@staticmethod
def get_evaluation_tags():
    """ Returns a list of fields that are computed during .update() to display in the stats"""
    return ['rl_policy_loss', 'rl_value_loss', 'rl_draw_loss',
        'rl_entropy_loss', 'rl_total_loss']


def pytest_terminal_summary(terminalreporter, exitstatus, config):
    """Add a section to terminal summary reporting.

    :param _pytest.terminal.TerminalReporter terminalreporter: the internal terminal reporter object
    :param int exitstatus: the exit status that will be reported back to the OS
    :param _pytest.config.Config config: pytest config object

    .. versionadded:: 4.2
        The ``config`` parameter.
    """


def warning_auth_in_get(request):
    """
    Проверка наличия данных авторизации в GET-запросах.
    Выполняется с кешированием проверки в атрибут `_warning_auth_in_get`
    запроса.
    """
    if request.method != 'GET':
        return False
    if hasattr(request, '_warning_auth_in_get'):
        return request._warning_auth_in_get
    request._warning_auth_in_get = bool('username' in request.GET or
        'password' in request.GET)
    return request._warning_auth_in_get


def RunModels(models, record):
    """
    Return a single record (dict) with results from all models

    :param list models: list of 'Model'; the models which will be run
    :param dict record: record to which models will be applied
    """
    record['results'] = {}
    for model in models:
        data = record['data'][model.name][model.version]
        x = model.execute(data=data, results=record['results'])
        record['results'] = x
    return record


def __get_int(section, name):
    """Get the forecasted int from json section."""
    try:
        return int(section[name])
    except (ValueError, TypeError, KeyError):
        return 0


def wl_lockValues(killinvalids=0):
    """ Returns a sequence of locks.  if 'killinvalids' is true,
        invalid locks will be deleted"""


def cache_inc(key, value=1, expires=None, cache=None):
    """Increments the specified key value by the specified value.

    * http://uwsgi.readthedocs.io/en/latest/Changelog-1.9.9.html#math-for-cache

    :param str|unicode key:

    :param int value:

    :param int expires: Expire timeout (seconds).

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

    :rtype: bool
    """
    return False


@staticmethod
def protocol_a_checksum(data):
    """calculate a checksum for given data

        Checksum for protocol A is a binary sum of the rest of the packet

        :param data: input data
        :type data: bytes
        :returns: checksum as a hex string
        :rtype: str
        """
    s = 0
    for c in data:
        s += c
    return '%02X' % (s % 255)


def git_version():
    """Return the git version tuple (major, minor, patch)"""
    from git import Git
    g = Git()
    return g.version_info


def string_to_compose(string):
    """Convert an SVG string to a ``svgutils.compose.SVG``."""
    from svgutils.compose import SVG
    from svgutils.transform import fromstring
    svg_figure = fromstring(string)
    element = SVG()
    element.root = svg_figure.getroot().root
    return element, list(map(float, svg_figure.get_size()))


def isIpAvailable(ipaddr, chuteStor, name):
    """
    Make sure this IP address is available.

    Checks the IP addresses of all zones on all other chutes, makes sure
    subnets are not the same.
    """
    chList = chuteStor.getChuteList()
    for ch in chList:
        if name != ch.name:
            otherIPs = ch.getChuteIPs()
            if ipaddr in otherIPs:
                return False
    return True


def get_float_arg(r, name, default=None):
    """
    Retrieve argument from :attr:`flask:flask.request` and convert to float

    :param r: :attr:`flask:flask.request`
    :param name: argument name
    :type: str
    :param default: default value if parameter is non-existent, defaults to None
    :return: float argument value
    """
    val = r.args.get(name)
    if val is None or val == '':
        return default
    else:
        try:
            return float(val)
        except BaseException:
            return default


def cacheattr(obj, name, function):
    """add and cache an object member which is the result of a given function.
    This is for implementing lazy getters when the function call is expensive."""
    if hasattr(obj, name):
        val = getattr(obj, name)
    else:
        val = function()
        setattr(obj, name, val)
    return val


def extract_auto_refresh_profiles(profiles):
    """Pull out any profiles with the prefix 'auto-refresh-' in the name.

    Parameters
    ----------
    - profiles - the profiles read from the aws credentials file

    Returns
    -------
    A dict of profiles that are prefixed by 'auto-refresh-' in the name.
    """
    autoRefreshProfiles = {}
    for profile in profiles:
        if 'auto-refresh-' in profile:
            autoRefreshProfiles[profile] = profiles[profile]
    return autoRefreshProfiles


@classmethod
def from_nds2_buffers(cls, buffers, scaled=None, copy=True, **metadata):
    """Construct a new dict from a list of `nds2.buffer` objects

        **Requires:** |nds2|_

        Parameters
        ----------
        buffers : `list` of `nds2.buffer`
            the input NDS2-client buffers to read

        scaled : `bool`, optional
            apply slope and bias calibration to ADC data, for non-ADC data
            this option has no effect.

        copy : `bool`, optional
            if `True`, copy the contained data array to new  to a new array

        **metadata
            any other metadata keyword arguments to pass to the `TimeSeries`
            constructor

        Returns
        -------
        dict : `TimeSeriesDict`
            a new `TimeSeriesDict` containing the data from the given buffers
        """
    tsd = cls()
    for buf in buffers:
        tsd[buf.channel.name] = tsd.EntryClass.from_nds2_buffer(buf, scaled
            =scaled, copy=copy, **metadata)
    return tsd


def tree(strings, separator='.'):
    """Return a tree of strings as a nested dictionary.

    The levels of hierarchy in each string are marked with *separator*.
    The keys in the dictionary are the sub-branch names.  The value at the
    end of each branch is the full string.

    **Arguments:**

    - *strings*: List of strings

    - *separator*: String that marks a level of hierarchy

    **Example:**

    >>> tree(['a.b.c', 'd.e', 'd.f']) # doctest: +SKIP
    {'a': {'b': {'c': 'a.b.c'}}, 'd': {'e': 'd.e', 'f': 'd.f'}}

    .. testcleanup::

       >>> tree(['a.b.c', 'd.e', 'd.f']) == {'a': {'b': {'c': 'a.b.c'}}, 'd': {'e': 'd.e', 'f': 'd.f'}}
       True
    """
    root = {}
    for string in strings:
        branch = root
        elements = string.split(separator)
        for element in elements[:-1]:
            if element not in branch:
                branch[element] = {}
            branch = branch[element]
        branch[elements[-1]] = string
    return root


def run_length_decode(integers):
    """Expands a list of integers where every second integer is a count of the
    integer before it.

    :param list integers: the integers to decode.
    :rtype: ``list``"""
    x = []
    for index, val in enumerate(integers[::2]):
        x += [val] * integers[1::2][index]
    return x


def humanize_bytes(bytes, raw=False, precision=1):
    """Return a humanized string representation of a number of bytes.

    >>> humanize_bytes(1)
    '1 byte'
    >>> humanize_bytes(2)
    '2.0 bytes'
    >>> humanize_bytes(1024)
    '1.0 kB'
    >>> humanize_bytes(1024*123)
    '123.0 kB'
    >>> humanize_bytes(1024*12342)
    '12.1 MB'
    >>> humanize_bytes(1024*12342, precision=2)
    '12.05 MB'
    >>> humanize_bytes(1024*1234, precision=2)
    '1.21 MB'
    >>> humanize_bytes(1024*1234*1111, precision=2)
    '1.31 GB'
    >>> humanize_bytes(1024*1234*1111)
    '1.3 GB'
    >>> humanize_bytes(1024, True)
    1024
    """
    if raw:
        return bytes
    abbrevs = (1 << 50, 'PB'), (1 << 40, 'TB'), (1 << 30, 'GB'), (1 << 20, 'MB'
        ), (1 << 10, 'kB'), (1, 'bytes')
    if bytes == 1:
        return '1 byte'
    for factor, suffix in abbrevs:
        if bytes >= factor:
            break
    return '%.*f %s' % (precision, bytes / factor, suffix)


def unfiltered():
    """Obtain an unfiltered/raw view of this repo."""


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

    The ".dev0" means dirty.

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


@classmethod
def createFromToken(cls, token, context=None, onMissingClass=None):
    """
        Create a serializable instance from an arbitrary storage token
        @param token: Storage token
        @param context: Mutable context for the loading process
        """
    anId = token.getId()
    if context and anId in context:
        instance = context[anId]
    else:
        classId = token.getClassId()
        aClass = cls._getFactoryClass(classId)
        if aClass is not None:
            instance = aClass()
            instance.initializeFromToken(token, context)
        else:
            if onMissingClass is None:
                onMissingClass = cls.defaultOnMissingClass
            instance = onMissingClass(token)
    return instance


def join_uuids(uuid_parts):
    """
    Join a list of UUIDs to a single string.
    :param uuid_parts: Sequence of strings, each containing a UUID.
    :return: String with joined UUIDs.
    """
    return '.'.join(uuid_parts)


def getAvailableYears(domain):
    """Return the available years for given domain.
        """


@classmethod
def get_name(cls):
    """
        Return the name of the resource. This is the model_name for almost all resources.

        :return: (str) lowercase model name
        """
    return cls._meta.model_name


def get_top_k_edges(method_ranks, k):
    """
    Return the top k edges for a given method.

    Args:
        method_ranks (pandas.Series): edges ranks for a given method, where each
            element represents the rank of a given edge
        k (int): top k edges to select

    Returns:
        list: list of the top k edges

    Example:
        >>> import pandas as pd
        >>> method_ranks = pd.Series([1,4,2,3], index=['gene1_gene2',
                                                       'gene1_gene3',
                                                       'gene3_gene1',
                                                       'gene3_gene2'])
        >>> edges = get_top_k_edges(method_ranks,2)
        >>> edges
        ['gene1_gene2', 'gene3_gene1']

    """
    return list(method_ranks.sort_values().index)[:k]


def draw_preview(snap: bool=False):
    """Draw preview of current sketch stroke (internal use)

    :param snap: Snap
    :type snap: bool
    """
    pass


def islocked(instance):
    """
    Return ``True`` if ``instance`` is locked.

    This function can be used on an instance of the `ReadOnly` class or an
    instance of any other class implemented the same locking API.

    For example:

    >>> readonly = ReadOnly()
    >>> islocked(readonly)
    False
    >>> readonly.__lock__()
    >>> islocked(readonly)
    True

    Also see the `lock()` function.

    :param instance: The instance of `ReadOnly` (or similar) to interrogate.
    """
    assert hasattr(instance, '__lock__') and callable(instance.__lock__
        ), 'no __lock__() method: %r' % instance
    return instance.__islocked__()


def htmlquote(text):
    """
    Encodes `text` for raw use in HTML.

        >>> htmlquote(u"<'&\\">")
        u'<'&">'
    """
    text = text.replace(u'&', u'&')
    text = text.replace(u'<', u'<')
    text = text.replace(u'>', u'>')
    text = text.replace(u"'", u''')
    text = text.replace(u'"', u'"')
    return text


def _get_header_length(read_file, ext='text', comment='#'):
    """
    Determines the amount of rows that are part of the header in a file that is
    already opened and readable

    Parameters
    ----------
    read_file : opened file
        an opened file object that is readable
    ext : str
        the extension (in words) of the file the headerlength needs to be found
        for
    comment : str
        comment symbol used in the files

    Returns
    -------
    headerlength : int
        the amount of rows that are part of the header in the read file

    """
    headerlength = 0
    header_test = comment
    counter = 0
    if ext == 'excel' or ext == 'zrx':
        while header_test == comment:
            header_test = str(read_file.sheet_by_index(0).cell_value(
                counter, 0))[0]
            headerlength += 1
            counter += 1
    elif ext == 'text' or ext == 'csv':
        while header_test == comment:
            header_test = read_file.readline()[0]
            headerlength += 1
    return headerlength - 1


@classmethod
def fromfile(cls, fh, edv=None, verify=True):
    """Read a frame from a filehandle.

        Parameters
        ----------
        fh : filehandle
            From which the header and payload are read.
        edv : int, False, or None, optional
            Extended Data Version.  `False` is for legacy headers.  If `None`
            (default), it will be determined from the words themselves.
        verify : bool, optional
            Whether or not to do basic assertions that check the integrity
            (e.g., that channel information and whether or not data are complex
            are consistent between header and data).  Default: `True`.
        """
    header = cls._header_class.fromfile(fh, edv, verify)
    payload = cls._payload_class.fromfile(fh, header=header)
    return cls(header, payload, verify=False)


def addSource(name, data):
    """Add a new data source to the manager.

        A data source can be assigned to generator plugins.
        """


def make_time_index_intervals(twitter_df, col='date', start=None, end=None,
    freq='CBH', num_offset=1):
    """Takes a df, rounds first timestamp down to nearest hour, last timestamp rounded up to hour.
    Creates 30 minute intervals based that encompass all data."""
    import pandas as pd
    if freq == 'CBH':
        freq = pd.offsets.CustomBusinessHour(n=num_offset, start='09:30',
            end='16:30')
        ofst = pd.offsets.CustomBusinessHour(n=num_offset, start='09:30',
            end='16:30')
        ofst_early = pd.offsets.CustomBusinessHour(n=-num_offset, start=
            '09:30', end='16:30')
    if freq == 'T':
        ofst = pd.offsets.Minute(n=num_offset)
        ofst_early = pd.offsets.Minute(n=-num_offset)
    if freq == 'H':
        ofst = pd.offsets.Hour(n=num_offset)
        ofst_early = pd.offsets.Hour(n=-num_offset)
    if start is None:
        start_idx = ofst.rollback(twitter_df[col].iloc[0])
    else:
        start_idx = pd.to_datetime(start)
    if end is None:
        end_idx = ofst.rollforward(twitter_df[col].iloc[-1])
    else:
        end_idx = pd.to_datetime(end)
    time_range = pd.date_range(start=start_idx, end=end_idx, freq=freq)
    time_intervals = pd.interval_range(start=start_idx, end=end_idx, freq=
        freq, name='interval_index', closed='left')
    return time_intervals


def iconcat(a, b):
    """Same as a += b, for a and b sequences."""
    if not hasattr(a, '__getitem__'):
        msg = "'%s' object can't be concatenated" % type(a).__name__
        raise TypeError(msg)
    a += b
    return a


@classmethod
def parse_service_table(cls, tablename):
    """Given tablename returns (service, name)."""
    pieces = tablename.split(':')
    if len(pieces) == 1:
        table = pieces[0]
        service = None
    else:
        service = pieces[0]
        table = ':'.join(pieces[1:])
    return service, table


def __(string):
    """dummy function to fake the translation"""
    return string


def col_defn(col_data, i):
    """
    returns individual column creation statement; excluding indexes and keys

    used with iterations, i = str(i) where i is index of current iterations
    """
    type_field = col_data['type_' + i]
    length_field = col_data['length_' + i]
    name_field = col_data['name_' + i]
    key_field = col_data['key_' + i]
    sql_stmt = ' {name} {type}'.format(name=name_field, type=type_field)
    if type_field in ('bit', 'bit varying', 'character varying',
        'character', 'interval'):
        sql_stmt += '({length_' + i + '})'
    if length_field and (type_field.startswith('time') or type_field.
        startswith('timestamp')):
        _in = 9 if type_field.startswith('timestamp') else 4
        sql_stmt = ' {name} {type_prefix} ({length}) {type_postfix}'.format(
            type_prefix=type_field[0:_in], length=length_field,
            type_postfix=type_field[_in + 1:])
    sql_stmt += ' NOT NULL' if col_data['not_null_' + i] else ''
    d = {'primary': 'PRIMARY KEY', 'unique': 'UNIQUE', 'index': 'INDEX'}
    if key_field:
        sql_stmt += ' ' + d[key_field] if key_field != 'unique' else ''
    return sql_stmt


def get_urls():
    """
        get_urls() should return a set of patterns to be added to the /servee/ urls.
        """
    return []


def correctivesmooth_bind(modifier: str=''):
    """Bind base pose in Corrective Smooth modifier

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


def _retrieve_device_battery_state(detail):
    """Get the latest state of the sensor."""
    return detail.battery_level


def import_toothpick_picture():
    """Return the stream of the toothpick picture."""
    import pkg_resources
    resource = pkg_resources.resource_stream('gemd.demo', 'toothpick.jpg')
    return resource


def set_deep(instance, path, value):
    """
    Do NOT use this helper in your code.
    It's extremely primitive and wouldn't work properly with most Mappings.
    """
    path = path.split('.')
    for path_segment in path[:-1]:
        if path_segment not in instance:
            instance[path_segment] = {}
        instance = instance[path_segment]
    instance[path[-1]] = value


def as_enum(enum_type, arg):
    """Check if arg is an instance or key of enum_type, and return that enum"""
    if isinstance(arg, enum_type):
        return arg
    try:
        return enum_type[arg]
    except KeyError:
        raise ValueError('{} is not a valid {} enum'.format(arg, enum_type.
            __name__))


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 apply_solution_scale(distance: float=0.0):
    """Apply scale on solution itself to make distance between selected tracks equals to desired

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


def dup_scale(f, a, K):
    """
    Evaluate efficiently composition ``f(a*x)`` in ``K[x]``.

    Examples
    ========

    >>> R, x = ring('x', ZZ)

    >>> R.dup_scale(x**2 - 2*x + 1, ZZ(2))
    4*x**2 - 4*x + 1

    """
    f, n, b = list(f), len(f) - 1, a
    for i in range(n - 1, -1, -1):
        f[i], b = b * f[i], b * a
    return f


def _default_host(host, default_host, default_port):
    """Build a default host string
    """
    if not host:
        host = default_host
    if ':' not in host:
        host = '{}:{}'.format(host, default_port)
    return host


@staticmethod
def interfaces_roles_change_and_tree_was_unsure_and_transitions_to_active(
    interface: 'TreeInterfaceUpstream'):
    """
        Interfaces roles change (NonRoot->Root) AND
        Tree was Unsure and transitions to Active state
        """
    interface.logger.debug(
        'interfaces_roles_change_and_tree_was_unsure_and_transitions_to_active'
        )
    interface.send_my_interest()


@classmethod
def load(cls, filename):
    """
        Loads a WordDictionary object from a vocabulary file.
        """
    words = []
    with open(filename, 'rb') as f:
        for word in f:
            word = word.decode('utf-8').strip()
            if word:
                words.append(word)
    return cls.init_from_wordlist(words)


def add_tags(iterable, *taglist):
    """
    Add tags to each item in ``iterable``. Each tag is added to the ``@tags``
    array, which will be created if required.

    >>> data_in = [{'@message': 'one message'}, {'@message': 'another message'}]
    >>> data_out = add_tags(data_in, 'foo', 'bar')
    >>> [x for x in data_out]
    [{'@message': 'one message', '@tags': ['foo', 'bar']},
     {'@message': 'another message', '@tags': ['foo', 'bar']}]
    """
    k = '@tags'
    for item in iterable:
        try:
            item[k].extend(taglist)
        except (AttributeError, KeyError):
            item[k] = []
            item[k].extend(taglist)
        yield item


def get_root(node):
    """Navigates up the given node and returns the root node."""
    try:
        while node.parent:
            node = node.parent
    except AttributeError:
        pass
    return node


def set_global_variables(args):
    """Copy argparse args into global variables."""
    global print_instances_p
    global print_errors_p
    global files_head_ids
    global files_tail_ids
    global confusions
    global min_count
    global wer_vs_length_p
    print_instances_p = args.print_instances
    print_errors_p = args.print_errors
    files_head_ids = args.head_ids
    files_tail_ids = args.tail_ids
    confusions = args.confusions
    min_count = args.min_word_count
    wer_vs_length_p = args.print_wer_vs_length


@staticmethod
def help_close():
    """Extended help for close method"""
    return (
        'If the current shell is a sub-shell spawned by another Friendly Shell instance, control will return to the parent shell which will continue running'
        )


@classmethod
def _fix_windows(cls, maxw, maxh):
    """
        Fixes all windows for which width or height is specified as 'max'.
        """
    if not cls.WINDOWS:
        return
    for win in cls.WINDOWS:
        if win.WIDTH == 'max':
            win.WIDTH = maxw - win.X
        if win.HEIGHT == 'max':
            win.HEIGHT = maxh - win.Y


@classmethod
def validate(cls, value):
    """
        Raise |ValueError| if *value* is not an assignable value.
        """
    if value not in cls._valid_settings:
        raise ValueError('%s not a member of %s enumeration' % (value, cls.
            __name__))


def _get_content_start_row_index(table: list) ->int:
    """表頭っぽい行にきたらbreakして行番号を取得する"""
    for i in range(len(table)):
        if '属性名' in table[i] or 'データ項目' in table[i]:
            break
    return i


@staticmethod
def get_dict_value(dictionary, path):
    """ Safely get the value of a dictionary given a key path. For
            instance, for the dictionary `{ 'a': { 'b': 1 } }`, the value at
            key path ['a'] is { 'b': 1 }, at key path ['a', 'b'] is 1, at
            key path ['a', 'b', 'c'] is None.

        :param dictionary: a dictionary.
        :param path: the key path.
        :return: The value of d at the given key path, or None if the key
                 path does not exist.
        """
    if len(path) == 0:
        return None
    temp_dictionary = dictionary
    try:
        for k in path:
            temp_dictionary = temp_dictionary[k]
        return temp_dictionary
    except (KeyError, TypeError):
        pass
    return None


def CubicTimeScaling(Tf, t):
    """Computes s(t) for a cubic time scaling

    :param Tf: Total time of the motion in seconds from rest to rest
    :param t: The current time t satisfying 0 < t < Tf
    :return: The path parameter s(t) corresponding to a third-order
             polynomial motion that begins and ends at zero velocity

    Example Input:
        Tf = 2
        t = 0.6
    Output:
        0.216
    """
    return 3 * (1.0 * t / Tf) ** 2 - 2 * (1.0 * t / Tf) ** 3


def iter3d_old(n):
    """
    Generate all possible unordered combinations of vectors i,j,k
    for i,j,k < n
    """
    for i in range(n):
        for j in range(i + 1, n):
            for k in range(j + 1, n):
                yield i, j, k


def rotate_right(x, y):
    """
    Right rotates a list x by the number of steps specified
    in y.

    Examples
    ========

    >>> a = [0, 1, 2]
    >>> rotate_right(a, 1)
    [2, 0, 1]

    """
    if len(x) == 0:
        return []
    y = len(x) - y % len(x)
    return x[y:] + x[:y]


def file_exists(file_path):
    """Check if the full file path exists."""
    try:
        with open(file_path, 'r'):
            return True
    except IOError:
        raise FileExistsError


def is_module(node):
    """Returns whether node is a module node."""
    return node.__class__.__name__ == 'Module'


def check_positive(**params):
    """Check that parameters are positive as expected

    Raises
    ------
    ValueError : unacceptable choice of parameters
    """
    for p in params:
        if params[p] <= 0:
            raise ValueError('Expected {} > 0, got {}'.format(p, params[p]))


@staticmethod
def supportedViews():
    """Overrides :meth:`.ControlMixin.supportedViews`. The
        ``TimeSeriesToolBar`` is only intended to be added to
        :class:`.TimeSeriesPanel` views.
        """
    from fsleyes.views.timeseriespanel import TimeSeriesPanel
    return [TimeSeriesPanel]


def unquote_header_value(value, is_filename=False):
    """Unquotes a header value.  (Reversal of :func:`quote_header_value`).
    This does not use the real unquoting but what browsers are actually
    using for quoting.

    .. versionadded:: 0.5

    :param value: the header value to unquote.
    """
    if value and value[0] == value[-1] == '"':
        value = value[1:-1]
        if not is_filename or value[:2] != '\\\\':
            return value.replace('\\\\', '\\').replace('\\"', '"')
    return value


def _restore_str(unused_name, value):
    """Restores a string key-value pair from a renewal config file.

    :param str unused_name: option name
    :param str value: option value

    :returns: converted option value to be stored in the runtime config
    :rtype: str or None

    """
    return None if value == 'None' else value


def cut_to_sentence(text):
    """
    Cut text to sentences
    """
    sentence = []
    sentences = []
    len_p = len(text)
    pre_cut = False
    for idx, word in enumerate(text):
        sentence.append(word)
        cut = False
        if pre_cut:
            cut = True
            pre_cut = False
        if word in u'。;!?\n':
            cut = True
            if len_p > idx + 1:
                if text[idx + 1] in '.。”"\'“”‘’?!':
                    cut = False
                    pre_cut = True
        if cut:
            sentences.append(sentence)
            sentence = []
    if sentence:
        sentences.append(''.join(list(sentence)))
    return sentences


def format_relative_time(datetime):
    """
    Return a string formatted timedelta of the given datetime with respect to the current datetime

    :param datetime: the datetime to format
    :return: string representation of the relative time since the given datetime
    """
    from aiida.common.utils import str_timedelta
    from aiida.common import timezone
    timedelta = timezone.delta(datetime, timezone.now())
    return str_timedelta(timedelta, negative_to_zero=True, max_num_fields=1)


def do_decoding(s, encoding):
    """
    Helper to decode a *bytes* object, or return the object as-is.

    Parameters
    ----------
    s : bytes | object
    encoding : str
        The encoding to use to decode *s*.

    Returns
    -------
    decoded
        *str* if *s* was *bytes* and the decoding was successful.
        *s* if *s* was not *bytes*.

    """
    try:
        return s.decode(encoding)
    except (AttributeError, TypeError):
        return s


@classmethod
def get_route(klass, id=None):
    """
        Returns the route to the object for id if specified

        """
    if id is not None:
        return '{}/{}{}'.format(klass.BASE_ROUTE, id, klass.ROUTE_SUFFIX)
    else:
        return '{}{}'.format(klass.BASE_ROUTE, klass.ROUTE_SUFFIX)


def _generate_windows_startup_code():
    """
    **NOT YET IMPLEMENTED**

    Add the returned code to your bash profile to automatically generate
    commandline shortcuts every time a new session is started.

    Returns
    -------
    str or unicode
    """
    raise NotImplementedError(
        'Windows commandline shortcuts are not currently supported')


def options(opt):
    """
	Add the ``--with-ruby-archdir``, ``--with-ruby-libdir`` and ``--with-ruby-binary`` options
	"""
    opt.add_option('--with-ruby-archdir', type='string', dest='rubyarchdir',
        help='Specify directory where to install arch specific files')
    opt.add_option('--with-ruby-libdir', type='string', dest='rubylibdir',
        help='Specify alternate ruby library path')
    opt.add_option('--with-ruby-binary', type='string', dest='rubybinary',
        help='Specify alternate ruby binary')


def check_permutation(permutation):
    """
    Check permutation sanity
    :param permutation:
    :return:
    """
    for n in range(len(permutation)):
        if n not in permutation:
            raise ValueError('Invalid permutation')


def _unquote_wrapped_quotes(value):
    """
    Removes wrapping double quotes and any '\\ ' characters. They are usually added to preserve spaces when passing
    value thru shell.

    Examples
    --------
    >>> _unquote_wrapped_quotes('val\\ ue')
    value

    >>> _unquote_wrapped_quotes("hel\\ lo")
    hello

    Parameters
    ----------
    value : str
        Input to unquote

    Returns
    -------
    Unquoted string
    """
    if value and value[0] == value[-1] == '"':
        value = value.strip('"')
    return value.replace('\\ ', ' ').replace('\\"', '"')


def execute_preset(filepath: str='', menu_idname: str=''):
    """Execute a preset

    :param filepath: filepath
    :type filepath: str
    :param menu_idname: Menu ID Name, ID name of the menu this was called from
    :type menu_idname: str
    """
    pass


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

        :param SharedLinkSettingsRemovePasswordType val:
        :rtype: EventType
        """
    return cls('shared_link_settings_remove_password', val)


def interpolate_max_nearest_neighbor(imax, y, window_length):
    """Trivial, nearest-neighbor interpolation."""
    return imax, y[imax]


def user_details(strategy, details, user=None, *args, **kwargs):
    """Update user details using data from provider."""
    if not user:
        return
    changed = False
    protected = ('username', 'id', 'pk', 'email') + tuple(strategy.setting(
        'PROTECTED_USER_FIELDS', []))
    for name, value in details.items():
        if value is None or not hasattr(user, name) or name in protected:
            continue
        current_value = getattr(user, name, None)
        if current_value or current_value == value:
            continue
        changed = True
        setattr(user, name, value)
    if changed:
        strategy.storage.user.changed(user)


def CO2LOGSERVER_OSEM_BOX_REDIRECT(box):
    """
    This function is called with the value of :any:`CO2LOGSERVER_OSEM_BOX_COL`
    as argument to determine whether this senseBox should be considered for
    OpenSenseMap upload. By default, this function returns ``True`` for any
    box, so any box will be redirected to the OpenSenseMap.
    """
    return True


def sort(results, key):
    """sort results on a key"""


def parabolic_turning_point(y):
    """
    Find the location of the turning point for a parabola
    ``y(x) = ax^2 + bx + c``, given input values ``y(-1), y(0), y(1)``.
    The maximum is located at ``x0 = -b / 2a``. Assumes
    that the input array represents an equally spaced sampling at the
    locations ``y(-1), y(0) and y(1)``.

    Parameters
    ----------
    y : `numpy.ndarray`
        A one dimensional numpy array of shape "3" with entries that sample the
        parabola at "-1", "0", and "1".

    Returns
    -------
    `float`
        A float, the location of the parabola maximum.
    """
    numerator = -0.5 * y.dot([-1, 0, 1])
    denominator = y.dot([1, -2, 1])
    return numerator / denominator


def strdict_to_dict(value):
    """
    Convert libcomps StrDict type object to standard dict.

    Args:
        value: a libcomps StrDict

    Returns:
        lang_dict: a dict

    """
    lang_dict = {}
    if len(value):
        for i, j in value.items():
            lang_dict[i] = j
    return lang_dict


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 draw_text(text, axes, loc, align, fontsize=16, **kwargs):
    """Draw arbitrary text strings at (x, y) on the chosen axes.

    :param text: text to draw
    :type text: str
    :param axes: axes to plot on
    :type axes: str
    :param loc: x and y position of text
    :type loc: tuple(float)
    :param align: horizontal and vertical alignment of text
    :type align: tuple(str)
    :param fontsize: fontsize of legend contents
    :type fontsize: float

    :Keyword Arguments:
        * **colour** (*str*) -- set text colour
        * **transform** (*str*) -- use data or axes coordinates
    """
    interpreted_kwargs = {'ha': align[0], 'va': align[1]}
    interpreted_kwargs['color'] = kwargs.pop('colour', 'black')
    interpreted_kwargs['transform'] = {'data': axes.transData, 'axes': axes
        .transAxes}[kwargs.pop('coordinates', 'axes')]
    axes.text(loc[0], loc[1], text, fontsize=fontsize, **interpreted_kwargs)


def toString(ol):
    """
        from elist.elist import *
        ol = [1,2,3,4]
        toString(ol)
    """
    return ol.__str__()


def set_prefs(prefs):
    """This function is called before opening the project"""
    prefs['ignored_resources'] = ['*.pyc', '*~', '.ropeproject', '.hg',
        '.svn', '_svn', '.git', '.tox', '.env', 'env', 'venv',
        'node_modules', 'bower_components']
    prefs['save_objectdb'] = True
    prefs['compress_objectdb'] = False
    prefs['automatic_soa'] = True
    prefs['soa_followed_calls'] = 0
    prefs['perform_doa'] = True
    prefs['validate_objectdb'] = True
    prefs['max_history_items'] = 32
    prefs['save_history'] = True
    prefs['compress_history'] = False
    prefs['indent_size'] = 4
    prefs['extension_modules'] = []
    prefs['import_dynload_stdmods'] = True
    prefs['ignore_syntax_errors'] = False
    prefs['ignore_bad_imports'] = False
    prefs['prefer_module_from_imports'] = False
    prefs['split_imports'] = False
    prefs['pull_imports_to_top'] = True
    prefs['sort_imports_alphabetically'] = False
    prefs['type_hinting_factory'
        ] = 'rope.base.oi.type_hinting.factory.default_type_hinting_factory'


def make_X_y_timeseries_data(data, x_window=35, verbose=2, as_array=True):
    """Creates an X and Y time sequence trianing set from a pandas Series.
    - X_train is a an array with x_window # of samples for each row in X_train
    - y_train is one value per X_train window: the next time point after the X_window.
    Verbose determines details printed about the contents and shapes of the data.

    # Example Usage:
    X_train, y_train = make_X_y_timeseries(df['price'], x_window= 35)
    print( X_train[0]]):
    # returns: arr[X1,X2...X35]
    print(y_train[0])
    # returns  X36
    """
    import numpy as np
    import pandas as pd
    if any(data.isna()):
        raise Exception('Function does not accept null values')
    if verbose > 0:
        print(f'Input Range: {np.min(data)} - {np.max(data)}')
        print(f'Input Shape: {np.shape(data)}\n')
    time_index_in = data.index
    time_index = data.index[x_window:]
    X_train, y_train = [], []
    check_time_index = []
    for i in range(x_window, data.shape[0]):
        check_time_index.append([data.index[i - x_window], data.index[i]])
        X_train.append(data.iloc[i - x_window:i])
        y_train.append(data.iloc[i])
    if as_array == True:
        X_train, y_train = np.array(X_train), np.array(y_train)
    if verbose > 0:
        print(f'\nOutput Shape - X: {X_train.shape}')
        print(f'Output Shape - y: {y_train.shape}')
        print(
            f"""
Timeindex Shape: {np.shape(time_index)}
	Range: {time_index[0]}-{time_index[-1]}"""
            )
        print(f'\tFrequency:', time_index.freq)
    return X_train, y_train, time_index


def cube_project(cube_size: float=1.0, correct_aspect: bool=True,
    clip_to_bounds: bool=False, scale_to_bounds: bool=False):
    """Project the UV vertices of the mesh over the six faces of a cube

    :param cube_size: Cube Size, Size of the cube to project on
    :type cube_size: float
    :param correct_aspect: Correct Aspect, Map UVs taking image aspect ratio into account
    :type correct_aspect: bool
    :param clip_to_bounds: Clip to Bounds, Clip UV coordinates to bounds after unwrapping
    :type clip_to_bounds: bool
    :param scale_to_bounds: Scale to Bounds, Scale UV coordinates to bounds after unwrapping
    :type scale_to_bounds: bool
    """
    pass


def Trid(x):
    """Trid(n == 6) = -50, Trid(n = 10) = -200"""
    n = len(x)
    s1 = 0
    s2 = 0
    for ii in range(n):
        s1 += pow(x[ii] - 1, 2.0)
    for ii in range(1, n):
        s2 += x[ii] * x[ii - 1]
    return s1 - s2


@staticmethod
def configuration():
    """Return the configuration object.

        Applicable to the ThermostatController, SecurityControlPanel, ModeController, RangeController,
        and EventDetectionSensor.
        """
    return []


@staticmethod
def _get_headers(response):
    """Access the headers from an HTTP response.

        Args:
            response (~requests.Response): The HTTP response object.

        Returns:
            ~requests.structures.CaseInsensitiveDict: The header mapping (keys
            are case-insensitive).
        """
    return response.headers


def precision(labels, predictions):
    """
    measure for false positives predictions.
    """
    from sklearn.metrics import precision_score
    return precision_score(labels, predictions, average='macro', pos_label=None
        )


def _sub(lhs=None, rhs=None, name=None, attr=None, out=None, **kwargs):
    """Subtracts arguments element-wise.

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

       - elemwise_sub(row_sparse, row_sparse) = row_sparse
       - elemwise_sub(csr, csr) = csr
       - elemwise_sub(default, csr) = default
       - elemwise_sub(csr, default) = default
       - elemwise_sub(default, rsp) = default
       - elemwise_sub(rsp, default) = default
       - otherwise, ``elemwise_sub`` generates output with default storage

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

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

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


@classmethod
def match_header(cls, header):
    """
        This is an abstract type that implements the shared functionality of
        the ASCII and Binary Table HDU types, which should be used instead of
        this.
        """
    raise NotImplementedError


@classmethod
def converted(cls, image):
    """given an Image-compatible object,
        returns a new M4A_ILST_COVR_Data_Atom object"""
    return cls(0, 0, image.data)


def extend_instance(obj, cls):
    """Apply mixins to a class instance after creation."""
    base_cls = obj.__class__
    base_cls_name = obj.__class__.__name__
    obj.__class__ = type(base_cls_name, (cls, base_cls), {})


@classmethod
def patch(cls):
    """
        TODO: Improve docstring and refactor implementation in Hive
        """
    pass


def get_evaluation(EvaluationId=None):
    """
    Returns an Evaluation that includes metadata as well as the current status of the Evaluation .
    See also: AWS API Documentation

    :example: response = client.get_evaluation(
        EvaluationId='string'
    )

    :type EvaluationId: string
    :param EvaluationId: [REQUIRED]
            The ID of the Evaluation to retrieve. The evaluation of each MLModel is recorded and cataloged. The ID provides the means to access the information.

    :rtype: dict
    :return: {
        'EvaluationId': 'string',
        'MLModelId': 'string',
        'EvaluationDataSourceId': 'string',
        'InputDataLocationS3': 'string',
        'CreatedByIamUser': 'string',
        'CreatedAt': datetime(2015, 1, 1),
        'LastUpdatedAt': datetime(2015, 1, 1),
        'Name': 'string',
        'Status': 'PENDING'|'INPROGRESS'|'FAILED'|'COMPLETED'|'DELETED',
        'PerformanceMetrics': {
            'Properties': {
                'string': 'string'
            }
        },
        'LogUri': 'string',
        'Message': 'string',
        'ComputeTime': 123,
        'FinishedAt': datetime(2015, 1, 1),
        'StartedAt': datetime(2015, 1, 1)
    }

    :returns:
    BinaryAUC: A binary MLModel uses the Area Under the Curve (AUC) technique to measure performance.
    RegressionRMSE: A regression MLModel uses the Root Mean Square Error (RMSE) technique to measure performance. RMSE measures the difference between predicted and actual values for a single variable.
    MulticlassAvgFScore: A multiclass MLModel uses the F1 score technique to measure performance.

    """
    pass


@classmethod
def normalize(cls, addrs, default_encoding='utf-8'):
    """
        Normalize one or more addresses of the form string, tuple or
        `EmailContact`) to `EmailContact`s.
        """
    normalized = []
    for addr in addrs:
        if isinstance(addr, cls):
            addr = addr
        elif isinstance(addr, tuple):
            addr = cls(*addr)
        else:
            addr = cls(addr)
        normalized.append(addr)
    return normalized


def _compare_term(minterm, term):
    """
    Return True if a binary term is satisfied by the given term. Used
    for recognizing prime implicants.

    """
    for i, x in enumerate(term):
        if x != 3 and x != minterm[i]:
            return False
    return True


@classmethod
def from_packet(cls, id_, packet):
    """Reads a Tribe from a packet.
		:param id: :class:`int` the tribe's id.
		:param packet: :class:`aiotfm.Packet`"""
    return cls(id_, packet.readUTF(), packet.read32())


def span_context_to_string(trace_id, span_id, parent_id, flags):
    """
    Serialize span ID to a string
        {trace_id}:{span_id}:{parent_id}:{flags}

    Numbers are encoded as variable-length lower-case hex strings.
    If parent_id is None, it is written as 0.

    :param trace_id:
    :param span_id:
    :param parent_id:
    :param flags:
    """
    parent_id = parent_id or 0
    return '{:x}:{:x}:{:x}:{:x}'.format(trace_id, span_id, parent_id, flags)


def obj_box_coord_upleft_to_centroid(coord):
    """Convert one coordinate [x, y, w, h] to [x_center, y_center, w, h].
    It is the reverse process of ``obj_box_coord_centroid_to_upleft``.

    Parameters
    ------------
    coord : list of 4 int/float
        One coordinate.

    Returns
    -------
    list of 4 numbers
        New bounding box.

    """
    if len(coord) != 4:
        raise AssertionError('coordinate should be 4 values : [x, y, w, h]')
    x, y, w, h = coord
    x_center = x + w / 2.0
    y_center = y + h / 2.0
    return [x_center, y_center, w, h]


def allocate_code(code_length=2):
    """
        Ask the wormhole to allocate a nameplate and generate a random code.

        When the code is ready, any Deferreds returned by ``get_code()`` will
        be fired.  Only one of generate_code/set_code/input_code may be used.

        :param int code_length: the number of random words to use.  More
            words means the code is harder to guess.  Defaults to 2.

        :return: None

            ~mod.class
        """


def get_host_details(host_string):
    """Parse a string to get user, protocol, host, etc.

    Args:
        host_string (str): the string
    Returns:
        dict: a dict containing the differnt parts
    """
    if not host_string:
        return {}
    username = None
    protocol = None
    host = None
    port = None
    if '://' in host_string:
        protocol, host = host_string.split('://')
    else:
        host = host_string
    if '@' in host:
        username, host = host.split('@')
    if ':' in host:
        host, port = host.split(':')
    result = {}
    if protocol:
        result['protocol'] = protocol
    if username:
        result['user'] = username
    if host:
        result['host'] = host
    if port:
        result['port'] = int(port)
    return result


@staticmethod
def generate_xor_triple(size):
    """Generate xor triples of given size"""
    raise NotImplementedError('HomomorphicProvider not implemented')


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 extremes(G):
    """Find left most and bottom nodes in the cartesian sense."""
    left_most = sorted(G.nodes(), key=lambda x: x[0])[0]
    bottom = sorted(G.nodes(), key=lambda x: x[1])[0]
    return left_most, bottom


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 SPIN(val):
    """SummaryForPatients"""
    return val


def _resolve_name(name, package, level):
    """Return the absolute name of the module to be imported."""
    if not hasattr(package, 'rindex'):
        raise ValueError("'package' not set to a string")
    dot = len(package)
    for x in range(level, 1, -1):
        try:
            dot = package.rindex('.', 0, dot)
        except ValueError:
            raise ValueError(
                'attempted relative import beyond top-level package')
    return '%s.%s' % (package[:dot], name)


def convert_neg(x):
    """Convert negative hex not correctly converted.

    :param x: int.

    :return: Correct int.
    """
    if x > 9223372036854775808:
        x -= 18446744073709551616
    return x


def file_writeOnce(astr_fileName, astr_val, **kwargs):
    """
    Simple "one-shot" writer. Opens <astr_fileName>
    and saves <astr_val> to file, then closes
    file.
    """
    _str_mode = 'w'
    for key, val in kwargs.items():
        if key == 'mode':
            _str_mode = val
    FILE = open(astr_fileName, _str_mode)
    FILE.write(astr_val)
    FILE.close()


@classmethod
def do_work(cls, message):
    """Class method that defines what the actor should do with the message it received"""
    pass


def default_exc_handler(exc, *args, **kwargs):
    """Default exception handler function: raise exc, ignore other arguments.
    """
    raise exc


@classmethod
def get_selected_path(cls, parse_result):
    """
        This method returns the path to the selected node as a `/` seperated string.

        :param argparse.Namespace parse_result: A namespace object returned by
            :py:meth:`argparse.ArgumentParser.parse_args`.
        :rtype: str
        """
    path_list = cls.get_selected_path_list(parse_result)
    return '/'.join(path_list)


def SGPtGroup(SGData):
    """
    Determine point group of the space group - done after space group symbol has
    been evaluated by SpcGroup. Only short symbols are allowed

    :param SGData: from :func SpcGroup
    :returns: SSGPtGrp & SSGKl (only defaults for Mono & Ortho)
    """
    Flds = SGData['SpGrp'].split()
    if len(Flds) < 2:
        return '', []
    if SGData['SGLaue'] == '-1':
        if '-' in Flds[1]:
            return '-1', [-1]
        else:
            return '1', [1]
    elif SGData['SGLaue'] == '2/m':
        if '/' in SGData['SpGrp']:
            return '2/m', [-1, 1]
        elif '2' in SGData['SpGrp']:
            return '2', [-1]
        else:
            return 'm', [1]
    elif SGData['SGLaue'] == 'mmm':
        if SGData['SpGrp'].count('2') == 3:
            return '222', [-1, -1, -1]
        elif SGData['SpGrp'].count('2') == 1:
            if SGData['SGPolax'] == 'x':
                return '2mm', [-1, 1, 1]
            elif SGData['SGPolax'] == 'y':
                return 'm2m', [1, -1, 1]
            elif SGData['SGPolax'] == 'z':
                return 'mm2', [1, 1, -1]
        else:
            return 'mmm', [1, 1, 1]
    elif SGData['SGLaue'] == '4/m':
        if '/' in SGData['SpGrp']:
            return '4/m', [1, -1]
        elif '-' in Flds[1]:
            return '-4', [-1]
        else:
            return '4', [1]
    elif SGData['SGLaue'] == '4/mmm':
        if '/' in SGData['SpGrp']:
            return '4/mmm', [1, -1, 1, 1]
        elif '-' in Flds[1]:
            if '2' in Flds[2]:
                return '-42m', [-1, -1, 1]
            else:
                return '-4m2', [-1, 1, -1]
        elif '2' in Flds[2:]:
            return '422', [1, -1, -1]
        else:
            return '4mm', [1, 1, 1]
    elif SGData['SGLaue'] in ['3', '3R']:
        if '-' in Flds[1]:
            return '-3', [-1]
        else:
            return '3', [1]
    elif SGData['SGLaue'] == '3mR' or 'R' in Flds[0]:
        if '2' in Flds[2]:
            return '32', [1, -1]
        elif '-' in Flds[1]:
            return '-3m', [-1, 1]
        else:
            return '3m', [1, 1]
    elif SGData['SGLaue'] == '3m1':
        if '2' in Flds[2]:
            return '321', [1, -1, 1]
        elif '-' in Flds[1]:
            return '-3m1', [-1, 1, 1]
        else:
            return '3m1', [1, 1, 1]
    elif SGData['SGLaue'] == '31m':
        if '2' in Flds[3]:
            return '312', [1, 1, -1]
        elif '-' in Flds[1]:
            return '-31m', [-1, 1, 1]
        else:
            return '31m', [1, 1, 1]
    elif SGData['SGLaue'] == '6/m':
        if '/' in SGData['SpGrp']:
            return '6/m', [1, -1]
        elif '-' in SGData['SpGrp']:
            return '-6', [-1]
        else:
            return '6', [1]
    elif SGData['SGLaue'] == '6/mmm':
        if '/' in SGData['SpGrp']:
            return '6/mmm', [1, -1, 1, 1]
        elif '-' in Flds[1]:
            if '2' in Flds[2]:
                return '-62m', [-1, -1, 1]
            else:
                return '-6m2', [-1, 1, -1]
        elif '2' in Flds[2:]:
            return '622', [1, -1, -1]
        else:
            return '6mm', [1, 1, 1]
    elif SGData['SGLaue'] == 'm3':
        if '2' in Flds[1]:
            return '23', []
        else:
            return 'm3', []
    elif SGData['SGLaue'] == 'm3m':
        if '4' in Flds[1]:
            if '-' in Flds[1]:
                return '-43m', []
            else:
                return '432', []
        else:
            return 'm3m', []


def python_seq(start, stop, step, length):
    """
    Converts mathematica sequence tuple to python slice object.

    Based on David Mashburn's generic slice:
    https://gist.github.com/davidmashburn/9764309
    """
    if step == 0:
        return None
    if (start is not None and stop is not None and stop + 1 == start and
        step > 0):
        return slice(0, 0, 1)
    if start == 0 or stop == 0:
        return None
    if start < 0:
        start += length
    else:
        start -= 1
    if stop is None:
        if step < 0:
            stop = 0
        else:
            stop = length - 1
    elif stop < 0:
        stop += length
    else:
        assert stop > 0
        stop -= 1
    if (not 0 <= start < length or not 0 <= stop < length or step > 0 and
        start - stop > 1 or step < 0 and stop - start > 1):
        return None
    if step > 0:
        stop += 1
    else:
        stop -= 1
        if stop == -1:
            stop = None
        if start == 0:
            start = None
    return slice(start, stop, step)


def similar_words(wvs, word, n=10):
    """ Find similar words to word

    Parameters
    ----------
    word : :obj:`str`
        word to find most similar vectors, note it must be within vocabulary
    wvs : :obj:`gensim.model`
        Trained word vector model
    n  : :obj:`int`
        Number of similar words to return.

    Returns
    -------
        most_similar : :obj:`list`
            list of most similar words and their distance
    """
    most_similar = wvs.wv.most_similar(positive=word, topn=n)
    return most_similar


def humanize_bytes(n, precision=2):
    """Return a humanized string representation of a number of bytes.

    Assumes `from __future__ import division`.

    >>> humanize_bytes(1)
    '1 B'
    >>> humanize_bytes(1024, precision=1)
    '1.0 kB'
    >>> humanize_bytes(1024 * 123, precision=1)
    '123.0 kB'
    >>> humanize_bytes(1024 * 12342, precision=1)
    '12.1 MB'
    >>> humanize_bytes(1024 * 12342, precision=2)
    '12.05 MB'
    >>> humanize_bytes(1024 * 1234, precision=2)
    '1.21 MB'
    >>> humanize_bytes(1024 * 1234 * 1111, precision=2)
    '1.31 GB'
    >>> humanize_bytes(1024 * 1234 * 1111, precision=1)
    '1.3 GB'

    """
    abbrevs = [(1 << 50, 'PB'), (1 << 40, 'TB'), (1 << 30, 'GB'), (1 << 20,
        'MB'), (1 << 10, 'kB'), (1, 'B')]
    if n == 1:
        return '1 B'
    for factor, suffix in abbrevs:
        if n >= factor:
            break
    return '%.*f %s' % (precision, n / factor, suffix)


def extract_from_dict(data, path):
    """
    Navigate `data`, a multidimensional array (list or dictionary), and returns
    the object at `path`.
    """
    value = data
    try:
        for key in path:
            value = value[key]
        return value
    except (KeyError, IndexError):
        return ''


@classmethod
def byvolume(cls, base, *parts, **kw):
    """
        Returns an alloy defined by relative volume of the constituents.

        Mixture.byvolume(M1, M2, F2, ..., name='mixture name')
        """
    return cls(base, parts, by='volume', **kw)


def islockable():
    """
        Return False when the current context can never be locked or locking
        is not support in your setup.

        For example in Zope3, z3c.dav.lockingutils.DAVLockmanager depends
        on a persistent zope.locking.interfaces.ITokenUtility utility being
        present and registered. If this utility can not be locked be then
        we can never use this implementation of IDAVLockmanager.
        """


def is_recoverable():
    """Return a boolean, True if the file/dir can be recovered, False if
        not. Unrecoverable files are obviously unhealthy. Non-distributed LIT
        files always return True."""


def get_modification_datetime():
    """Return last modification time for the given version.
        """


def to_upper_camel_case(snake_case_str):
    """Converts snake_case to UpperCamelCase.
    Example:
        foo_bar -> FooBar
    """
    return ''.join(map(str.title, snake_case_str.split('_')))


def get_ensembl_protein_id_from_mapping(data):
    """
    Gets a list of Ensembl IDs from a 'xrefs/symbol/' mapping.

    :param data: Requests object from the Ensembl-UniProt Mapping
    :return: list of Ensembl Protein IDs
    """
    ensps = []
    for entry in data:
        if 'type' in entry and 'id' in entry:
            if entry['type'] == 'translation':
                if entry['id'] not in ensps:
                    ensps.append(entry['id'])
    return ensps


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

        :param SharingChangeLinkPolicyDetails val:
        :rtype: EventDetails
        """
    return cls('sharing_change_link_policy_details', val)


def bio2_to_bioes(tags):
    """
    Convert the BIO2 tag sequence into a BIOES sequence.

    Args:
        tags: a list of tags in BIO2 format

    Returns:
        new_tags: a list of tags in BIOES format
    """
    new_tags = []
    for i, tag in enumerate(tags):
        if tag == 'O':
            new_tags.append(tag)
        elif len(tag) < 2:
            raise Exception(f'Invalid BIO2 tag found: {tag}')
        elif tag[:2] == 'I-':
            if i + 1 < len(tags) and tags[i + 1][:2] == 'I-':
                new_tags.append(tag)
            else:
                new_tags.append('E-' + tag[2:])
        elif tag[:2] == 'B-':
            if i + 1 < len(tags) and tags[i + 1][:2] == 'I-':
                new_tags.append(tag)
            else:
                new_tags.append('S-' + tag[2:])
        else:
            raise Exception(f'Invalid IOB tag found: {tag}')
    return new_tags


def export_type(cls):
    """ Decorator to expose the given class to business_rules.export_rule_data. """
    cls.export_in_rule_data = True
    return cls


def class_to_dict(obj, *args):
    """
    Create dict which contains values of given fields
    :type obj: object
    :type args: list[str]
    :return:
    """
    res = dict()
    for name in args:
        res[name] = getattr(obj, name)
    return res


def stencil_reset_transform(mask: bool=False):
    """Reset the stencil transformation to the default

    :param mask: Modify Mask Stencil, Modify either the primary or mask stencil
    :type mask: bool
    """
    pass


@staticmethod
def _pos_isequal(pos, pos2, key_indices):
    """
        Сравнивает две позиции
        :param pos:
        :param pos2:
        :param key_indices:
        :return:
        """
    for i1, i2 in key_indices:
        if pos[i1] != pos2[i2]:
            return False
    return True


@classmethod
def on_notify(cls, kind, payload, **extra):
    """ 收到给内部通知（notify_clients 发送）"""
    raise NotImplementedError


def lsb(x, n):
    """Return the n least significant bits of x.

    >>> lsb(13, 3)
    5

    """
    return x & 2 ** n - 1


@classmethod
def clear(cls):
    """ Clear all trips """
    cls._all_trips = dict()


def maximum(rule, artifact):
    """Evaluate artifact's value to be maximum of values returned by rule's
    subrules.

    This evaluation function ignores subrule weights.
    """
    m = -1.0
    for i in range(len(rule.R)):
        e = rule.R[i](artifact)
        if e is not None:
            if e > m:
                m = e
    return m


def clean_schema_addresses(list_, udf_stages=None):
    """Clean a address from the addtitionnal layers of SCHEMA.

    Used only when a SCHEMA address must be found in the data to validate

     Parameters :
    -----------
    list_ : a list of string
        address in a nested dict
    udf_stages : a list of additionnal user defined stages (udf)
    Returns :
    ---------
    list
        the same list without SCHEMA intermedaite stages
    """
    skipped_stages = ['properties', 'oneOf']
    if udf_stages is not None:
        for udf_stage in udf_stages:
            skipped_stages.append(udf_stage)
    out = []
    for item in list_:
        if item not in skipped_stages:
            out.append(item)
    return out


def _normpath(path):
    """
    Globus Transfer-specific normalization, based on a careful reading of the stdlib
    posixpath implementation:
      https://github.com/python/cpython/blob/ea0f7aa47c5d2e58dc99314508172f0523e144c6/Lib/posixpath.py#L338

    this must be done without using os.path.normpath to be compatible with CLI calls
    from Windows systems

    Transfer requires forward slashes, even when communicating with Windows systems, so
    we must handle these strings appropriately.
    Note that this does not preserve leading slashes in the same way as python's
    posixpath module -- it's not clear how Transfer would treat such paths and
    non-obvious that we need to allow such usage

    Also, unlike normpath, we want to preserve trailing slashes because they may be
    required
    """
    initial_slash = 1 if path.startswith('/') else 0
    trailing_slash = 1 if path.endswith('/') and path != '/' else 0
    parts = path.split('/')
    new_parts = []
    for part in parts:
        if part in ('', '.'):
            continue
        if part != '..' or new_parts and new_parts[-1
            ] == '..' or not initial_slash and not new_parts:
            new_parts.append(part)
        elif new_parts:
            new_parts.pop()
    return '/' * initial_slash + '/'.join(new_parts) + '/' * trailing_slash


def view_all(fit_view: bool=False):
    """View the entire image

    :param fit_view: Fit View, Fit frame to the viewport
    :type fit_view: bool
    """
    pass


@staticmethod
def _get_firmware(dist_name):
    """ The power supplies do not have a readable firmware or bios revision so
        this will return None for firmware and bios revisions"""
    return None, None


def _pretty_print(child: dict, is_file: bool=False) ->str:
    """Converts a child folder entry into a console display string."""
    if is_file:
        prefix = 4 * ' '
        icon = '~'
        name = child['name']
    else:
        prefix = 2 * ' '
        icon = '*' if child['spec'] else '-'
        name = child['folder']
    return '{}{} {}'.format(prefix, icon, name)


def update_numpydoc(docstr, fun, op):
    """Transforms the numpy docstring to remove references of
       parameters that are supported by the numpy version but not the JAX version"""
    if not hasattr(op, '__code__'):
        return docstr
    if docstr[:4] == '    ':
        lines = docstr.split('\n')
        for idx, line in enumerate(lines):
            lines[idx] = line.replace('    ', '', 1)
        docstr = '\n'.join(lines)
    begin_idx = docstr.find('Parameters')
    begin_idx = docstr.find('--\n', begin_idx) + 2
    end_idx = docstr.find('Returns', begin_idx)
    parameters = docstr[begin_idx:end_idx]
    param_list = parameters.replace('\n    ', '@@').split('\n')
    for idx, p in enumerate(param_list):
        param = p[:p.find(' : ')].split(', ')[0]
        if param not in op.__code__.co_varnames:
            param_list[idx] = ''
    param_list = [param for param in param_list if param != '']
    parameters = '\n'.join(param_list).replace('@@', '\n    ')
    return docstr[:begin_idx + 1] + parameters + docstr[end_idx - 2:]


def _load_tf_operation(name, graph, session):
    """Loads a TensorFlow operation object"""
    return graph.get_operation_by_name(name)


def validate_single_type(srctype, target):
    """
    Compares a type against a string description

    :param srctype: source type
    :param target: srctype pattern
    """
    if type(target) is not str:
        if srctype is target:
            return True
    elif '.' in target:
        fqn = srctype.__module__ + '.' + srctype.__name__
        return target == fqn
    else:
        return srctype.__name__ == target
    return False


def convert_query_to_sql_statement(query):
    """
    Convert a Query object created from orm query, into executable sql statement.

    :param query: :class:`sqlalchemy.orm.Query`

    :return: :class:`sqlalchemy.sql.selectable.Select`
    """
    context = query._compile_context()
    context.statement.use_labels = False
    return context.statement


def _not_implemented():
    """Generic function for missing network on linux (etc) port"""
    return None