def _format_duration(elapsed_time):
    """Format the elapsed time in seconds, or milliseconds if the duration is less than 1 second."""
    if elapsed_time > 1:
        duration = '{:2.2f} s'.format(elapsed_time)
    else:
        duration = '{:d} ms'.format(int(elapsed_time * 1000))
    return duration


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

        :param PaperContentAddToFolderDetails val:
        :rtype: EventDetails
        """
    return cls('paper_content_add_to_folder_details', val)


def Cv_to_Kv(Cv):
    """Convert valve flow coefficient from imperial to common metric units.

    .. math::
        K_v = C_v/1.156

    Parameters
    ----------
    Cv : float
        Imperial Cv valve flow coefficient (flow rate of water at a pressure
        drop of 1 psi) [gallons/minute]

    Returns
    -------
    Kv : float
        Metric Kv valve flow coefficient (flow rate of water at a pressure drop
        of 1 bar) [m^3/hr]

    Notes
    -----
    Kv = 0.865 Cv is in the IEC standard 60534-2-1.
    It has also been said that Cv = 1.17Kv; this is wrong by current standards.

    The conversion factor does not depend on the density of the fluid or the
    diameter of the valve. It is calculated with the definition of a US gallon
    as 231 cubic inches, and a psi as a pound-force per square inch.

    The exact conversion coefficient between Kv to Cv is 1.1560992283536566;
    it is rounded in the formula above.

    Examples
    --------
    >>> Cv_to_Kv(2.312)
    1.9998283393826013

    References
    ----------
    .. [1] ISA-75.01.01-2007 (60534-2-1 Mod) Draft
    """
    return Cv / 1.1560992283536566


@classmethod
def join(cls, *args):
    """
        Returns an string in which each given languages have been joined by
        the `+` separator.
        """
    result = []
    if len(args) > 0:
        if isinstance(args[0], (list, tuple)):
            return cls.join(*args[0])
        langs = []
        for lang in args:
            if isinstance(lang, cls):
                lang = lang.value
            elif isinstance(lang, str):
                lang = lang.strip()
            else:
                raise ValueError(
                    'join: Only string and TessyLang types are supported. Given type: {0}'
                    .format(str(type(lang))))
                continue
            if not cls.contains(lang):
                raise ValueError(
                    "join: The given language '{0}' doesn't exist or not supported yet."
                    .format(lang))
                continue
            langs.append(lang)
        if langs:
            result = '+'.join(langs)
    return result


@classmethod
def state(cls, size):
    """Return 'state' as jByteArray of given 'size'"""
    jpype = cls._get_jpype()
    JByteArray = jpype.JArray(jpype.JByte)
    state = JByteArray(size)
    return state


def findRelationships(query):
    """Given a single dictionary of {indexName: token}, return an iterable
        of relationships that match the query intransitively"""


def has_sources():
    """Return True of the filter as at least one source to look
        items in.
        """


@classmethod
def find_match(cls, entry):
    """Look up closest matching user database entry"""
    return cls.find(cls.parse_uid(entry.key))


def hyperbolic_volume(representation):
    """
    The hyperbolic volume, calculated by the SnapPy library for
    studying the topology and geometry of 3-manifolds. This function
    depends on the Spherogram module, distributed with SnapPy or
    available separately.

    Parameters
    ----------
    representation : A PlanarDiagram, or anything convertible to a
                     :class:`~pyknotid.representations.gausscode.GaussCode`
        A pyknotid representation class for the knot, or anything that
        can automatically be converted into a GaussCode (i.e. by writing
        :code:`GaussCode(your_object)`), or a PlanarDiagram.

    """
    from pyknotid.representations.gausscode import GaussCode
    from pyknotid.representations.planardiagram import PlanarDiagram
    if not isinstance(representation, (GaussCode, PlanarDiagram)):
        representation = GaussCode(representation)
    if isinstance(representation, GaussCode):
        representation = PlanarDiagram(representation)
    volume = representation.as_spherogram().exterior().volume()
    return volume


def name_matches_object(name, *objects, **kwargs):
    """Determine if a resource name could have been created by given objects.

    The object(s) must implement RandomNameGeneratorMixin.

    It will often be more efficient to pass a list of classes to
    name_matches_object() than to perform multiple
    name_matches_object() calls, since this function will deduplicate
    identical name generation options.

    :param name: The resource name to check against the object's
                 RESOURCE_NAME_FORMAT.
    :param *objects: Classes or objects to fetch random name
                     generation parameters from.
    :param **kwargs: Additional keyword args. See the docstring for
                     RandomNameGenerator.name_matches_object() for
                     details on what args are recognized.
    :returns: bool
    """
    unique_rng_options = {}
    for obj in objects:
        key = obj._get_resource_name_format(
            ), obj._get_resource_name_allowed_characters()
        if key not in unique_rng_options:
            unique_rng_options[key] = obj
    return any(obj.name_matches_object(name, **kwargs) for obj in
        unique_rng_options.values())


def describe_reserved_db_instances_offerings(ReservedDBInstancesOfferingId=
    None, DBInstanceClass=None, Duration=None, ProductDescription=None,
    OfferingType=None, MultiAZ=None, Filters=None, MaxRecords=None, Marker=None
    ):
    """
    Lists available reserved DB instance offerings.
    See also: AWS API Documentation

    Examples
    This example lists information for all reserved DB instance offerings for the specified DB instance class, duration, product, offering type, and availability zone settings.
    Expected Output:

    :example: response = client.describe_reserved_db_instances_offerings(
        ReservedDBInstancesOfferingId='string',
        DBInstanceClass='string',
        Duration='string',
        ProductDescription='string',
        OfferingType='string',
        MultiAZ=True|False,
        Filters=[
            {
                'Name': 'string',
                'Values': [
                    'string',
                ]
            },
        ],
        MaxRecords=123,
        Marker='string'
    )

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

    :type DBInstanceClass: string
    :param DBInstanceClass: The DB instance class filter value. Specify this parameter to show only the available offerings matching the specified DB instance class.

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

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

    :type OfferingType: string
    :param OfferingType: The offering type filter value. Specify this parameter to show only the available offerings matching the specified offering type.
            Valid Values: 'Partial Upfront' | 'All Upfront' | 'No Upfront'

    :type MultiAZ: boolean
    :param MultiAZ: The Multi-AZ filter value. Specify this parameter to show only the available offerings matching the specified Multi-AZ parameter.

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

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

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

    :rtype: dict
    :return: {
        'Marker': 'string',
        'ReservedDBInstancesOfferings': [
            {
                'ReservedDBInstancesOfferingId': 'string',
                'DBInstanceClass': 'string',
                'Duration': 123,
                'FixedPrice': 123.0,
                'UsagePrice': 123.0,
                'CurrencyCode': 'string',
                'ProductDescription': 'string',
                'OfferingType': 'string',
                'MultiAZ': True|False,
                'RecurringCharges': [
                    {
                        'RecurringChargeAmount': 123.0,
                        'RecurringChargeFrequency': 'string'
                    },
                ]
            },
        ]
    }

    """
    pass


@classmethod
def fetch_object(cls, resolwe, id=None, slug=None):
    """Return resource instance that is uniquely defined by identifier."""
    if id is None and slug is None or id and slug:
        raise ValueError('One and only one of id or slug must be given')
    query = resolwe.get_query_by_resource(cls)
    if id:
        return query.get(id=id)
    return query.get(slug=slug)


def p_tablemaker(p):
    """tablemaker :  stringliteral ":" expression tablemaker2 """
    p[0] = [(p[1], p[3])] + p[4]


def toZone(z):
    """Return a DateTime with the value as the current object,
        represented in the indicated timezone."""


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 psi_K_Na_NO3_PK74(T, P):
    """c-c'-a: potassium sodium nitrate [PK74]."""
    psi = -0.0012
    valid = T == 298.15
    return psi, valid


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

        :param FileUnlikeCommentType val:
        :rtype: EventType
        """
    return cls('file_unlike_comment', val)


def one():
    """This function returns 1"""
    return 1


@classmethod
def get(cls, *args, **kwargs):
    """Shortcut for :func:`sheraf.queryset.QuerySet.filter` and
        :func:`sheraf.queryset.QuerySet.get`. ``Cowboy.get(name="Peter")`` and
        ``Cowboy.filter(name="Peter").get()`` are equivalent.

        :return: The instance of the model if the filter matches exactly one
            instance. Otherwise, it raises a
            :class:`~sheraf.exceptions.QuerySetUnpackException`.

        >>> class Cowboy(sheraf.Model):
        ...     table = "people"
        ...     name = sheraf.SimpleAttribute()
        ...     age = sheraf.SimpleAttribute()
        ...
        >>> with sheraf.connection(commit=True):
        ...     peter = Cowboy.create(name="Peter", age=30)
        ...     steven = Cowboy.create(name="Steven", age=30)
        ...     assert peter == Cowboy.get(name="Peter")
        ...
        >>> with sheraf.connection():
        ...     Cowboy.get()
        Traceback (most recent call last):
            ...
        sheraf.exceptions.QuerySetUnpackException: Trying to unpack more than 1 value from a QuerySet
        >>> with sheraf.connection():
        ...     Cowboy.get(age=30)
        Traceback (most recent call last):
            ...
        sheraf.exceptions.QuerySetUnpackException: Trying to unpack more than 1 value from a QuerySet
        >>> with sheraf.connection():
        ...     Cowboy.get(name="Unknown cowboy")
        Traceback (most recent call last):
            ...
        sheraf.exceptions.EmptyQuerySetUnpackException: Trying to unpack an empty QuerySet
        """
    return cls.filter(*args, **kwargs).get()


def getGenesFromStrainT(geneT, strainT, genesO):
    """Given a tuple of genes (one from each strain) identify and return the two which are from strain pair."""
    genesInStrainTL = []
    for geneNum in geneT:
        if genesO.numToStrainName(geneNum) in strainT:
            genesInStrainTL.append(geneNum)
    return genesInStrainTL


def LN(number):
    """
    Calculates the natural logarithm ln of a number and returns the result as a double.
    See https://docs.mongodb.com/manual/reference/operator/aggregation/ln/
    for more details
    :param number: The number or field of number
    :return: Aggregation operator
    """
    return {'$ln': number}


def _get_y_min_max(y, plot_at_least):
    """
    Returns the maximum / minimum values which should be plotted according to
    plot_at_least.

    Parameters
    ----------
    y : list of floats
        The y values in question.

    plot_at_least : 2-tuple of floats
        The (from_below, from_above) percentage of points to show.

    Returns
    -------
    min_y_new : float
        The new minimum y value.
    max_y_new : float
        The new maximum y value.
    """
    sorted_y = sorted(y)
    max_y_new = sorted_y[min(len(sorted_y) - 1, int(plot_at_least[1] * len(
        sorted_y)))]
    min_y_new = sorted_y[int(plot_at_least[0] * (1 - len(sorted_y)))]
    return min_y_new, max_y_new


@classmethod
def get_container_name(cls):
    """ Returns the name of the container class.

			Obviously, "for" is an overloaded word in programming. So rather
			than risk problems with statements like `import for`, it is better
			to just have a different name that is used in parsing containers.
		"""
    return 'for'


def optimize_bit_format(bits_size):
    """
    By default, C types are represented in the machine’s native format and byte
    order. Alternatively, the first character of the format string can be used
    to indicate the byte order, size and alignment of the packed data.
    ~~~
    @params bits_size : Decimal integer.
    @return fmt_code  : Format codes means the conversion between C and Python values.
                        Ref: https://docs.python.org/3/library/struct.html#format-characters
    @return std_size  : Refers to the size of the packed value in bytes when using standard size.
    """
    if bits_size >= 1 << 31:
        fmt_code, std_size = 'Q', 8
    elif bits_size >= 1 << 15:
        fmt_code, std_size = 'I', 4
    else:
        fmt_code, std_size = 'H', 2
    return fmt_code, std_size


def get_func_dict(func_title, func_dicts):
    """ Get specific function dict from func_dicts """
    func_dict = [func_dict for func_dict in func_dicts if func_dict['title'
        ] == func_title]
    if len(func_dict) > 1:
        raise Exception('Cannot use same title for your functions')
    func_dict = func_dict[0]
    return func_dict


def drivers_add_selected():
    """Add drivers to selected items

    """
    pass


def close(i, j, tolerance):
    """
    check two float values are within a bound of one another
    """
    return i <= j + tolerance and i >= j - tolerance


def temperature_data_to_csv(temperature_data, path_or_buf):
    """ Write temperature data to CSV. See also :any:`pandas.DataFrame.to_csv`.

    Parameters
    ----------
    temperature_data : :any:`pandas.Series`
        Temperature data series with :any:`pandas.DatetimeIndex`.
    path_or_buf : :any:`str` or file handle, default None
        File path or object, if None is provided the result is returned as a string.
    """
    if temperature_data.index.name is None:
        temperature_data.index.name = 'dt'
    if temperature_data.name is None:
        temperature_data.name = 'temperature'
    return temperature_data.to_frame().to_csv(path_or_buf, index=True)


def lower_transform(word: str, index: int):
    """
    Lower-case every word.

    Parameters
    ----------
    word : str
        Word to lower-case
    index : int
        Index of word in original string of words.

    Returns
    -------
    w : str
        Transformed word.
    """
    return word.lower()


def equal(x, y):
    """Compares whether the elements are equal.

    Parameters
    ----------
    x, y : Tensor
        The two tensors

    Returns
    -------
    Boolean tensor
        The result, with the same shape as input.
    """
    pass


@classmethod
def from_mark5b_frame(cls, mark5b_frame, verify=True, **kwargs):
    """Construct an Mark5B over VDIF frame (EDV=0xab).

        Any additional keywords can be used to set VDIF header properties
        not found in the Mark 5B header (such as station).

        See https://vlbi.org/wp-content/uploads/2019/03/vdif_extension_0xab.pdf
        """
    m5h, m5pl = mark5b_frame.header, mark5b_frame.payload
    header = cls._header_class.from_mark5b_header(m5h, nchan=m5pl.
        sample_shape.nchan, bps=m5pl.bps, invalid_data=not mark5b_frame.
        valid, **kwargs)
    payload = cls._payload_class(m5pl.words, header)
    return cls(header, payload, verify)


def get_segment_names(cos_spectrum):
    """
    Returns a list of segment names sorted such that the bluest segment come
    first.

    :param cos_spectrum: COS spectrum as returned by READSPEC.

    :type cos_spectrum: COSSpectrum

    :returns: list -- A list of segment names.
    """
    segment_names = list(cos_spectrum.segments.keys())
    if cos_spectrum.band == 'FUV':
        segment_names.sort(reverse=True)
    else:
        segment_names.sort(reverse=False)
    return segment_names


@staticmethod
def list_to_headers(headers=None, key=None, type_of_key='str', key_index=
    None, types=None):
    """
        Transform list item to the object we need send to Devo for headers

        :param list headers: list of headers names
        :param str key: key name (Must be in headers)
        :param str type_of_key: type of the key field
        :result str:
        """
    if key is not None:
        out = '[{"%s":{"type":"%s","key":true}}' % (key, types[key_index] if
            types else type_of_key)
    elif key_index is not None:
        key = headers[key_index]
        out = '[{"%s":{"type":"%s","key":true}}' % (key, types[key_index] if
            types else type_of_key)
    else:
        raise Exception('Not key identified')
    if headers is None:
        return out + ']'
    aux = -1
    for item in headers:
        aux += 1
        if item == key:
            continue
        field_type = 'str' if not isinstance(types, dict) else types[aux]
        out += ',{"%s":{"type":"%s"}}' % (item, field_type)
    out += ']'
    return out


@classmethod
def _add_submit_args(cls, parser):
    """Add arguments to submit sub command to parser."""
    parser.add_argument('flags', type=str, nargs='*', help=
        'Flags to be forwarded to the scheduler.')
    parser.add_argument('--pretend', action='store_true', help=
        'Do not really submit, but print the submission script to screen.')
    parser.add_argument('--force', action='store_true', help=
        'Ignore all warnings and checks, just submit.')
    parser.add_argument('--test', action='store_true', help=
        'Do not interact with the scheduler, implies --pretend.')
    cls._add_operation_selection_arg_group(parser)
    cls._add_operation_bundling_arg_group(parser)
    cls._add_template_arg_group(parser)


@classmethod
def from_offset(cls, chunk_type, stream_rdr, offset):
    """
        Return an _IHDRChunk instance containing the image dimensions
        extracted from the IHDR chunk in *stream* at *offset*.
        """
    px_width = stream_rdr.read_long(offset)
    px_height = stream_rdr.read_long(offset, 4)
    return cls(chunk_type, px_width, px_height)


def is_float_or_int(value):
    """
    Returns True if the value is a float or an int, False otherwise.
    :param value:
    :return:
    """
    if type(value) is float:
        return True
    elif type(value) is int:
        return True
    else:
        return False


@classmethod
def definedPlatformTypes(cls):
    """
        Class method to get all platform types defined in API v4.

        @return list of all defined platform types
        @rtype list of str
        """
    return ['PLATFORM_TYPE_UNSPECIFIED', 'WINDOWS', 'LINUX', 'ANDROID',
        'OSX', 'IOS', 'ANY_PLATFORM', 'ALL_PLATFORMS', 'CHROME']


def _capitalize_first_letter(word):
    """Return a regex pattern with the first letter.

    Accepts both lowercase and uppercase.
    """
    if word[0].isalpha():
        if word[0].isupper():
            return '[' + word[0].swapcase() + word[0] + ']' + word[1:]
        else:
            return '[' + word[0] + word[0].swapcase() + ']' + word[1:]
    return word


@classmethod
def get_available_fields(cls, model, db_fields_only=False):
    """
        Returns a list of all the fields that can be used in the API for the
        specified model class.

        Setting db_fields_only to True will remove all fields that do not have
        an underlying column in the database (eg, type/detail_url and any custom
        fields that are callables)
        """
    fields = cls.get_body_fields_names(model) + cls.get_meta_fields_names(model
        )
    if db_fields_only:
        database_fields = set()
        for field in model._meta.get_fields():
            database_fields.add(field.name)
            if hasattr(field, 'attname'):
                database_fields.add(field.attname)
        fields = [field for field in fields if field in database_fields]
    return fields


def _ge(left, right):
    """Helper for match_spec."""
    return float(left) >= float(right)


@classmethod
def cycle_pre_run(cls, context, synergy_manager):
    """

        This class method will be executed each cycle, one time by action class.
        Useful fo apply some tricks before this synergies objects action.

        :param context:
        :param synergy_manager:
        :return:
        """
    pass


def force_hdr_to_2D(hdrin):
    """
    A simple function to take in a header and remove items related to 3D or 4D structure -- such as NAXIS3...

    Parameters
    ----------
    hdrin : astropy.io.fits.header
        Header object

    Returns
    -------
    astropy.io.fits.header
        Output 2D header
    """
    hdr2D = hdrin.copy()
    for item in ['CRVAL3', 'CRPIX3', 'CDELT3', 'CTYPE3', 'CUNIT3', 'NAXIS3',
        'CRVAL4', 'CRPIX4', 'CDELT4', 'CUNIT4', 'CTYPE4', 'NAXIS4',
        'PC03_01', 'PC04_01', 'PC03_02', 'PC04_02', 'PC01_03', 'PC02_03',
        'PC03_03', 'PC04_03', 'PC01_04', 'PC02_04', 'PC03_04', 'PC04_04']:
        try:
            hdr2D.remove(item)
        except:
            pass
        hdr2D['NAXIS'] = 2
    return hdr2D


@classmethod
def response_payload(cls, result, request_id):
    """JSON v1 response payload."""
    return {'result': result, 'error': None, 'id': request_id}


def atom_formal_charge(atom):
    """Get formal charge for an atom.

    Parameters
    ----------
    atom : rdkit.Chem.rdchem.Atom
        RDKit atom instance.

    Returns
    -------
    list
        List containing one int only.
    """
    return [atom.GetFormalCharge()]


def selection_sort(nums):
    """
    Takes an array of numbers and returns the sorted array
    Time Complexity: O(n^2)
    Space Complexity: O(1)
    """
    for i in range(len(nums) - 1):
        min_index = i
        for j in range(i + 1, len(nums)):
            if nums[j] < nums[min_index]:
                min_index = j
        nums[min_index], nums[i] = nums[i], nums[min_index]
    return nums


def copy_url(url):
    """Copy the url into the clipboard."""
    try:
        import win32clipboard
    except ImportError:
        from subprocess import Popen, PIPE
        try:
            client = Popen(['pbcopy'], stdin=PIPE)
        except OSError:
            try:
                import pygtk
                pygtk.require('2.0')
                import gtk
                import gobject
            except ImportError:
                return
            gtk.clipboard_get(gtk.gdk.SELECTION_CLIPBOARD).set_text(url)
            gobject.idle_add(gtk.main_quit)
            gtk.main()
        else:
            client.stdin.write(url)
            client.stdin.close()
            client.wait()
    else:
        win32clipboard.OpenClipboard()
        win32clipboard.EmptyClipboard()
        win32clipboard.SetClipboardText(url)
        win32clipboard.CloseClipboard()


@classmethod
def service_disable(cls, options=None):
    """Build foreman-maintain service disable"""
    cls.command_sub = 'disable'
    if options is None:
        options = {}
    result = cls._construct_command(options)
    return result


def __call__():
    """ Creates and returns an :py:class:`IWidget` instance
        """


def pair_window(iterable):
    """
    A more simple version of `window` for size=2.

    >>> list(window([11, 22, 33, 44]))
    [(11, 22), (22, 33), (33, 44)]
    """
    iterable = iter(iterable)
    try:
        prev_value = next(iterable)
    except StopIteration:
        return
    for item in iterable:
        yield prev_value, item
        prev_value = item


def addition(first, second):
    """ Addition operation

    :param first: first operator
    :param second: second operator

    Returns:
        The result of an addition operation
    """
    return first + second


def create_folder(service, name, folder_id=None, **kwargs):
    """
    Creates a folder and returns the FileId
    :param service: Service object
    :param name: name of the folder
    :param folder_id: (Optional) FileId of the containing folder
    :return: folder object
    """
    kwargs['name'] = name
    kwargs['mimeType'] = 'application/vnd.google-apps.folder'
    if folder_id:
        kwargs['parents'] = [folder_id]
    return service.files().create(body=kwargs).execute()


def associate_qualification_with_worker(QualificationTypeId=None, WorkerId=
    None, IntegerValue=None, SendNotification=None):
    """
    The AssociateQualificationWithWorker operation gives a Worker a Qualification. AssociateQualificationWithWorker does not require that the Worker submit a Qualification request. It gives the Qualification directly to the Worker.
    You can only assign a Qualification of a Qualification type that you created (using the CreateQualificationType operation).
    See also: AWS API Documentation

    :example: response = client.associate_qualification_with_worker(
        QualificationTypeId='string',
        WorkerId='string',
        IntegerValue=123,
        SendNotification=True|False
    )

    :type QualificationTypeId: string
    :param QualificationTypeId: [REQUIRED]
            The ID of the Qualification type to use for the assigned Qualification.

    :type WorkerId: string
    :param WorkerId: [REQUIRED]
            The ID of the Worker to whom the Qualification is being assigned. Worker IDs are included with submitted HIT assignments and Qualification requests.

    :type IntegerValue: integer
    :param IntegerValue: The value of the Qualification to assign.

    :type SendNotification: boolean
    :param SendNotification: Specifies whether to send a notification email message to the Worker saying that the qualification was assigned to the Worker. Note: this is true by default.

    :rtype: dict
    :return: {}

    :returns:
    (dict) --

    """
    pass


@classmethod
def from_payload(cls, payload, id_key, airship):
    """Create based on results from a ScheduledList iterator."""
    obj = cls(airship)
    obj._schedule_id = payload[id_key]
    for key in payload:
        setattr(obj, key, payload[key])
    return obj


def _csv_field_str(field):
    """Stringify csv fields"""
    value = '' if field is None else str(field)
    if ',' in value:
        value = f'"{value}"'
    return value


def _requires_launchpad_login(scheme, netloc, path, query, fragment):
    """Does the URL require a Launchpad login in order to be reached?

    The URL is specified by its parsed components, as returned from
    urlsplit.
    """
    return scheme in ('bzr+ssh', 'sftp') and (netloc.endswith(
        'launchpad.net') or netloc.endswith('launchpad.dev'))


def set_dubbo_decode(decode: str):
    """
    set decode format

    :param decode: decode name
    """
    global __decode_fmt__
    __decode_fmt__ = decode


def __add__(interfaces):
    """Create an interface specification with some interfaces added

        The argument can be an interface or an interface
        specifications.  The interface or interfaces given in a
        specification are added to the interface specification.

        Adding an interface that is already in the specification does
        not raise an error. Doing so has no effect.
        """


@classmethod
def type_key(cls):
    """ Get the key used to store data type on an instance"""
    return cls.__type_key


def is_process_running(process):
    """Checks whether the process is still running.

    Parameters
    ----------
    process: subprocess.Popen
        The process to query

    Returns
    -------
    whether the process is still running.
    """
    return process.poll() is None


def index_select_images_lone(phi_width, images):
    """Select images close to 0, 45 and 90 degrees from the list of available
    frames. N.B. we assume all frames have the same oscillation width."""
    selected_images = [images[0]]
    offset = images[0] - 1
    if offset + int(90.0 / phi_width) in images:
        selected_images.append(offset + int(45.0 / phi_width))
        selected_images.append(offset + int(90.0 / phi_width))
    else:
        middle = len(images) // 2 - 1
        if len(images) >= 3:
            selected_images.append(images[middle])
        selected_images.append(images[-1])
    return selected_images


def _join_translated(translated_parts, os_sep_class):
    """Join translated glob pattern parts.

    This is different from a simple join, as care need to be taken
    to allow ** to match ZERO or more directories.
    """
    res = ''
    for part in translated_parts[:-1]:
        if part == '.*':
            res += part
        else:
            res += part + os_sep_class
    if translated_parts[-1] == '.*':
        res += '.+'
        res += '({os_sep_class}?.*)?'.format(os_sep_class=os_sep_class)
    else:
        res += translated_parts[-1]
    return res


@classmethod
def model_path(cls):
    """Get the path to fastai pretrained models in the config file."""
    return cls.get_path('model_path')


def call_menu(name: str=''):
    """Call (draw) a pre-defined menu

    :param name: Name, Name of the menu
    :type name: str
    """
    pass


def get_message_by_hash(message_id_hash):
    """Return the message with the matching Message-ID-Hash.

        :param message_id_hash: The Message-ID-Hash header contents to
            search for.
        :returns: The message, or None if no matching message was found.
        """


def instantiate_steppers(model, steps, selected_steps, step_kwargs=None):
    """Instantiates steppers assigned to the model variables.

    This function is intended to be called automatically from ``sample()``, but
    may be called manually.

    Parameters
    ----------
    model : Model object
        A fully-specified model object
    step : step function or vector of step functions
        One or more step functions that have been assigned to some subset of
        the model's parameters. Defaults to None (no assigned variables).
    selected_steps: dictionary of step methods and variables
        The step methods and the variables that have were assigned to them.
    step_kwargs : dict
        Parameters for the samplers. Keys are the lower case names of
        the step method, values a dict of arguments.

    Returns
    -------
    methods : list
        List of step methods associated with the model's variables.
    """
    if step_kwargs is None:
        step_kwargs = {}
    used_keys = set()
    for step_class, vars in selected_steps.items():
        if len(vars) == 0:
            continue
        args = step_kwargs.get(step_class.name, {})
        used_keys.add(step_class.name)
        step = step_class(vars=vars, **args)
        steps.append(step)
    unused_args = set(step_kwargs).difference(used_keys)
    if unused_args:
        raise ValueError('Unused step method arguments: %s' % unused_args)
    if len(steps) == 1:
        steps = steps[0]
    return steps


def log_nodes_cb(node, status):
    """
    Record node run statistics to a log file as json dictionaries.

    Parameters
    ----------
    node : nipype.pipeline.engine.Node
        the node being logged
    status : string
        acceptable values are 'start', 'end'; otherwise it is
        considered and error

    Returns
    -------
    None
        this function does not return any values, it logs the node
        status info to the callback logger

    """
    if status != 'end':
        return
    import logging
    import json
    status_dict = {'name': node.name, 'id': node._id, 'start': getattr(node
        .result.runtime, 'startTime'), 'finish': getattr(node.result.
        runtime, 'endTime'), 'duration': getattr(node.result.runtime,
        'duration'), 'runtime_threads': getattr(node.result.runtime,
        'cpu_percent', 'N/A'), 'runtime_memory_gb': getattr(node.result.
        runtime, 'mem_peak_gb', 'N/A'), 'estimated_memory_gb': node.mem_gb,
        'num_threads': node.n_procs}
    if status_dict['start'] is None or status_dict['finish'] is None:
        status_dict['error'] = True
    logging.getLogger('callback').debug(json.dumps(status_dict))


def constraint(value):
    """Check a customized constraint on the value.

        You can implement this method with your Field to
        require a certain constraint.  This relaxes the need
        to inherit/subclass a Field you to add a simple constraint.
        Returns true if the given value is within the Field's constraint.
        """


@staticmethod
def mm_to_pt(measure):
    """Convert millimeters to points."""
    return measure * 2.83465


@classmethod
def get_real_child_model(cls, data):
    """Returns the real base class specified by the discriminator"""
    discriminator_value = data[cls.json_discriminator_key]
    return cls.discriminator_value_class_map.get(discriminator_value)


@classmethod
def from_string(cls, token_string):
    """ `token_string` should be the string representation from the server. """
    return cls(int(token_string))


def sft32kgm3(density_slft3):
    """Convert density from slugs/ft^3 to kg/m^3"""
    return density_slft3 / 0.00194032


def chain(*operations):
    """Run callables one after the other

    The output of the last callable is passed to the next.

    Arguments:
        operations (list): Callables to run

    Returns:
        Result from last operation

    """
    result = None
    for operation in operations:
        result = operation(result)
    return result


def calculate_wheel_power(velocities, accelerations, road_loads, vehicle_mass):
    """
    Calculates the wheel power [kW].

    :param velocities:
        Velocity [km/h].
    :type velocities: numpy.array | float

    :param accelerations:
        Acceleration [m/s2].
    :type accelerations: numpy.array | float

    :param road_loads:
        Cycle road loads [N, N/(km/h), N/(km/h)^2].
    :type road_loads: list, tuple

    :param vehicle_mass:
        Vehicle mass [kg].
    :type vehicle_mass: float

    :return:
        Power at wheels [kW].
    :rtype: numpy.array | float
    """
    f0, f1, f2 = road_loads
    quadratic_term = f0 + (f1 + f2 * velocities) * velocities
    vel = velocities / 3600
    return (quadratic_term + 1.03 * vehicle_mass * accelerations) * vel


def _validate_use(use: str):
    """Validates the 'use' argument. If invalid, raises an error"""
    use = use.lower()
    valid_use_keywords = {'everything', 'pairwise.complete', 'complete'}
    if use not in valid_use_keywords:
        raise ValueError(f"use must be one of {', '.join(valid_use_keywords)}")
    return use


def __call__(value, mimeType):
    """Transform the IRichTextValue 'value' to the given MIME type.
        Return a unicode string. Raises TransformError if something went
        wrong.
        """


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


def ternary_feedback(sensing, collision):
    """ Count 1 iff the sensing authorized to communicate and no collision was observed, 0 if no communication, and -1 iff communication but a collision was observed.

    .. math::

       \\mathrm{reward}(\\text{user}\\;j, \\text{time}\\;t) &:= F_{m,t} \\times (2 r_{m,t} - 1), \\\\
       \\text{where}\\;\\; r_{j,t} &:= F_{m,t} \\times (1 - c_{m,t}), \\\\
       \\text{and}  \\;\\; F_{m,t} &\\; \\text{is the sensing feedback (1 iff channel is free)}, \\\\
       \\text{and}  \\;\\; c_{m,t} &\\; \\text{is the collision feedback (1 iff user j experienced a collision)}.
    """
    assert 0 <= sensing <= 1, "Error: 'sensing' argument was not in [0, 1] (was {:.3g}).".format(
        sensing)
    if sensing not in [0, 1]:
        print(
            "Warning: 'sensing' argument was not 0 or 1, but this policy rhoLearnExp3 was only designed for binary sensing model... (was {:.3g})."
            .format(sensing))
    assert collision in [0, 1
        ], "Error: 'collision' argument was not binary, it can only be 0 or 1 (was {:.3g}).".format(
        collision)
    first_reward = sensing * (1 - collision)
    assert 0 <= first_reward <= 1, "Error: variable 'first_reward' should have been only binary 0 or 1 (was {:.3g}).".format(
        first_reward)
    reward = sensing * (2 * first_reward - 1)
    assert -1 <= reward <= 1, "Error: variable 'reward' should have been only binary 0 or 1 (was {:.3g}).".format(
        reward)
    if reward not in {-1, 0, 1}:
        print(
            "Warning: 'reward' argument was not -1, 0 or 1, but this function should give ternary reward... (was {:.3g})."
            .format(reward))
    return reward


@staticmethod
def get_entry_property(entry, prop, default=None, raw=False):
    """
        Simple wrapper that gets an attribute from ldap3 dictionary,
        converting empty values to the default specified. This is primarily
        for output to JSON
        """
    try:
        if raw:
            value = entry['raw_attributes'][prop]
        else:
            value = entry['attributes'][prop]
    except KeyError:
        return default
    if value == []:
        return default
    try:
        if len(value) == 1 and default != []:
            return value[0]
    except TypeError:
        pass
    return value


def to_monthly(series, method='ffill', how='end'):
    """
    将时间序列转换成月频，使用asfreq_actual
    """
    return series.asfreq_actual('M', method=method, how=how)


@staticmethod
def format_time(seconds):
    """
        Converts seconds into seconds, minutes:seconds, or
        hours:minutes.seconds as appropriate.
        """
    minutes, seconds = divmod(float(seconds), 60)
    hours, minutes = divmod(minutes, 60)
    return_value = int(hours), int(minutes), float(seconds)
    if hours:
        return '{0:d}:{1:0>2d}:{2:0>6.3f}'.format(*return_value)
    elif minutes:
        return '{1:d}:{2:0>6.3f}'.format(*return_value)
    else:
        return '{2:.3f}'.format(*return_value)


def is_soft_clipped(read):
    """Function that checks the CIGAR string of the sam file and returns true if the read is soft-clipped"""
    match = 0
    for cigar in read.cigar:
        if cigar[0] == 4:
            match += 1
        else:
            pass
    if match > 0:
        return True
    else:
        return False


@classmethod
def template_class(cls, class_):
    """
        Assign a class to be this widget class's template class
        """
    cls._template_class = class_
    return class_


@staticmethod
def fixed_pattern(pattern=None, io_size='8k'):
    """ renew the fixed pattern

        generate a data with fixed data pattern
        :return : data pattern in bytes
        """
    iosize = int(io_size)
    tmpbytes = bytes('content of data pattern is not important', encoding=
        'utf-8')
    if pattern is not None:
        tmpbytes = bytes(tmpbytes, encoding='utf-8')
    if len(tmpbytes) >= iosize:
        return tmpbytes[:iosize]
    else:
        number = iosize // len(tmpbytes)
        remainder = tmpbytes[:iosize % len(tmpbytes)]
        return tmpbytes * number + remainder


def normalize_url(url, loader_context=None):
    """Expand URL fragments."""
    try:
        return loader_context['response'].urljoin(url)
    except Exception:
        pass
    return 'http:' + url if url.startswith('//') else url


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

        :param ResellerSupportSessionEndType val:
        :rtype: EventType
        """
    return cls('reseller_support_session_end', val)


def quit():
    """
        Free any resources associated with this L{IWorker} and cause it to
        reject all future work.

        @raise: L{AlreadyQuit} if this method has already been called.
        """


def to_str(obj, *fields):
    """该函数用于方便生成__repr__和__str__方法的返回内容
       :param obj: 目标对象
       :param fields: 目标属性，如果不指定，则会返回所有
    """
    if not fields:
        try:
            fields = obj.__dict__.keys()
        except AttributeError:
            fields = obj.__slots__
    str_buf = ['{class_name}@{id_} <']
    for idx, field in enumerate(fields):
        if isinstance(field, str):
            str_buf.append('{field}={value}'.format(field=field, value=
                getattr(obj, field)))
        elif isinstance(field, tuple):
            field, callback = field
            str_buf.append('{field}={value}'.format(field=field, value=
                callback(getattr(obj, field))))
        else:
            raise AttributeError("Unsupport field type: '{clazz}'".format(
                clazz=field.__class__.__name__))
        if idx < len(fields) - 1:
            str_buf.append(', ')
    str_buf.append('>')
    return ''.join(str_buf).format(class_name=obj.__class__.__name__, id_=
        id(obj))


def ensure_alt_ids_are_only_in_one_nest(nest_spec, list_elements):
    """
    Ensures that the alternative id's in `nest_spec` are only associated with
    a single nest. Raises a helpful ValueError if they are not.

    Parameters
    ----------
    nest_spec : OrderedDict, or None, optional.
        Keys are strings that define the name of the nests. Values are lists of
        alternative ids, denoting which alternatives belong to which nests.
        Each alternative id must only be associated with a single nest!
        Default == None.
    list_elements : list of ints.
        Each element should correspond to one of the alternatives identified as
        belonging to a nest.

    Returns
    -------
    None.
    """
    try:
        assert len(set(list_elements)) == len(list_elements)
    except AssertionError:
        msg = 'Each alternative id should only be in a single nest.'
        raise ValueError(msg)
    return None


def let(**nameValuePair):
    """
    Takes in a single name = value pair. The value is assigned to the name and
    returned. This is useful in if statements, while loops, and anyplace else
    where you want to both assign and use a value. Examples:

    Instead of:

        name = longInstanceName.longAttributeName
        if name:
            ...

    - Or worse, using that long identifier in the condition and then repeatedly
    in the body - you can use this:

        if let(name = longInstanceName.longAttributeName):
            ...

    Instead of:

        results = dbConnection.fetch_results():
        while results:
            ...
            results = dbConnection.fetch_results()

    You can do this:

        while let(results = dbConnection.fetch_results):
            ...

    Instead of:

        if len(nameValuePair) != 1:
            raise Exception('Bad amount: {}'.format(len(nameValuePair)))

    You could use:

        if let(count = len(nameValuePair)) != 1:
            raise Exception('Bad amount: {}'.format(count))
    """
    count = len(nameValuePair)
    if count != 1:
        raise TypeError('let() takes exactly one key = value pair ({} given)'
            .format(count))
    name, value = nameValuePair.items()[0]
    from inspect import stack
    frame = stack()[1][0]
    locals_ = frame.f_locals
    if name in locals_:
        raise Exception(name +
            ' has already been locally assigned. Due to optimizations in the Python interpreter, it is not possible to write over it using let(). Sorry!'
            )
    else:
        frame.f_globals[name] = value
    return value


def hook_add_newob():
    """Hook selected vertices to a newly created object

    """
    pass


def generate_new_key():
    """ generate new internal key
        """


def plural(obj):
    """Return "s" or "" depending on n."""
    if isinstance(obj, (list, tuple, str)):
        n = len(obj)
    else:
        n = obj
    return '' if n == 1 else 's'


def nbr_to_str(nbr, t_precision):
    """
    Converts a scalar into a string in scientific (exponential) notation
    without the decimal point.

    Parameters
    ----------
    nbr : scalar
        The number to be converted into a scalar.

    t_precision : integer
        The time precision (number of decimal places). Default value is 12.
    """
    from decimal import Decimal as dc
    n = int(-dc(str(round(nbr, t_precision))).as_tuple().exponent * (round(
        nbr, t_precision) != int(nbr)))
    nbr_str = str(int(round(nbr, t_precision) * 10 ** n)) + ('e-' + str(n)) * (
        n != 0)
    return nbr_str


def tuparray_value_by_index(tupa, i):
    """Compose list of indexed values from tupa"""
    v_ = []
    for t_ in tupa:
        v_.append(t_[i])
    return v_


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 list_prs_arguments(parser):
    """ List pull requests.
    """
    parser.add_argument('indexname', type=str, action='store', nargs='?',
        help=
        'index name, specified as NAME or USER/NAME.  If no index is specified use the current index'
        )
    parser.add_argument('-a', '--all-states', action='store_true', help=
        'Output normally hidden states.')
    parser.add_argument('-m', '--messages', action='store_true', help=
        'Include state change messages in output.')


def make_paths_relative():
    """Make all paths to external files relative to current .blend

    """
    pass


def _validate_int(value, content):
    """Return parameter value as an integer.
    :param str value: The raw parameter value.
    :param dict content: The template parameter definition.
    :returns: int
    """
    try:
        original = str(value)
        value = int(value)
    except (ValueError, UnicodeEncodeError):
        raise TypeError("'{}' is not a valid integer.".format(value))
    if str(value) != original:
        raise TypeError("'{}' is not a valid integer.".format(value))
    try:
        if value < int(content['minValue']):
            raise ValueError('Minimum value: {}'.format(content['minValue']))
    except KeyError:
        pass
    try:
        if value > int(content['maxValue']):
            raise ValueError('Maximum value: {}'.format(content['maxValue']))
    except KeyError:
        pass
    return value


def copy_class(cls):
    """Return a copy (actually a subclass) of the given class.

    Function |copy_class| simplifies testing classes through changing them:

    >>> x = int(3)
    >>> x.bit_length()
    2
    >>> from hydpy.core.objecttools import copy_class
    >>> int_ = copy_class(int)
    >>> int_.bit_length = lambda self: 'test'
    >>> int_(3).bit_length()
    'test'
    """
    return type(cls.__name__, (cls,), {})


@classmethod
def from_requirement(cls, req, changes=None):
    """ Create an instance from :class:`pkg_resources.Requirement` instance """
    return cls(req.project_name, req.specs and ''.join(req.specs[0]) or '',
        changes=changes)


@classmethod
def from_clang_range(cls, range):
    """
        Creates a SourceRange from a clang SourceRange object.

        :param range: A cindex.SourceRange object.
        """
    return cls.from_values(range.start.file.name, range.start.line, range.
        start.column, range.end.line, range.end.column)


@staticmethod
def to_reaumur(fahrenheit):
    """ Convert fahrenheit to reaumur """
    return (fahrenheit - 32) * 4 / 9


@classmethod
def delete(cls, db_name):
    """ Delete the registry linked to a given database. """
    with cls._lock:
        if db_name in cls.registries:
            cls.registries.pop(db_name)


def four_d_to_projection_stack_image_filter(*args, **kwargs):
    """Procedural interface for FourDToProjectionStackImageFilter"""
    import itk
    instance = itk.FourDToProjectionStackImageFilter.New(*args, **kwargs)
    return instance.__internal_call__()


def floor(data=None, name=None, attr=None, out=None, **kwargs):
    """Returns element-wise floor of the input.

    The floor of the scalar x is the largest integer i, such that i <= x.

    Example::

       floor([-2.1, -1.9, 1.5, 1.9, 2.1]) = [-3., -2.,  1.,  1.,  2.]

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

       - floor(default) = default
       - floor(row_sparse) = row_sparse
       - floor(csr) = csr

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

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

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

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


def getGroupMembers():
    """ Return a list of the portal_memberdata-ish members of the group."""


def input_or(prompt, default='y'):
    """
    get input from command-line,
    if  the input is ommited by an enter key, then the default values is returned.
    """
    v = input(prompt + '(default:%s):' % str(default))
    v = v or default
    dtype = type(default)
    return dtype(v)


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


def convert_unusable_tag_to_misc(line, misc_text, tag_match_end, closing_tag):
    """Function to remove an unwanted, tagged, citation item from a reference
       line. The tagged item itself is put into the miscellaneous text variable;
       the data up to the closing tag is then trimmed from the beginning of the
       working line. For example, the following working line:
         Example, AN. Testing software; <cds.YR>(2001)</cds.YR>, CERN, Geneva.
       ...would be trimmed down to:
         , CERN, Geneva.
       ...And the Miscellaneous text taken from the start of the line would be:
         Example, AN. Testing software; (2001)
       ...(assuming that the details of <cds.YR> and </cds.YR> were passed to
       the function).
       @param line: (string) - the reference line.
       @param misc_text: (string) - the variable containing the miscellaneous
        text recorded so far.
       @param tag_match_end: (integer) - the index of the end of the opening tag
        in the line.
       @param closing_tag: (string) - the closing tag to look for in the line
        (e.g. </cds.YR>).
       @return: (tuple) - containing misc_text (string) and line (string)
    """
    idx_closing_tag = line.find(closing_tag, tag_match_end)
    if idx_closing_tag == -1:
        line = line[tag_match_end:]
    else:
        misc_text += line[tag_match_end:idx_closing_tag]
        line = line[idx_closing_tag + len(closing_tag):]
    return misc_text, line


def cluster_contour_mask(rgb_img, clusters_i, contours, hierarchies):
    """Outputs masks for the grouped clusters. Since there can be a variable number of
    clusters/masks the output is a list of arrays.

    Inputs:
    rgb_img       = RGB image data
    clusters_i    = clusters, output from cluster_contours function
    contours      = contours, contours from cluster_contours function
    hierarchies   = hierarchies, hierarchies from cluster_contours function

    Returns:
    output_masks  = resulting masks
    masked_images  = masked_images

    :param rgb_img: numpy.ndarray
    :param clusters_i: numpy array
    :param contours: numpy array
    :param hierarchies: numpy array
    :return output_masks: list of resulting masks
    :return masked_images: list of masked images
    """


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 runCommands(agent, command_list):
    """
    Executes each command in command_list on a given AgentType.  The commands
    should be methods of that AgentType's subclass.

    Parameters
    ----------
    agent : AgentType
        An instance of AgentType on which the commands will be run.
    command_list : [string]
        A list of commands that the agent should run, as methods.

    Returns
    -------
    agent : AgentType
        The same AgentType instance passed as input, after running the commands.
    """
    for command in command_list:
        exec('agent.' + command)
    return agent


def get_storage_client(configuration, announcement, get_rref):
    """
        Get an ``IStorageServer`` provider that implements the client side of the
        storage protocol.

        :param allmydata.node._Config configuration: A representation of the
            configuration for the node into which this plugin has been loaded.

        :param dict announcement: The announcement for the corresponding
            server portion of this plugin received from a storage server which
            is offering it.

        :param get_rref: A no-argument callable which returns a
            ``foolscap.referenceable.RemoteReference`` which refers to the
            server portion of this plugin on the currently active connection,
            or ``None`` if no connection has been established yet.

        :rtype: ``IStorageServer``
        """


def initialize():
    """Do a postmonkey with the API so your connected to mailchimp API"""


def compute_resize_scale(image_shape, min_side=800, max_side=1333):
    """ Compute an image scale such that the image size is constrained to min_side and max_side.

    Args
        min_side: The image's min side will be equal to min_side after resizing.
        max_side: If after resizing the image's max side is above max_side, resize until the max side is equal to max_side.

    Returns
        A resizing scale.
    """
    rows, cols, _ = image_shape
    smallest_side = min(rows, cols)
    scale = min_side / smallest_side
    largest_side = max(rows, cols)
    if largest_side * scale > max_side:
        scale = max_side / largest_side
    return scale


def align_options(options):
    """
    Indents flags and aligns help texts.
    """
    l = 0
    for opt in options:
        if len(opt[0]) > l:
            l = len(opt[0])
    s = []
    for opt in options:
        s.append('  {0}{1}  {2}'.format(opt[0], ' ' * (l - len(opt[0])),
            opt[1]))
    return '\n'.join(s)


def find_opt_end(options):
    """ Find the end of an option (;) handling escapes. """
    offset = 0
    while True:
        i = options[offset:].find(';')
        if options[offset + i - 1] == '\\':
            offset += 2
        else:
            return offset + i


def getNoMappedReadsStrCheck(inFile, outFiles):
    """File from map-reduce steps may carry no data. This is indicated by
    the string 'no_mapped_reads. This must be caught within the wrappers
    to know when not to exit the algorithm required by the wrapper and
    sebsequently exit gracefully. Given and input and output file variable
    name we create a string of bash code that will check for the 'no_mapped-reads'
    string and will print this to the output file if present (to propogate
    the checking behavior)

    Will take array with multiple output files"""
    noMappedCat = ''
    for outFile in outFiles:
        noMappedCat = (noMappedCat + '\techo no_mapped_reads > $' + outFile +
            '\n')
    return ('# Check for empty files/no data here\nif [ "$(head -1 $' +
        inFile + """)" == "no_mapped_reads" ]; then
	echo "$""" + inFile +
        ' contains no mapped reads... exiting" >> $logFile 2>&1\n' +
        noMappedCat + """	rm -rf $tmpDir
	exit 0
else
	echo "$""" + inFile +
        ' contains mapped reads... continuing" >> $logFile 2>&1\nfi\n\n')


def json_copy_values(destination, source, keys):
    """
    If a key is not present on destination it will be copied from source (if exists)

    destination - destination json
    source - source json
    keys - list of keys
    """
    for key in keys:
        if key not in destination and key in source:
            destination[key] = source[key]


def expand_as_pair(input_):
    """Return a pair of same element if the input is not a pair.
    """
    if isinstance(input_, tuple):
        return input_
    else:
        return input_, input_


def clear_delays(topology):
    """
    Remove all delays from the topology.

    Parameters
    ----------
    topology : Topology
    """
    topology.graph.pop('delay_unit', None)
    for u, v in topology.edges():
        topology.adj[u][v].pop('delay', None)


def urljoin(*args):
    """
    Joins given arguments into a url. Trailing but not leading slashes are
    stripped for each argument.
    """
    return '/'.join(map(lambda x: str(x).strip('/'), args))


def loop_multi_select(ring: bool=False):
    """Select a loop of connected edges by connection type

    :param ring: Ring
    :type ring: bool
    """
    pass


def status_print(first: str, second: str, third: str, indent=0, onetwo_pad=
    ' ', second_tab=55):
    """
    Stylistic status printing for :class:`HDFOverview`.

    :param first: string for 1st column
    :param second: string for 2nd column
    :param third: string for 3rd column
    :param int indent: num. of indentations for 1st column display
    :param str onetwo_pad: one character string for pad style
        between 1st and 2nd column
    :param int second_tab: number of characters between start of string
        and start of 2nd column

    :Example:
        .. code-block:: python

            >>> status_print('one', 'two', 'three', second_tab=15)
            one            two    three
            >>> status_print('one', 'two', 'three', second_tab=15,
            ...              indent=2, onetwo_pad='~')
            |   +-- one    two    three

    """
    note_tab = 7
    if indent == 0:
        str_print = ''
    elif indent == 1:
        str_print = '+-- '
    else:
        str_print = '|   ' * (indent - 1) + '+-- '
    str_print += str(first) + ' '
    str_print = str_print.ljust(second_tab - 1, onetwo_pad) + ' '
    str_print += str(second).ljust(note_tab) + str(third)
    print(str_print)


@staticmethod
def balance(data, *args, **kwargs):
    """
        Returns dict of available balances, with currency names as keys - this ignores
        any amount already involved in a trade (i.e. margin)
        ex.:
            {'BTC': '12.04', 'LTC': '444.12'}
        :param data: requests.response() obj
        :param args:
        :param kwargs:
        :return: dict
        """
    return data


def __gallon_to_liter(gallon: float) ->float:
    """Convert a volume measurement in Gallon to Liter."""
    return gallon * 3.785


def strenumerate(*args, **kwargs):
    """Same as enumerate, but yields str(index)."""
    for i, v in enumerate(*args, **kwargs):
        yield str(i), v


@classmethod
def values(cls):
    """Get a list of deposition type names."""
    return cls.all().values()


def unmute(unselected: bool=False):
    """Unmute (un)selected strips

    :param unselected: Unselected, Unmute unselected rather than selected strips
    :type unselected: bool
    """
    pass


def get_spots_masks(mask):
    """
    takes boolean mask and
    """
    from skimage import measure
    from numpy import where, zeros_like, bool
    blobs = measure.label(mask == 1)
    spots = []
    temp_mask = zeros_like(mask, dtype=bool)
    for blob_number in range(1, blobs.max() + 1):
        these_pixels = where(blobs == blob_number)
        if len(these_pixels[0]) < 1000:
            temp_mask[these_pixels] = True
            spots.append(temp_mask)
    return spots


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.

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


@classmethod
def _manipulate_stripe_object_hook(cls, data):
    """
        Gets called by this object's stripe object conversion method just before
        conversion.
        Use this to populate custom fields in a StripeModel from stripe data.
        """
    return data


def _join_translated(translated_parts, os_sep_class):
    """Join translated glob pattern parts.

    This is different from a simple join, as care need to be taken
    to allow ** to match ZERO or more directories.
    """
    res = ''
    for part in translated_parts[:-1]:
        if part == '.*':
            res += part
        else:
            res += part + os_sep_class
    if translated_parts[-1] == '.*':
        res += '.+'
        res += '({os_sep_class}?.*)?'.format(os_sep_class=os_sep_class)
    else:
        res += translated_parts[-1]
    return res


def _w2i(word):
    """
    Converts strings if possible to integer.
    """
    try:
        return int(word)
    except (ValueError, TypeError):
        return word


def resolveDotted(dotted_or_ep):
    """ Resolve a dotted name or setuptools entry point to a callable.
    """
    from pkg_resources import EntryPoint
    return EntryPoint.parse('x=%s' % dotted_or_ep).resolve()


def save_image_pixels(session, localfile, image_tags=None):
    """
        put a local image on the server and return the URL
        to the METADATA XML record

        @param: session - the local session
        @param: image - an BQImage object
        @param: localfile - a file-like object or name of a localfile

        @return: XML content when upload ok
    """
    xml = None
    if image_tags:
        xml = session.factory.to_string(image_tags)
    return session.postblob(localfile, xml=xml)


def decodefilename(filename):
    """Perforce escapes special characters @, #, *, or %
    with %40, %23, %2A, or %25 respectively

    >>> decodefilename(b'portable-net45%252Bnetcore45%252Bwp8%252BMonoAndroid')
    'portable-net45%2Bnetcore45%2Bwp8%2BMonoAndroid'
    >>> decodefilename(b'//Depot/Directory/%2525/%2523/%23%40.%2A')
    '//Depot/Directory/%25/%23/#@.*'
    """
    replacements = [(b'%2A', b'*'), (b'%23', b'#'), (b'%40', b'@'), (b'%25',
        b'%')]
    for k, v in replacements:
        filename = filename.replace(k, v)
    return filename


@staticmethod
def _clean_up_columns(df, cols):
    """
        Cleans up the additional columns in the DataFrame
        """
    df.drop(cols['next_key'], axis=1, inplace=True)
    df.drop(cols['previous_key'], axis=1, inplace=True)
    df.drop(cols['next_start'], axis=1, inplace=True)
    df.drop(cols['previous_end'], axis=1, inplace=True)
    df.drop(cols['start'], axis=1, inplace=True)
    df.drop(cols['end'], axis=1, inplace=True)
    if cols['clean_start'] in df.columns:
        df.drop(cols['clean_start'], axis=1, inplace=True)
    if cols['clean_end'] in df.columns:
        df.drop(cols['clean_end'], axis=1, inplace=True)


def propertyItems():
    """Return a list of (id,property) tuples.
        """


def jpeg_minify(jpeg, settings: dict):
    """Minify JPEG main function."""
    return jpeg


@classmethod
def get(cls, storage_pool):
    """Get a storage_pool resource for a named pool

        Implements GET /1.0/storage-pools/<pool>/resources

        Needs the 'resources' api extension in the LXD server.

        :param storage_pool: a storage pool object on which to fetch resources
        :type storage_pool: :class:`pylxd.models.storage_pool.StoragePool`
        :returns: A storage resources object
        :rtype: :class:`pylxd.models.storage_pool.StorageResources`
        :raises: :class:`pylxd.exceptions.LXDAPIExtensionNotAvailable` if the
            'resources' api extension is missing.
        """
    storage_pool.client.assert_has_api_extension('resources')
    response = storage_pool.api.resources.get()
    resources = cls(storage_pool.client, **response.json()['metadata'])
    return resources


def pretty_name(name):
    """Converts 'first_name' to 'first name'"""
    if not name:
        return ''
    return name.replace('_', ' ')


def aggregate_roas(rtree):
    """
    remove any supplied prefixes which are superfluous because they are
    already included in another supplied prefix. For example, 203.97.2.0/24
    would be removed if 203.97.0.0/17 was also supplied.
    """
    prefixes = list(rtree.prefixes())
    for prefix in prefixes:
        if not prefix == rtree.search_worst(prefix).prefix:
            rtree.delete(prefix)
    return rtree.prefixes()


@classmethod
def _parse_value(cls, stream_rdr, offset, value_count, value_offset):
    """
        Return the short int value contained in the *value_offset* field of
        this entry. Only supports single values at present.
        """
    if value_count == 1:
        return stream_rdr.read_short(offset, 8)
    else:
        return 'Multi-value short integer NOT IMPLEMENTED'


def reorder_columns(idx, single_session):
    """ Reorder the name of columns

    Parameters
    ----------
    idx             : int
        Dataclass index
    single_session  : boolean
        True if the project is single session

    Returns
    -------
    column          : list or None
        Reordered column
    """
    if idx == 0:
        if single_session:
            return ['Subject', 'DataType', 'Filename', 'Abspath']
        else:
            return ['Subject', 'Session', 'DataType', 'Filename', 'Abspath']
    elif idx == 1:
        if single_session:
            return ['Pipeline', 'Step', 'Subject', 'Filename', 'Abspath']
        else:
            return ['Pipeline', 'Step', 'Subject', 'Session', 'Filename',
                'Abspath']
    elif idx == 2:
        if single_session:
            return ['Pipeline', 'Result', 'Subject', 'Filename', 'Abspath']
        else:
            return ['Pipeline', 'Result', 'Subject', 'Session', 'Filename',
                'Abspath']
    else:
        return None


@staticmethod
def toString(val, join_char='\n'):
    """
        Turn a string or array value into a string.
        """
    if type(val) in (list, tuple):
        return join_char.join(val)
    return val


def b23p_t(temperature):
    """Release on the IAPWS Industrial Formulation 1997 for the Thermodynamic Properties of Water and Steam 1997
      Section 4 Auxiliary Equation for the Boundary between Regions 2 and 3 Eq 5, Page 5"""
    return (348.05185628969 - 1.1671859879975 * temperature +
        0.0010192970039326 * temperature ** 2)


def lambd_H3PO4_H3PO4_PS76(T, P):
    """n-n: phosphoric-acid phosphoric-acid [PS76]."""
    lambd = 0.05031
    valid = T == 298.15
    return lambd, valid


@classmethod
def get_current(cls, app, os_image, tag):
    """
        Given an app, OS image, and a tag, look for a build that matches
        all three and was successfully built (or is currently building).
        If not found, return None.
        """
    builds = cls.objects.filter(app=app, os_image=os_image, tag=tag).exclude(
        status='expired').exclude(status='failed').order_by('-id')
    return next(iter(builds), None)


def _normalize_mac(mac):
    """Convert MAC to a well-known format aa:bb:cc:dd:ee:ff."""
    if '-' in mac:
        mac = mac.split('-', 1)[1]
        mac = mac.replace('-', ':')
    return mac.lower()


@classmethod
def clean_templates(cls, action, instance, pk_set, **kwargs):
    """
        adds organization validation
        """
    templates = cls.clean_templates_org(action, instance, pk_set, **kwargs)
    super().clean_templates(action, instance, templates, **kwargs)


def in_hm3(var):
    """
    Return whether the variant was part of HapMap3
    """
    return var.INFO.get('H3')


def log_target_types(all_logs=False, **kwargs):
    """
    Log targets for log tasks. A log target defines the log types
    that will be affected by the operation. For example, when creating
    a DeleteLogTask, you can specify which log types are deleted.

    :param bool for_alert_event_log: alert events traces (default: False)
    :param bool for_alert_log: alerts (default: False)
    :param bool for_fw_log: FW logs (default: False)
    :param bool for_ips_log: IPS logs (default: False)
    :param bool for_ips_recording: any IPS pcaps (default: False)
    :param bool for_l2fw_log: layer 2 FW logs (default: False)
    :param bool for_third_party_log: any 3rd party logs (default: False)
    :return: dict of log targets
    """
    log_types = {'for_alert_event_log': False, 'for_alert_log': False,
        'for_audit_log': False, 'for_fw_log': False, 'for_ips_log': False,
        'for_ips_recording_log': False, 'for_l2fw_log': False,
        'for_third_party_log': False}
    if all_logs:
        for key in log_types.keys():
            log_types[key] = True
    else:
        for key, value in kwargs.items():
            log_types[key] = value
    return log_types


def provider_parser(subparser):
    """Configure provider parser for Transip"""
    subparser.add_argument('--auth-username', help=
        'specify username for authentication')
    subparser.add_argument('--auth-api-key', help=
        'specify API private key for authentication')


def test_doc(enable: bool=True) ->None:
    """Test whether exported objects have a non-zero docstring. This must be called before the module is imported.

    :param enable:  Determines whether the test should be enabled or disabled.
    """
    global enable_doc_test
    enable_doc_test = enable


@staticmethod
def positional_to_model(value):
    """Converts a positional argument to a model value"""
    return value


@classmethod
def get_default_option(cls):
    """Get default option for migration strategies."""
    return cls.IGNORE.name


def issubclass_safe(value, type_):
    """Determine if value is a subclass of type_

    Will work even value is not a class
    """
    try:
        return issubclass(value, type_)
    except (TypeError, AttributeError):
        return False


def entry_in_entries(entry, entries, mac, serial):
    """Check if a device entry is in a list of device entries."""
    if mac is None and serial is None:
        return entry in entries
    for item in entries:
        if item.description is not None:
            e_device = item.description.get('device', {})
            e_mac = e_device.get('macAddress')
            e_serial = e_device.get('serialNumber')
        else:
            e_mac = None
            e_serial = None
        if e_mac == mac and e_serial == serial and item.st == entry.st:
            return True
    return False


def isdir(path):
    """Reproduces the behavior of :func:`os.path.isdir` for HPSS files.

    Parameters
    ----------
    path : :class:`str`
        Path to the file.

    Returns
    -------
    :class:`bool`
        ``True`` if `path` is a directory.
    """
    from ._os import stat
    return stat(path).isdir


def multidict(D):
    """creates a multidictionary"""
    keys = list(D.keys())
    if len(keys) == 0:
        return [[]]
    try:
        N = len(D[keys[0]])
        islist = True
    except:
        N = 1
        islist = False
    dlist = [dict() for d in range(N)]
    for k in keys:
        if islist:
            for i in range(N):
                dlist[i][k] = D[k][i]
        else:
            dlist[0][k] = D[k]
    return [keys] + dlist


@staticmethod
def gen_file_header(file_path, inode_str_struct):
    """Generate file header for rsync binary data file

        :param file_path: file path
        :param inode_str_struct: file binary string including inode data
        :return: chunk of binary data to be processed on the next iteration
        """
    start_of_block = b'\x00{}\x00'.format(file_path)
    header_size = len(start_of_block) + len(inode_str_struct)
    header_size += len(str(header_size))
    file_header = b'{}{}{}'.format(header_size, start_of_block,
        inode_str_struct)
    len_file_header = len(file_header)
    if header_size != len_file_header:
        file_header_list = file_header.split('\x00')
        file_header_list = file_header_list[1:]
        file_header_list.insert(0, str(len_file_header))
        file_header = '\x00'.join(file_header_list)
    return file_header


@classmethod
def remove(cls, name):
    """Remove provider from the registry, if it exists."""
    if name in cls._REGISTRY:
        del cls._REGISTRY[name]


def chunks(seq, size):
    """Generator that cuts sequence (bytes, memoryview, etc.)
     into chunks of given size. If `seq` length is not multiply
     of `size`, the lengh of the last chunk returned will be
     less than requested.

     >>> list( chunks([1,2,3,4,5,6,7], 3) )
     [[1, 2, 3], [4, 5, 6], [7]]
    """
    d, m = divmod(len(seq), size)
    for i in range(d):
        yield seq[i * size:(i + 1) * size]
    if m:
        yield seq[d * size:]


def validate_string(value, choices=None):
    """Validate string."""
    if not isinstance(value, str):
        raise ValueError(f'Value {value} should be a string.')
    if choices and value not in choices:
        choices_ = ', '.join(choices)
        raise ValueError(f'Value {value} should be one of {choices_}.')


def xsd_error_log_string(xsd_error_log):
    """Return a human-readable string representation of the error log
    returned by lxml's XMLSchema validator.
    """
    ret = []
    for error in xsd_error_log:
        ret.append('ERROR ON LINE {}: {}'.format(error.line, error.message.
            encode('utf-8')))
    return '\n'.join(ret)


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 syevd(A=None, out=None, name=None, **kwargs):
    """Eigendecomposition for symmetric matrix.
    Input is a tensor *A* of dimension *n >= 2*.

    If *n=2*, *A* must be symmetric, of shape *(x, x)*. We compute the eigendecomposition,
    resulting in the orthonormal matrix *U* of eigenvectors, shape *(x, x)*, and the
    vector *L* of eigenvalues, shape *(x,)*, so that:

       *U* \\* *A* = *diag(L)* \\* *U*

    Here:

       *U* \\* *U*\\ :sup:`T` = *U*\\ :sup:`T` \\* *U* = *I*

    where *I* is the identity matrix. Also, *L(0) <= L(1) <= L(2) <= ...* (ascending order).

    If *n>2*, *syevd* is performed separately on the trailing two dimensions of *A* (batch
    mode). In this case, *U* has *n* dimensions like *A*, and *L* has *n-1* dimensions.

    .. note:: The operator supports float32 and float64 data types only.

    .. note:: Derivatives for this operator are defined only if *A* is such that all its
              eigenvalues are distinct, and the eigengaps are not too small. If you need
              gradients, do not apply this operator to matrices with multiple eigenvalues.

    Examples::

       Single symmetric eigendecomposition
       A = [[1., 2.], [2., 4.]]
       U, L = syevd(A)
       U = [[0.89442719, -0.4472136],
            [0.4472136, 0.89442719]]
       L = [0., 5.]

       Batch symmetric eigendecomposition
       A = [[[1., 2.], [2., 4.]],
            [[1., 2.], [2., 5.]]]
       U, L = syevd(A)
       U = [[[0.89442719, -0.4472136],
             [0.4472136, 0.89442719]],
            [[0.92387953, -0.38268343],
             [0.38268343, 0.92387953]]]
       L = [[0., 5.],
            [0.17157288, 5.82842712]]

    Defined in src/operator/tensor/la_op.cc:L868

    Parameters
    ----------
    A : NDArray
        Tensor of input matrices to be factorized

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

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


def __iter__():
    """Return an iterator over all of this file's data"""


def check_valid_object_name(sequence):
    """Check that the names of the objects are all different."""
    names = []
    for o in sequence:
        if o.__name__ in names:
            raise ValueError(
                'A tallyable PyMC object called %s already exists. This will cause problems for some database backends.'
                 % o.__name__)
        else:
            names.append(o.__name__)


@classmethod
def from_named_function(cls, function):
    """Make a :class:`SassFunction` object from the named ``function``.
        Function name and arguments are automatically inspected.

        :param function: the named function to be called
        :type function: :class:`types.FunctionType`
        :returns: a custom function wrapper of the ``function``
        :rtype: :class:`SassFunction`

        """
    if not getattr(function, '__name__', ''):
        raise TypeError('function must be named')
    return cls.from_lambda(function.__name__, function)


def count_front(s: str) ->int:
    """Count the number of leading dashes on a string."""
    for position, element in enumerate(s):
        if element != '-':
            return position


@staticmethod
def callback(t, q, v, out):
    """
        @brief Callback method for the simulation.
        """
    pass


def get_paginator(operation_name=None):
    """
    Create a paginator for an operation.

    :type operation_name: string
    :param operation_name: The operation name. This is the same name
            as the method name on the client. For example, if the
            method name is create_foo, and you'd normally invoke the
            operation as client.create_foo(**kwargs), if the
            create_foo operation can be paginated, you can use the
            call client.get_paginator('create_foo').

    :rtype: L{botocore.paginate.Paginator}
    """
    pass


def create_user_res(serial_list, all_atoms, chain_selected, used_atoms,
    user_res_names):
    """Creates a customized BioPython Residue object corresponding to a user specified residue.

    Parameters
    ----------
    serial_list: list of int
        List of atom serial numbers included in residue
    all_atoms: list of :class:`Bio.PDB.Atom.Atom`
        All atoms in protein on selected chains
    chain_selected: list of str
        Chains included in analysis
    used_atoms: list of :class:`Bio.PDB.Atom.Atom`
        Atoms already included in analysis
    user_res_names: list of str
        User residue names already included in the analysis.

    Returns
    -------
    user_res: :class:`Bio.PDB.Residue.Residue`
        Customized residue object corresponding to the atoms in serial_list

    """
    source_res = []
    atm_list = []
    for atm in all_atoms:
        if atm.serial_number in serial_list:
            if atm.serial_number in used_atoms:
                message = 'Invalid atom serial number range. Atom ' + str(atm
                    .serial_number
                    ) + ' is already included in another residue.'
                raise ValueError(message)
            if atm.parent.parent.id not in chain_selected:
                message = 'Invalid atom serial number range. Atom ' + str(atm
                    .serial_number) + ' is in chain ' + str(atm.parent.
                    parent.id) + '.'
                raise ValueError(message)
            atm.get_full_id()
            if not source_res:
                source_res = atm.parent
            atm.get_full_id()
            atm_copy = atm.copy()
            atm_list.append(atm_copy)
    source_res.get_full_id()
    user_res = source_res.copy()
    for atm in list(source_res.get_atoms()):
        user_res.detach_child(atm.id)
    for atm in atm_list:
        user_res.add(atm)
    k = 1
    name = 'CUST'
    name += '-'
    while name + str(k) in user_res_names:
        k += 1
    user_res_names.append(name + str(k))
    user_res.resname = name + str(k)
    user_res.node_label = user_res.resname
    return user_res


def selected_currency_code(session_key):
    """Returns selected currency code from session."""


@classmethod
def route_prefix(cls):
    """Override this to define the API route namespace for these resources"""
    return None


def ensure_array(exemplar, item):
    """Coerces *item* to be an array (linear sequence); if *item* is
    already an array it is returned unchanged.  Otherwise, an array of
    the same length as exemplar is created which contains *item* at
    every index.  The fresh array is returned.
    """
    try:
        item[0]
        return item
    except TypeError:
        return (item,) * len(exemplar)


def edge_face_add():
    """Add an edge or face to selected

    """
    pass


def convert_datetime_to_string(date):
    """
    >>> x = datetime(2017, 5, 16)
    >>> convert_datetime_to_string(x)
    '2017-05-16'
    """
    return date.strftime('%Y-%m-%d')


def make_result(text, weight_map):
    """ Extract the (possibly-empty) list of country codes with the highest weight.
    Order is not significant.
    @param text: the original text
    @param weight_map: a weight map (country codes as keys, weights as values)
    @returns: a list of country codes (may be empty)
    """
    max_keys = []
    max_score = 0
    if weight_map:
        for key in weight_map:
            if weight_map[key] > max_score:
                max_keys = [key]
                max_score = weight_map[key]
            elif weight_map[key] == max_score:
                max_keys.append(key)
    return {'text': text, 'status': True if max_score > 0 else False,
        'score': max_score, 'countries': max_keys}


def select_split():
    """Select only entirely selected faces

    """
    pass


def cleanup_tail(options):
    """ cleanup the tail of a recovery """
    if options.kwargs['omode'] == 'csv':
        options.kwargs['fd'].write('\n')
    elif options.kwargs['omode'] == 'xml':
        options.kwargs['fd'].write('\n</results>\n')
    else:
        options.kwargs['fd'].write('\n]\n')


def c_to_f(c):
    """
    Convert celcius to fahrenheit
    """
    return c * 1.8 + 32.0


def canon_pairwise_tag(tag: str) ->str:
    """
    Canonicalize pairwise tag to specify unencrypted storage.

    :param tag: input tag
    :return: tag prefixed with '~' if not already
    """
    return '{}{}'.format('' if str(tag).startswith('~') else '~', tag)


def formula(foyer_fiscal, period, parameters):
    """
        Impôt après imputation des réductions d'impôt
        """
    ip_net = foyer_fiscal('ip_net', period)
    reductions = foyer_fiscal('reductions', period)
    return ip_net - reductions


def files():
    """Obtain paths that are backing storage for this manifest.

        TODO this is used by verify and there should probably be a better API
        for this functionality.
        """


def log_only(path_output_log, text_log):
    """
    Write the log to the file only
    """
    with open(path_output_log, 'a') as fileLog:
        fileLog.write(text_log)
        fileLog.write('\n')


def ray_quadric_intersection_image_filter(*args, **kwargs):
    """Procedural interface for RayQuadricIntersectionImageFilter"""
    import itk
    instance = itk.RayQuadricIntersectionImageFilter.New(*args, **kwargs)
    return instance.__internal_call__()


def dict2args(dictionary):
    """
    Generates an arguments list from a dictionary.

    ``dict2args(<dictionary>)``

    ``dictionary`` (dictionary)
      Dictionary to process.

    returns
      list - Arguments list.

    Example
    =======

    .. code:: python

        docutils_argv = {
            "report": "info",
            "strip-comments": True,
            "pep-references": True,
            "rfc-references": True,
            "syntax-highlight": "short",
            "tab-width": 4,
            "xml-declaration": True
        }

        dict2args(docutils_argv)
    """
    args = []
    for key, value in dictionary.items():
        arg = '-'
        if len(key) > 1:
            arg += '-'
        arg += key
        if not isinstance(value, bool):
            arg += '=' + str(value)
        args.append(arg)
    return args


@staticmethod
def get_xml_element(element, element_name, default=None):
    """
        Method to retrieve the data from the xml tree

        :type element: String
        :param element: The xml element
        :type element_name: String
        :param element_name: The property
        :type default: String
        :param default: What to set default to

        :rtype: String
        :return: A String

        """
    child = element.find('.//{DAV:}' + element_name)
    return default if child is None else child.text


def setdomain(value):
    """
    Sets the default domain for remote access.
    """
    global NX_DOMAIN
    NX_DOMAIN = value


def _llc_face_shape(llc_id):
    """Given an integer identifier for the llc grid, return the face shape."""
    if llc_id in (90, 270, 1080, 2160, 4320):
        return llc_id, llc_id
    else:
        raise ValueError('%g is not a valid llc identifier' % llc_id)


@staticmethod
def getCreateTable():
    """Create the table to hold the URLs"""
    return 'create table url (url char(256))'


def _add_edge(g, u, v):
    """Add edge to graph or increase edge weight."""
    if g.has_edge(u, v):
        g.edge[u][v]['weight'] += 1
    else:
        g.add_edge(u, v, {'weight': 1})
    return g


def _us_to_s(time_us):
    """Convert [us] into (float) [s]
    """
    return float(time_us) / 1000000.0


@staticmethod
def replace_celcius(string):
    """
         Replaces u'celsius' with 'fahrenheit' in the provided string.

        Returns:
             string: The modified string
        """
    return string.replace(u'celsius', u'fahrenheit')


def _is_in_group(opt, group):
    """Check if opt is in group."""
    for value in group._opts.values():
        if not value['opt'] != opt:
            return True
    return False


def snd(pair):
    """Return the second element of pair
    """
    return pair[1]


def disable_notebook():
    """Disable the automatic display of figures in the IPython Notebook.

    See Also
    --------
    :func:`enable_notebook` : automatically embed figures in IPython notebook
    """
    try:
        from IPython.core.getipython import get_ipython
        from matplotlib.figure import Figure
    except ImportError:
        raise ImportError('This feature requires IPython 1.0+ and Matplotlib')
    ip = get_ipython()
    formatter = ip.display_formatter.formatters['text/html']
    formatter.type_printers.pop(Figure, None)


def middle_drop(progress):
    """
    Returns a linear value with a drop near the middle to a constant value for the Scheduler

    :param progress: (float) Current progress status (in [0, 1])
    :return: (float) 1 - progress if (1 - progress) >= 0.75 else 0.075
    """
    eps = 0.75
    if 1 - progress < eps:
        return eps * 0.1
    return 1 - progress


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


def describe_prefix_lists(DryRun=None, PrefixListIds=None, Filters=None,
    MaxResults=None, NextToken=None):
    """
    Describes available AWS services in a prefix list format, which includes the prefix list name and prefix list ID of the service and the IP address range for the service. A prefix list ID is required for creating an outbound security group rule that allows traffic from a VPC to access an AWS service through a VPC endpoint.
    See also: AWS API Documentation

    :example: response = client.describe_prefix_lists(
        DryRun=True|False,
        PrefixListIds=[
            'string',
        ],
        Filters=[
            {
                'Name': 'string',
                'Values': [
                    '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 PrefixListIds: list
    :param PrefixListIds: One or more prefix list IDs.
            (string) --

    :type Filters: list
    :param Filters: One or more filters.
            prefix-list-id : The ID of a prefix list.
            prefix-list-name : The name of a prefix list.
            (dict) --A filter name and value pair that is used to return a more specific list of results. Filters can be used to match a set of resources by various criteria, such as tags, attributes, or IDs.
            Name (string) --The name of the filter. Filter names are case-sensitive.
            Values (list) --One or more filter values. Filter values are case-sensitive.
            (string) --

    :type MaxResults: integer
    :param MaxResults: The maximum number of items to return for this request. The request returns a token that you can specify in a subsequent call to get the next set of results.
            Constraint: If the value specified is greater than 1000, we return only 1000 items.

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

    :rtype: dict
    :return: {
        'PrefixLists': [
            {
                'PrefixListId': 'string',
                'PrefixListName': 'string',
                'Cidrs': [
                    'string',
                ]
            },
        ],
        'NextToken': 'string'
    }

    :returns:
    (string) --

    """
    pass


def PaneSortFunc(p1, p2):
    """
    This function is used to sort panes by dock position.

    :param `p1`: the first pane instance to compare, an instance of :class:`AuiPaneInfo`;
    :param `p2`: the second pane instance to compare, an instance of :class:`AuiPaneInfo`.
    """
    return (p1.dock_pos < p2.dock_pos and [-1] or [1])[0]


def to_iterable(value, allow_none=True):
    """
    Tries to convert the given value to an iterable, if necessary.
    If the given value is a list, a list is returned; if it is a string, a list
    containing one string is returned, ...

    :param value: Any object
    :param allow_none: If True, the method returns None if value is None, else
                       it returns an empty list
    :return: A list containing the given string, or the given value
    """
    if value is None:
        if allow_none:
            return None
        return []
    elif isinstance(value, (list, tuple, set, frozenset)):
        return value
    return [value]


def layer_next():
    """Switch to editing action in animation layer above the current action in the NLA Stack

    """
    pass


def _max_line_width(s):
    """
    Visible width of a potentially multinie content.

    >>> _max_line_width('this\\nis\\na\\nmultiline\\ntext')
    9

    """
    if not s:
        return 0
    return max(map(len, s.splitlines()))


def switch_view_update():
    """Update views of selected node

    """
    pass


def parse_file(filename):
    """ Parses message information from ccnd log files

        filename: path to ccndlog file

    """
    faces = dict()
    sep = ' '
    with open(filename, 'r') as f:
        data = []
        for line in f:
            cols = line.strip().split(sep)
            if line.find('accepted datagram client') > -1:
                face_id = cols[5].replace('id=', '')
                ip = cols[7]
                port = cols[9]
                faces[face_id] = ip, port
                continue
            if line.find('releasing face id') > -1:
                face_id = cols[5]
                if face_id in faces:
                    del faces[face_id]
                continue
            if len(cols) < 6:
                continue
            timestamp = cols[0]
            message_type = cols[3]
            if message_type not in ['interest_from', 'interest_to',
                'content_from', 'content_to', 'interest_dupnonce',
                'interest_expiry']:
                continue
            face_id = cols[4]
            content_name = cols[5]
            nonce = ''
            if message_type in ['interest_from', 'interest_to',
                'interest_dupnonce']:
                last = cols[-1]
                if len(last.split('-')) == 5:
                    nonce = last
            try:
                size = int(cols[6].replace('(', ''))
            except:
                print('interest_expiry without face id!', line)
                continue
            peer = 'localhost'
            if face_id in faces:
                peer, port = faces[face_id]
            data.append((content_name, timestamp, message_type, peer,
                face_id, size, nonce, line))
    return data


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

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

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


@classmethod
def set_class_maintenance_message(cls, maintenance_message):
    """Set class maintenance message.

        It will be returned if bot is under maintenance, unless and instance
            `_maintenance_message` is set.
        """
    cls._maintenance_message = maintenance_message


def parse_contaminations(file):
    """
    Parse contamination file.
    example:
    ==============================
    Pirisoci	Alveolata	group
    DiplDSTH	GoniavonGEN	org
    Fucucera	Ochrophyta	subtax
    ==============================
    input: tab separated file with contaminations
    result: dictionary with organism as key and tuple with taxonomy
            and rank
    """
    cont_dict = {}
    for line in open(file):
        org, tax, rank = line.split('\t')
        cont_dict[org] = tax, rank.strip()
    return cont_dict


@classmethod
def from_python(cls, level: int) ->'LogLevel':
    """Map Python log level to katcp log level"""
    try:
        return cls(level)
    except ValueError:
        ans = cls.ALL
        for member in cls.__members__.values():
            if member > ans and member <= level and member != cls.OFF:
                ans = member
        return member


def pronounce(phonemes: str, pitch: int=64, speed: int=72, mouth: int=128,
    throat: int=128) ->None:
    """
    Pronounce the phonemes in the string phonemes. See below for details of how
    to use phonemes to finely control the output of the speech synthesiser.
    Override the optional pitch, speed, mouth and throat settings to change
    the timbre (quality) of the voice.
    """