def add_hyperband_arguments(parser):
    """
    Add arguments to a parser for sub-command "stitch"
    :param parser: argeparse object
    :return:
    """
    parser.add_argument('--train_image_dir', type=str, required=True, help=
        'Path to directory containing labeled images for training.')
    parser.add_argument('--test_image_dir', type=str, required=True, help=
        'Path to directory containing labeled images for testing the models.')
    parser.add_argument('--gpu_mode', action='store_true', help=
        'If true then cuda is on.')
    parser.add_argument('--output_dir', type=str, required=False, default=
        './debug_output', help='Output file name.')
    parser.add_argument('--batch_size', type=int, required=False, default=
        100, help='Batch size for training, default is 100.')
    parser.add_argument('--max_epochs', type=int, required=False, default=
        10, help='Epoch size for training iteration.')
    parser.add_argument('--num_workers', type=int, required=False, default=
        40, help='Epoch size for training iteration.')
    return parser


def test_empty_functions():
    """
    This is a test function.
    This should be replaced with 'def test_empty_functions(): 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


@classmethod
def get_last(cls, **filters) ->dict:
    """
        Return last revision of the document matching provided filters.
        """
    return cls.get(**filters)


def _check_dev_type(devices, dev_list):
    """
    Function used for checking weather the "devices" field only contain devices used during the
    acquisition.

    ----------
    Parameters
    ----------
    devices : list ["mac_address_1" <str>, "mac_address_2" <str>...]
        List of devices selected by the user.

    dev_list : list
        List of available devices in the acquisition file.

    Returns
    -------
    out : list
        Returns a standardized list of devices.

    """
    if devices is not None:
        for device in devices:
            if device in dev_list:
                continue
            else:
                raise RuntimeError(
                    'At least one of the specified devices is not available in the acquisition file.'
                    )
        out = devices
    else:
        out = dev_list
    return out


@classmethod
def get_name(cls):
    """get command name as used from command line"""
    return cls.name or cls.__name__.lower()


@classmethod
def _from_dict(cls, _dict):
    """Initialize a NluEnrichmentConcepts object from a json dictionary."""
    args = {}
    if 'limit' in _dict:
        args['limit'] = _dict.get('limit')
    return cls(**args)


def getSubclassFromModule_(module, class_):
    """Get the subclass of a class from a specific module."""
    name = class_.__name__ + 'Sub'
    if hasattr(module, name):
        return getattr(module, name)
    else:
        return None


def _calc_mdd_4_drawback_analysis(pair, y):
    """
    此函数仅供 drawback_analysis 使用
    用于计算最大回撤使用
    :param pair:
    :param y:
    :return:
    """
    max_y_last = pair[0]
    max_y = max_y_last if max_y_last > y else y
    mdd_last = pair[1]
    keep_max = pair[2]
    dd = y / max_y - 1
    if keep_max:
        mdd = dd if dd < mdd_last else mdd_last
    else:
        mdd = dd
    return max_y, mdd, keep_max


def get_layer_id(model_table, layer_name):
    """
    Get ID of layer from deep learning model

    Parameters
    ----------
    model_table : :class:`CASTable`
        CASTable of the deep learning model.
    layer_name : str
        Name of the layer.

    Returns
    -------
    int
        ID of the layer

    """
    return int(model_table.query('_DLKey0_ = "{}"'.format(layer_name.lower(
        ))).fetch()['Fetch'].iloc[0]['_DLLayerID_'])


def listenUNIXDatagram(address, protocol, maxPacketSize=8192, mode=438):
    """
        Listen on a datagram UNIX socket.

        @param address: a path to a unix socket on the filesystem.

        @param protocol: a L{twisted.internet.protocol.DatagramProtocol} instance.

        @param maxPacketSize: maximum packet size to accept

        @param mode: The mode (B{not} umask) to set on the unix socket.  See
            platform specific documentation for information about how this
            might affect connection attempts.
        @type mode: C{int}

        @return: An object which provides L{IListeningPort}.
        """


def replace(folder, reindex=False):
    """ Replace all the indexes in ``folder`` with the ones implied by this
        factory.  Reindex any added indexes if ``reindex`` is true."""


def EulerStep(x0, dt, fv, direction=1.0):
    """
	This Function will take a step in the direction of the field at the
	point x0.

	Inputs:
		x0: initial location vector.
		dt: Step size.
		fv: Callable function which provides a field vector given a
			positional vector.
		direction: direction in which to trace, +1.0 will trace along
		the field direction, -1.0 will trace in the opposite direction.

	Returns:
		new positional vector of the same form as x0.
	"""
    v0 = direction * fv(x0)
    x1 = x0 + dt * v0[:, (0)]
    return x1


def dw_WriteBoundData(fname, boundflow_labels):
    """
    writes B5\\_bounddata.inc
    """
    exfile = open(fname, 'w')
    print(';Written by dw_WriteBoundData', file=exfile)
    for i in boundflow_labels:
        print("ITEM '%s'" % i, file=exfile)
        print("CONCENTRATION  '%s' 'Check' 'Initial'" % i, file=exfile)
        print('DATA', file=exfile)
        print('1.0  1.0  0.0', file=exfile)
        print('', file=exfile)
    exfile.close()


@classmethod
def add_application_properties(cls, application, new_groups,
    add_default_group=True, **kwargs):
    """Add argparse properties for an application

        If the application does not exist, the application will be added in
        the applications properties storage.

        new_groups: extend the existing groups defined. If no group is defined
        before, this extend the groups of the default application.

        :param application: the name of the application
        :param new_groups: list of the configuration groups
        :param add_default_group: if True the default groups will be add
        :params kwargs: other properties to change
        """
    if application not in cls.applications:
        cls.applications[application] = {}
    app = cls.applications[application]
    if kwargs:
        app.update(kwargs)
    if new_groups:
        if 'configuration_groups' not in app:
            app['configuration_groups'] = []
            if add_default_group:
                app['configuration_groups'].extend(cls.applications[
                    'default']['configuration_groups'])
        cg = app['configuration_groups']
        for new_group in new_groups:
            if new_group not in cg:
                cg.append(new_group)


def get_roles_for_permission(permission):
    """Return the role grants for the permission

        The role grants are an iterable of role, setting tuples, where
        setting is either Allow or Deny.
        """


def delDotPrefix(string):
    """Delete dot prefix to file extension if present"""
    return string[1:] if string.find('.') == 0 else string


def can_set_not_paid(payment):
    """If it can be set as not paid once it has been paid

        :param payment: the payment to be set as not paid
        """


@classmethod
def filter(cls, **kwargs: dict) ->'QuerySet<Meta.Model>':
    """
        Shortcut for filter method of model
        return: QuerySet<Model>
        """
    return cls.Meta.model.objects.filter(**kwargs)


def remove_www(hostname):
    """
    Removes ``www``. from the beginning of the address. Only for
    routing purposes. ``www.test.com/login/`` and ``test.com/login/`` should
    find the same tenant.
    """
    if hostname.startswith('www.'):
        return hostname[4:]
    return hostname


def find_source(node):
    """Locate source code for *node*. Returns a list of strings."""
    if node.filename == '' or node.filename is None:
        return
    lines = open(node.filename, 'r').readlines()
    if isinstance(node.lineno, slice):
        lineno = slice(node.lineno.start - 1, node.lineno.stop - 1)
    else:
        lineno = node.lineno - 1
    return lines[lineno]


def search(cursor=None, expr=None, facet=None, filterQuery=None, highlight=
    None, partial=None, query=None, queryOptions=None, queryParser=None,
    returnFields=None, size=None, sort=None, start=None, stats=None):
    """
    Retrieves a list of documents that match the specified search criteria. How you specify the search criteria depends on which query parser you use. Amazon CloudSearch supports four query parsers:
    For more information, see Searching Your Data in the Amazon CloudSearch Developer Guide .
    The endpoint for submitting Search requests is domain-specific. You submit search requests to a domain's search endpoint. To get the search endpoint for your domain, use the Amazon CloudSearch configuration service DescribeDomains action. A domain's endpoints are also displayed on the domain dashboard in the Amazon CloudSearch console.
    See also: AWS API Documentation

    :example: response = client.search(
        cursor='string',
        expr='string',
        facet='string',
        filterQuery='string',
        highlight='string',
        partial=True|False,
        query='string',
        queryOptions='string',
        queryParser='simple'|'structured'|'lucene'|'dismax',
        returnFields='string',
        size=123,
        sort='string',
        start=123,
        stats='string'
    )

    :type cursor: string
    :param cursor: Retrieves a cursor value you can use to page through large result sets. Use the size parameter to control the number of hits to include in each response. You can specify either the cursor or start parameter in a request; they are mutually exclusive. To get the first cursor, set the cursor value to initial . In subsequent requests, specify the cursor value returned in the hits section of the response.
            For more information, see Paginating Results in the Amazon CloudSearch Developer Guide .

    :type expr: string
    :param expr: Defines one or more numeric expressions that can be used to sort results or specify search or filter criteria. You can also specify expressions as return fields.
            You specify the expressions in JSON using the form {'EXPRESSIONNAME':'EXPRESSION'} . You can define and use multiple expressions in a search request. For example:
            {'expression1':'_score*rating', 'expression2':'(1/rank)*year'}
            For information about the variables, operators, and functions you can use in expressions, see Writing Expressions in the Amazon CloudSearch Developer Guide .

    :type facet: string
    :param facet: Specifies one or more fields for which to get facet information, and options that control how the facet information is returned. Each specified field must be facet-enabled in the domain configuration. The fields and options are specified in JSON using the form {'FIELD':{'OPTION':VALUE,'OPTION:'STRING'},'FIELD':{'OPTION':VALUE,'OPTION':'STRING'}} .
            You can specify the following faceting options:
            buckets specifies an array of the facet values or ranges to count. Ranges are specified using the same syntax that you use to search for a range of values. For more information, see Searching for a Range of Values in the Amazon CloudSearch Developer Guide . Buckets are returned in the order they are specified in the request. The sort and size options are not valid if you specify buckets .
            size specifies the maximum number of facets to include in the results. By default, Amazon CloudSearch returns counts for the top 10. The size parameter is only valid when you specify the sort option; it cannot be used in conjunction with buckets .
            sort specifies how you want to sort the facets in the results: bucket or count . Specify bucket to sort alphabetically or numerically by facet value (in ascending order). Specify count to sort by the facet counts computed for each facet value (in descending order). To retrieve facet counts for particular values or ranges of values, use the buckets option instead of sort .
            If no facet options are specified, facet counts are computed for all field values, the facets are sorted by facet count, and the top 10 facets are returned in the results.
            To count particular buckets of values, use the buckets option. For example, the following request uses the buckets option to calculate and return facet counts by decade.
            {'year':{'buckets':['[1970,1979]','[1980,1989]','[1990,1999]','[2000,2009]','[2010,}']}}
            To sort facets by facet count, use the count option. For example, the following request sets the sort option to count to sort the facet values by facet count, with the facet values that have the most matching documents listed first. Setting the size option to 3 returns only the top three facet values.
            {'year':{'sort':'count','size':3}}
            To sort the facets by value, use the bucket option. For example, the following request sets the sort option to bucket to sort the facet values numerically by year, with earliest year listed first.
            {'year':{'sort':'bucket'}}
            For more information, see Getting and Using Facet Information in the Amazon CloudSearch Developer Guide .

    :type filterQuery: string
    :param filterQuery: Specifies a structured query that filters the results of a search without affecting how the results are scored and sorted. You use filterQuery in conjunction with the query parameter to filter the documents that match the constraints specified in the query parameter. Specifying a filter controls only which matching documents are included in the results, it has no effect on how they are scored and sorted. The filterQuery parameter supports the full structured query syntax.
            For more information about using filters, see Filtering Matching Documents in the Amazon CloudSearch Developer Guide .

    :type highlight: string
    :param highlight: Retrieves highlights for matches in the specified text or text-array fields. Each specified field must be highlight enabled in the domain configuration. The fields and options are specified in JSON using the form {'FIELD':{'OPTION':VALUE,'OPTION:'STRING'},'FIELD':{'OPTION':VALUE,'OPTION':'STRING'}} .
            You can specify the following highlight options:
            format : specifies the format of the data in the text field: text or html . When data is returned as HTML, all non-alphanumeric characters are encoded. The default is html .
            max_phrases : specifies the maximum number of occurrences of the search term(s) you want to highlight. By default, the first occurrence is highlighted.
            pre_tag : specifies the string to prepend to an occurrence of a search term. The default for HTML highlights is lt;emgt; . The default for text highlights is * .
            post_tag : specifies the string to append to an occurrence of a search term. The default for HTML highlights is lt;/emgt; . The default for text highlights is * .
            If no highlight options are specified for a field, the returned field text is treated as HTML and the first match is highlighted with emphasis tags: lt;emsearch-termlt;/emgt; .
            For example, the following request retrieves highlights for the actors and title fields.
            { 'actors': {}, 'title': {'format': 'text','max_phrases': 2,'pre_tag': '**','post_tag': '** '} }

    :type partial: boolean
    :param partial: Enables partial results to be returned if one or more index partitions are unavailable. When your search index is partitioned across multiple search instances, by default Amazon CloudSearch only returns results if every partition can be queried. This means that the failure of a single search instance can result in 5xx (internal server) errors. When you enable partial results, Amazon CloudSearch returns whatever results are available and includes the percentage of documents searched in the search results (percent-searched). This enables you to more gracefully degrade your users' search experience. For example, rather than displaying no results, you could display the partial results and a message indicating that the results might be incomplete due to a temporary system outage.

    :type query: string
    :param query: [REQUIRED]
            Specifies the search criteria for the request. How you specify the search criteria depends on the query parser used for the request and the parser options specified in the queryOptions parameter. By default, the simple query parser is used to process requests. To use the structured , lucene , or dismax query parser, you must also specify the queryParser parameter.
            For more information about specifying search criteria, see Searching Your Data in the Amazon CloudSearch Developer Guide .

    :type queryOptions: string
    :param queryOptions: Configures options for the query parser specified in the queryParser parameter. You specify the options in JSON using the following form {'OPTION1':'VALUE1','OPTION2':VALUE2'...'OPTIONN':'VALUEN'}.
            The options you can configure vary according to which parser you use:
            defaultOperator : The default operator used to combine individual terms in the search string. For example: defaultOperator: 'or' . For the dismax parser, you specify a percentage that represents the percentage of terms in the search string (rounded down) that must match, rather than a default operator. A value of 0% is the equivalent to OR, and a value of 100% is equivalent to AND. The percentage must be specified as a value in the range 0-100 followed by the percent (%) symbol. For example, defaultOperator: 50% . Valid values: and , or , a percentage in the range 0%-100% (dismax ). Default: and (simple , structured , lucene ) or 100 (dismax ). Valid for: simple , structured , lucene , and dismax .
            fields : An array of the fields to search when no fields are specified in a search. If no fields are specified in a search and this option is not specified, all text and text-array fields are searched. You can specify a weight for each field to control the relative importance of each field when Amazon CloudSearch calculates relevance scores. To specify a field weight, append a caret (^ ) symbol and the weight to the field name. For example, to boost the importance of the title field over the description field you could specify: 'fields':['title^5','description'] . Valid values: The name of any configured field and an optional numeric value greater than zero. Default: All text and text-array fields. Valid for: simple , structured , lucene , and dismax .
            operators : An array of the operators or special characters you want to disable for the simple query parser. If you disable the and , or , or not operators, the corresponding operators (+ , | , - ) have no special meaning and are dropped from the search string. Similarly, disabling prefix disables the wildcard operator (* ) and disabling phrase disables the ability to search for phrases by enclosing phrases in double quotes. Disabling precedence disables the ability to control order of precedence using parentheses. Disabling near disables the ability to use the ~ operator to perform a sloppy phrase search. Disabling the fuzzy operator disables the ability to use the ~ operator to perform a fuzzy search. escape disables the ability to use a backslash (\\ ) to escape special characters within the search string. Disabling whitespace is an advanced option that prevents the parser from tokenizing on whitespace, which can be useful for Vietnamese. (It prevents Vietnamese words from being split incorrectly.) For example, you could disable all operators other than the phrase operator to support just simple term and phrase queries: 'operators':['and','not','or', 'prefix'] . Valid values: and , escape , fuzzy , near , not , or , phrase , precedence , prefix , whitespace . Default: All operators and special characters are enabled. Valid for: simple .
            phraseFields : An array of the text or text-array fields you want to use for phrase searches. When the terms in the search string appear in close proximity within a field, the field scores higher. You can specify a weight for each field to boost that score. The phraseSlop option controls how much the matches can deviate from the search string and still be boosted. To specify a field weight, append a caret (^ ) symbol and the weight to the field name. For example, to boost phrase matches in the title field over the abstract field, you could specify: 'phraseFields':['title^3', 'plot'] Valid values: The name of any text or text-array field and an optional numeric value greater than zero. Default: No fields. If you don't specify any fields with phraseFields , proximity scoring is disabled even if phraseSlop is specified. Valid for: dismax .
            phraseSlop : An integer value that specifies how much matches can deviate from the search phrase and still be boosted according to the weights specified in the phraseFields option; for example, phraseSlop: 2 . You must also specify phraseFields to enable proximity scoring. Valid values: positive integers. Default: 0. Valid for: dismax .
            explicitPhraseSlop : An integer value that specifies how much a match can deviate from the search phrase when the phrase is enclosed in double quotes in the search string. (Phrases that exceed this proximity distance are not considered a match.) For example, to specify a slop of three for dismax phrase queries, you would specify 'explicitPhraseSlop':3 . Valid values: positive integers. Default: 0. Valid for: dismax .
            tieBreaker : When a term in the search string is found in a document's field, a score is calculated for that field based on how common the word is in that field compared to other documents. If the term occurs in multiple fields within a document, by default only the highest scoring field contributes to the document's overall score. You can specify a tieBreaker value to enable the matches in lower-scoring fields to contribute to the document's score. That way, if two documents have the same max field score for a particular term, the score for the document that has matches in more fields will be higher. The formula for calculating the score with a tieBreaker is (max field score) + (tieBreaker) * (sum of the scores for the rest of the matching fields) . Set tieBreaker to 0 to disregard all but the highest scoring field (pure max): 'tieBreaker':0 . Set to 1 to sum the scores from all fields (pure sum): 'tieBreaker':1 . Valid values: 0.0 to 1.0. Default: 0.0. Valid for: dismax .

    :type queryParser: string
    :param queryParser: Specifies which query parser to use to process the request. If queryParser is not specified, Amazon CloudSearch uses the simple query parser.
            Amazon CloudSearch supports four query parsers:
            simple : perform simple searches of text and text-array fields. By default, the simple query parser searches all text and text-array fields. You can specify which fields to search by with the queryOptions parameter. If you prefix a search term with a plus sign (+) documents must contain the term to be considered a match. (This is the default, unless you configure the default operator with the queryOptions parameter.) You can use the - (NOT), | (OR), and * (wildcard) operators to exclude particular terms, find results that match any of the specified terms, or search for a prefix. To search for a phrase rather than individual terms, enclose the phrase in double quotes. For more information, see Searching for Text in the Amazon CloudSearch Developer Guide .
            structured : perform advanced searches by combining multiple expressions to define the search criteria. You can also search within particular fields, search for values and ranges of values, and use advanced options such as term boosting, matchall , and near . For more information, see Constructing Compound Queries in the Amazon CloudSearch Developer Guide .
            lucene : search using the Apache Lucene query parser syntax. For more information, see Apache Lucene Query Parser Syntax .
            dismax : search using the simplified subset of the Apache Lucene query parser syntax defined by the DisMax query parser. For more information, see DisMax Query Parser Syntax .

    :type returnFields: string
    :param returnFields: Specifies the field and expression values to include in the response. Multiple fields or expressions are specified as a comma-separated list. By default, a search response includes all return enabled fields (_all_fields ). To return only the document IDs for the matching documents, specify _no_fields . To retrieve the relevance score calculated for each document, specify _score .

    :type size: integer
    :param size: Specifies the maximum number of search hits to include in the response.

    :type sort: string
    :param sort: Specifies the fields or custom expressions to use to sort the search results. Multiple fields or expressions are specified as a comma-separated list. You must specify the sort direction (asc or desc ) for each field; for example, year desc,title asc . To use a field to sort results, the field must be sort-enabled in the domain configuration. Array type fields cannot be used for sorting. If no sort parameter is specified, results are sorted by their default relevance scores in descending order: _score desc . You can also sort by document ID (_id asc ) and version (_version desc ).
            For more information, see Sorting Results in the Amazon CloudSearch Developer Guide .

    :type start: integer
    :param start: Specifies the offset of the first search hit you want to return. Note that the result set is zero-based; the first result is at index 0. You can specify either the start or cursor parameter in a request, they are mutually exclusive.
            For more information, see Paginating Results in the Amazon CloudSearch Developer Guide .

    :type stats: string
    :param stats: Specifies one or more fields for which to get statistics information. Each specified field must be facet-enabled in the domain configuration. The fields are specified in JSON using the form:
            {'FIELD-A':{},'FIELD-B':{}}
            There are currently no options supported for statistics.

    :rtype: dict
    :return: {
        'status': {
            'timems': 123,
            'rid': 'string'
        },
        'hits': {
            'found': 123,
            'start': 123,
            'cursor': 'string',
            'hit': [
                {
                    'id': 'string',
                    'fields': {
                        'string': [
                            'string',
                        ]
                    },
                    'exprs': {
                        'string': 'string'
                    },
                    'highlights': {
                        'string': 'string'
                    }
                },
            ]
        },
        'facets': {
            'string': {
                'buckets': [
                    {
                        'value': 'string',
                        'count': 123
                    },
                ]
            }
        },
        'stats': {
            'string': {
                'min': 'string',
                'max': 'string',
                'count': 123,
                'missing': 123,
                'sum': 123.0,
                'sumOfSquares': 123.0,
                'mean': 'string',
                'stddev': 123.0
            }
        }
    }

    :returns:
    cursor (string) -- Retrieves a cursor value you can use to page through large result sets. Use the size parameter to control the number of hits to include in each response. You can specify either the cursor or start parameter in a request; they are mutually exclusive. To get the first cursor, set the cursor value to initial . In subsequent requests, specify the cursor value returned in the hits section of the response.
    For more information, see Paginating Results in the Amazon CloudSearch Developer Guide .

    expr (string) -- Defines one or more numeric expressions that can be used to sort results or specify search or filter criteria. You can also specify expressions as return fields.
    You specify the expressions in JSON using the form {"EXPRESSIONNAME":"EXPRESSION"} . You can define and use multiple expressions in a search request. For example:
    {"expression1":"_score*rating", "expression2":"(1/rank)*year"}
    For information about the variables, operators, and functions you can use in expressions, see Writing Expressions in the Amazon CloudSearch Developer Guide .

    facet (string) -- Specifies one or more fields for which to get facet information, and options that control how the facet information is returned. Each specified field must be facet-enabled in the domain configuration. The fields and options are specified in JSON using the form {"FIELD":{"OPTION":VALUE,"OPTION:"STRING"},"FIELD":{"OPTION":VALUE,"OPTION":"STRING"}} .
    You can specify the following faceting options:

    buckets specifies an array of the facet values or ranges to count. Ranges are specified using the same syntax that you use to search for a range of values. For more information, see Searching for a Range of Values in the Amazon CloudSearch Developer Guide . Buckets are returned in the order they are specified in the request. The sort and size options are not valid if you specify buckets .
    size specifies the maximum number of facets to include in the results. By default, Amazon CloudSearch returns counts for the top 10. The size parameter is only valid when you specify the sort option; it cannot be used in conjunction with buckets .
    sort specifies how you want to sort the facets in the results: bucket or count . Specify bucket to sort alphabetically or numerically by facet value (in ascending order). Specify count to sort by the facet counts computed for each facet value (in descending order). To retrieve facet counts for particular values or ranges of values, use the buckets option instead of sort .

    If no facet options are specified, facet counts are computed for all field values, the facets are sorted by facet count, and the top 10 facets are returned in the results.
    To count particular buckets of values, use the buckets option. For example, the following request uses the buckets option to calculate and return facet counts by decade.
    {"year":{"buckets":["[1970,1979]","[1980,1989]","[1990,1999]","[2000,2009]","[2010,}"]}}
    To sort facets by facet count, use the count option. For example, the following request sets the sort option to count to sort the facet values by facet count, with the facet values that have the most matching documents listed first. Setting the size option to 3 returns only the top three facet values.
    {"year":{"sort":"count","size":3}}
    To sort the facets by value, use the bucket option. For example, the following request sets the sort option to bucket to sort the facet values numerically by year, with earliest year listed first.
    {"year":{"sort":"bucket"}}
    For more information, see Getting and Using Facet Information in the Amazon CloudSearch Developer Guide .

    filterQuery (string) -- Specifies a structured query that filters the results of a search without affecting how the results are scored and sorted. You use filterQuery in conjunction with the query parameter to filter the documents that match the constraints specified in the query parameter. Specifying a filter controls only which matching documents are included in the results, it has no effect on how they are scored and sorted. The filterQuery parameter supports the full structured query syntax.
    For more information about using filters, see Filtering Matching Documents in the Amazon CloudSearch Developer Guide .

    highlight (string) -- Retrieves highlights for matches in the specified text or text-array fields. Each specified field must be highlight enabled in the domain configuration. The fields and options are specified in JSON using the form {"FIELD":{"OPTION":VALUE,"OPTION:"STRING"},"FIELD":{"OPTION":VALUE,"OPTION":"STRING"}} .
    You can specify the following highlight options:

    format : specifies the format of the data in the text field: text or html . When data is returned as HTML, all non-alphanumeric characters are encoded. The default is html .
    max_phrases : specifies the maximum number of occurrences of the search term(s) you want to highlight. By default, the first occurrence is highlighted.
    pre_tag : specifies the string to prepend to an occurrence of a search term. The default for HTML highlights is lt;emgt; . The default for text highlights is * .
    post_tag : specifies the string to append to an occurrence of a search term. The default for HTML highlights is lt;/emgt; . The default for text highlights is * .

    If no highlight options are specified for a field, the returned field text is treated as HTML and the first match is highlighted with emphasis tags: lt;emsearch-termlt;/emgt; .
    For example, the following request retrieves highlights for the actors and title fields.

    { "actors": {}, "title": {"format": "text","max_phrases": 2,"pre_tag": "**","post_tag": "** "} }

    partial (boolean) -- Enables partial results to be returned if one or more index partitions are unavailable. When your search index is partitioned across multiple search instances, by default Amazon CloudSearch only returns results if every partition can be queried. This means that the failure of a single search instance can result in 5xx (internal server) errors. When you enable partial results, Amazon CloudSearch returns whatever results are available and includes the percentage of documents searched in the search results (percent-searched). This enables you to more gracefully degrade your users' search experience. For example, rather than displaying no results, you could display the partial results and a message indicating that the results might be incomplete due to a temporary system outage.
    query (string) -- [REQUIRED]
    Specifies the search criteria for the request. How you specify the search criteria depends on the query parser used for the request and the parser options specified in the queryOptions parameter. By default, the simple query parser is used to process requests. To use the structured , lucene , or dismax query parser, you must also specify the queryParser parameter.
    For more information about specifying search criteria, see Searching Your Data in the Amazon CloudSearch Developer Guide .

    queryOptions (string) -- Configures options for the query parser specified in the queryParser parameter. You specify the options in JSON using the following form {"OPTION1":"VALUE1","OPTION2":VALUE2"..."OPTIONN":"VALUEN"}.
    The options you can configure vary according to which parser you use:

    defaultOperator : The default operator used to combine individual terms in the search string. For example: defaultOperator: 'or' . For the dismax parser, you specify a percentage that represents the percentage of terms in the search string (rounded down) that must match, rather than a default operator. A value of 0% is the equivalent to OR, and a value of 100% is equivalent to AND. The percentage must be specified as a value in the range 0-100 followed by the percent (%) symbol. For example, defaultOperator: 50% . Valid values: and , or , a percentage in the range 0%-100% (dismax ). Default: and (simple , structured , lucene ) or 100 (dismax ). Valid for: simple , structured , lucene , and dismax .
    fields : An array of the fields to search when no fields are specified in a search. If no fields are specified in a search and this option is not specified, all text and text-array fields are searched. You can specify a weight for each field to control the relative importance of each field when Amazon CloudSearch calculates relevance scores. To specify a field weight, append a caret (^ ) symbol and the weight to the field name. For example, to boost the importance of the title field over the description field you could specify: "fields":["title^5","description"] . Valid values: The name of any configured field and an optional numeric value greater than zero. Default: All text and text-array fields. Valid for: simple , structured , lucene , and dismax .
    operators : An array of the operators or special characters you want to disable for the simple query parser. If you disable the and , or , or not operators, the corresponding operators (+ , | , - ) have no special meaning and are dropped from the search string. Similarly, disabling prefix disables the wildcard operator (* ) and disabling phrase disables the ability to search for phrases by enclosing phrases in double quotes. Disabling precedence disables the ability to control order of precedence using parentheses. Disabling near disables the ability to use the ~ operator to perform a sloppy phrase search. Disabling the fuzzy operator disables the ability to use the ~ operator to perform a fuzzy search. escape disables the ability to use a backslash (\\ ) to escape special characters within the search string. Disabling whitespace is an advanced option that prevents the parser from tokenizing on whitespace, which can be useful for Vietnamese. (It prevents Vietnamese words from being split incorrectly.) For example, you could disable all operators other than the phrase operator to support just simple term and phrase queries: "operators":["and","not","or", "prefix"] . Valid values: and , escape , fuzzy , near , not , or , phrase , precedence , prefix , whitespace . Default: All operators and special characters are enabled. Valid for: simple .
    phraseFields : An array of the text or text-array fields you want to use for phrase searches. When the terms in the search string appear in close proximity within a field, the field scores higher. You can specify a weight for each field to boost that score. The phraseSlop option controls how much the matches can deviate from the search string and still be boosted. To specify a field weight, append a caret (^ ) symbol and the weight to the field name. For example, to boost phrase matches in the title field over the abstract field, you could specify: "phraseFields":["title^3", "plot"] Valid values: The name of any text or text-array field and an optional numeric value greater than zero. Default: No fields. If you don't specify any fields with phraseFields , proximity scoring is disabled even if phraseSlop is specified. Valid for: dismax .
    phraseSlop : An integer value that specifies how much matches can deviate from the search phrase and still be boosted according to the weights specified in the phraseFields option; for example, phraseSlop: 2 . You must also specify phraseFields to enable proximity scoring. Valid values: positive integers. Default: 0. Valid for: dismax .
    explicitPhraseSlop : An integer value that specifies how much a match can deviate from the search phrase when the phrase is enclosed in double quotes in the search string. (Phrases that exceed this proximity distance are not considered a match.) For example, to specify a slop of three for dismax phrase queries, you would specify "explicitPhraseSlop":3 . Valid values: positive integers. Default: 0. Valid for: dismax .
    tieBreaker : When a term in the search string is found in a document's field, a score is calculated for that field based on how common the word is in that field compared to other documents. If the term occurs in multiple fields within a document, by default only the highest scoring field contributes to the document's overall score. You can specify a tieBreaker value to enable the matches in lower-scoring fields to contribute to the document's score. That way, if two documents have the same max field score for a particular term, the score for the document that has matches in more fields will be higher. The formula for calculating the score with a tieBreaker is (max field score) + (tieBreaker) * (sum of the scores for the rest of the matching fields) . Set tieBreaker to 0 to disregard all but the highest scoring field (pure max): "tieBreaker":0 . Set to 1 to sum the scores from all fields (pure sum): "tieBreaker":1 . Valid values: 0.0 to 1.0. Default: 0.0. Valid for: dismax .

    queryParser (string) -- Specifies which query parser to use to process the request. If queryParser is not specified, Amazon CloudSearch uses the simple query parser.
    Amazon CloudSearch supports four query parsers:

    simple : perform simple searches of text and text-array fields. By default, the simple query parser searches all text and text-array fields. You can specify which fields to search by with the queryOptions parameter. If you prefix a search term with a plus sign (+) documents must contain the term to be considered a match. (This is the default, unless you configure the default operator with the queryOptions parameter.) You can use the - (NOT), | (OR), and * (wildcard) operators to exclude particular terms, find results that match any of the specified terms, or search for a prefix. To search for a phrase rather than individual terms, enclose the phrase in double quotes. For more information, see Searching for Text in the Amazon CloudSearch Developer Guide .
    structured : perform advanced searches by combining multiple expressions to define the search criteria. You can also search within particular fields, search for values and ranges of values, and use advanced options such as term boosting, matchall , and near . For more information, see Constructing Compound Queries in the Amazon CloudSearch Developer Guide .
    lucene : search using the Apache Lucene query parser syntax. For more information, see Apache Lucene Query Parser Syntax .
    dismax : search using the simplified subset of the Apache Lucene query parser syntax defined by the DisMax query parser. For more information, see DisMax Query Parser Syntax .

    returnFields (string) -- Specifies the field and expression values to include in the response. Multiple fields or expressions are specified as a comma-separated list. By default, a search response includes all return enabled fields (_all_fields ). To return only the document IDs for the matching documents, specify _no_fields . To retrieve the relevance score calculated for each document, specify _score .
    size (integer) -- Specifies the maximum number of search hits to include in the response.
    sort (string) -- Specifies the fields or custom expressions to use to sort the search results. Multiple fields or expressions are specified as a comma-separated list. You must specify the sort direction (asc or desc ) for each field; for example, year desc,title asc . To use a field to sort results, the field must be sort-enabled in the domain configuration. Array type fields cannot be used for sorting. If no sort parameter is specified, results are sorted by their default relevance scores in descending order: _score desc . You can also sort by document ID (_id asc ) and version (_version desc ).
    For more information, see Sorting Results in the Amazon CloudSearch Developer Guide .

    start (integer) -- Specifies the offset of the first search hit you want to return. Note that the result set is zero-based; the first result is at index 0. You can specify either the start or cursor parameter in a request, they are mutually exclusive.
    For more information, see Paginating Results in the Amazon CloudSearch Developer Guide .

    stats (string) -- Specifies one or more fields for which to get statistics information. Each specified field must be facet-enabled in the domain configuration. The fields are specified in JSON using the form:

    {"FIELD-A":{},"FIELD-B":{}}
    There are currently no options supported for statistics.

    """
    pass


def get_activities_dirlist(activities_direction):
    """
    Form an ordered list out of a dictionary that contains for each activity
    the direction (going from -1 if all ingoing edges, to 1 if all outgoing edges)

    Parameters
    -----------
    activities_direction
        Dictionary that contains for each direction a number that goes from -1 (all ingoing edges)
        to 1 (all outgoing edges)

    Returns
    ----------
    dirlist
        Sorted list of couples of activity plus the direction
    """
    dirlist = []
    for act in activities_direction:
        dirlist.append([act, activities_direction[act]])
    dirlist = sorted(dirlist, key=lambda x: (x[1], x[0]), reverse=True)
    return dirlist


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


def set_labels(ax, histogram):
    """ define the axis labels """
    if histogram.has_uniform_bins():
        ylabel_suffix = f' / {histogram.bin_width} {histogram.unit}'
    else:
        ylabel_suffix = f' / bin'
    ax.set_ylabel(f'Events{ylabel_suffix}', horizontalalignment='right', y=1.0)
    return 0


def _buildElementNsmap(using_elements):
    """
    build a namespace map for an ADMX element
    """
    thisMap = {}
    for e in using_elements:
        thisMap[e.attrib['prefix']] = e.attrib['namespace']
    return thisMap


def notEqualTo(t):
    """Compare this DateTime object to another DateTime object OR
        a floating point number such as that which is returned by the
        python time module. Returns true if the object represents a
        date/time not equal to the specified DateTime or time module
        style time.  Revised to give more correct results through
        comparison of long integer milliseconds."""


def reverse_code(apps, schema_editor):
    """Reversing the inference of the process type is not possible and not necessary."""


def type_object_attrgetter(obj, attr, *defargs):
    """
    This implements an improved attrgetter for type objects (i.e. classes)
    that can handle class attributes that are implemented as properties on
    a metaclass.

    Normally `getattr` on a class with a `property` (say, "foo"), would return
    the `property` object itself.  However, if the class has a metaclass which
    *also* defines a `property` named "foo", ``getattr(cls, 'foo')`` will find
    the "foo" property on the metaclass and resolve it.  For the purposes of
    autodoc we just want to document the "foo" property defined on the class,
    not on the metaclass.

    For example::

        >>> class Meta(type):
        ...     @property
        ...     def foo(cls):
        ...         return 'foo'
        ...
        >>> class MyClass(metaclass=Meta):
        ...     @property
        ...     def foo(self):
        ...         ""\"Docstring for MyClass.foo property.""\"
        ...         return 'myfoo'
        ...
        >>> getattr(MyClass, 'foo')
        'foo'
        >>> type_object_attrgetter(MyClass, 'foo')
        <property at 0x...>
        >>> type_object_attrgetter(MyClass, 'foo').__doc__
        'Docstring for MyClass.foo property.'

    The last line of the example shows the desired behavior for the purposes
    of autodoc.
    """
    for base in obj.__mro__:
        if attr in base.__dict__:
            if isinstance(base.__dict__[attr], property):
                return base.__dict__[attr]
            break
    return getattr(obj, attr, *defargs)


def with_metaclass(meta, *bases):
    """Create a base class with a metaclass."""
    return meta('NewBase', bases, {})


def normalize_rgb(r, g, b, a):
    """Transform a rgb[a] color to #hex[a].
    """
    r = int(r, 10)
    g = int(g, 10)
    b = int(b, 10)
    if a:
        a = float(a) * 256
    if r > 255 or g > 255 or b > 255 or a and a > 255:
        return None
    color = '#%02x%02x%02x' % (r, g, b)
    if a:
        color += '%02x' % int(a)
    return color


def pop(k, default=None):
    """ Pop the key k from the dictionary and return its value.  If k
        doesn't exist, and default is provided, return the default.  If k
        doesn't exist and default is not provided, raise a KeyError."""


def isDoomed():
    """Returns True if the current transaction is doomed, otherwise False.

        In explicit mode, if a transaction hasn't begun, a
        `NoTransaction` exception will be raised.
        """


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


def exp(input):
    """Returns a new tensor with the exponential of the elements of the input tensor `input`.

    Parameters
    ----------
    input : Tensor
        The input tensor.

    Returns
    -------
    Tensor
        The output tensor.
    """
    pass


def aggressive_strip(string):
    """
    Split a string along newlines, strip surrounding whitespace on
    each line, and recombine with a single space in place of the
    newlines.
    """
    return ' '.join(filter(None, map(str.strip, string.splitlines())))


def is_pure_list(coll):
    """
    Returns true if and only if the collection is a list.
    @sig is_pure_list :: [a] -> bool
    """
    return isinstance(coll, list)


def delete_permission(pid: str=None, **extra):
    """
    DynamoDB Integration:
    ---

    if not pid:
        raise KeyError("PID argument is required.")

    return permission_table.delete_item(Key={"pid": {"S": pid}})
    """
    if not pid:
        raise KeyError('PID argument is required.')
    return {'success': True}


def parent(docker_path):
    """
    >>> path = getfixture('tmpdir').mkdir('parent').join('Dockerfile')
    >>> path.write('FrOm    ubuntu')

    >>> parent(str(path))
    'ubuntu'

    """
    for l in open(docker_path):
        if l.strip().lower().startswith('from'):
            return l.split()[1]


def forceWrite(this, key, val):
    """
        Always writes through to MBUS
        """
    this.log.debug('fored-write: ' + str(key) + ':' + str(val))
    addr = key[0]
    size = key[1]
    assert isinstance(addr, int)
    assert isinstance(val, int)
    this.mbus.write_mem(addr, val, size)


@classmethod
def parse(cls, s, **kwargs):
    """
        Parse a bytes object and create a class object.

        :param bytes s: A bytes object.
        :return:        A class object.
        :rtype:         cls
        """
    pb2_obj = cls._get_cmsg()
    pb2_obj.ParseFromString(s)
    return cls.parse_from_cmessage(pb2_obj, **kwargs)


def retrieve_solutions(store):
    """ Retrieve a list of solutions from the data store
    """
    return list(store['stats']['init_id'].astype(str).values)


def get_term_code(term):
    """Converts different variations of term codes into the yyyymm format for HTTP requests

    acceptable codes include:  FALL09, 2016-FALL, SUMMER-2017, 2016SUMMER, 2017-WINTER
    """
    part_codes = {'FALL': '09', 'FALL-SUP': '10', 'WINTER': '01',
        'WINTER-SUP': '02', 'SUMMER': '05', 'SUMMER-SUP': '06'}
    if term == 'PREVIOUSEDUCATION':
        return '000000'
    elif term.isdigit():
        return term
    elif term[0].isdigit():
        year = term[0:4]
        if term[4] == '-':
            part = term[5:]
        else:
            part = term[4:]
        part = part_codes[part.upper()]
    else:
        year = term[-4:]
        if term[-5] == '-':
            part = term[:-5]
        else:
            part = term[:-4]
        part = part_codes[part.upper()]
    return year + part


def _remove_noop_on_off_italics(collection):
    """Return an equivalent list to `collection`. It removes the italics node
     pairs that don't surround text nodes, if those nodes are in the order:
     on, off

    :type collection: list[_InstructionNode]
    :rtype: list[_InstructionNode]
    """
    new_collection = []
    to_commit = None
    for node in collection:
        if node.is_italics_node() and node.sets_italics_on():
            to_commit = node
            continue
        elif node.is_italics_node() and node.sets_italics_off():
            if to_commit:
                to_commit = None
                continue
        elif to_commit:
            new_collection.append(to_commit)
            to_commit = None
        new_collection.append(node)
    return new_collection


def _py_to_val(pyval):
    """Convert python value to ovs-vsctl value argument"""
    if isinstance(pyval, bool):
        return 'true' if pyval is True else 'false'
    elif pyval == '':
        return '""'
    else:
        return getattr(pyval, 'record_id', pyval)


def to_str_none(val):
    """
    Converts val to a string via str, returns None if val is None

    :param s: Any - Value to convert
    :return: String?
    """
    if val is None:
        return None
    return str(val)


def generate_schema(primary_keys) ->object:
    """Generate singer schema for kafka messages

    MESSAGE_TIMESTAMP: Automatically will extract from kafka metadata
    MESSAGE: The original kafka message
    DYNAMIC_COLUMNS_FOR_PK: optional
    """
    schema = {'type': 'object', 'properties': {'message_timestamp': {'type':
        ['integer', 'string', 'null']}, 'message_offset': {'type': [
        'integer', 'null']}, 'message_partition': {'type': ['integer',
        'null']}, 'message': {'type': ['object', 'array', 'string', 'null']}}}
    for key in primary_keys:
        schema['properties'][key] = {'type': ['string', 'null']}
    return schema


def vectorize(e, tolerance=0.1):
    """
    vectorizes the pdf object's bounding box
    min_width is the width under which we consider it a line
    instead of a big rectangle
    """
    tolerance = max(tolerance, e.linewidth)
    is_high = e.height > tolerance
    is_wide = e.width > tolerance
    if is_wide and not is_high:
        return e.width, 0.0
    if is_high and not is_wide:
        return 0.0, e.height


@staticmethod
def cloud_cover_prct_range_builder(min=0, max=100):
    """
        Builds cloud cover percentage range query.
        :param min:
            float specifying the minimum percentage. Default is 0
        :type min:
            float
        :param max:
            float specifying the maximum percentage. Default is 100
        :type max:
            float
        :returns:
            String
        """
    return 'cloudCoverFull:[%s+TO+%s]' % (min, max)


@staticmethod
def complex_to_point(point):
    """Transform tuple to complex

        :param point: Point to convert
        :type point: complex

        :return: tuple representation of point
        :rtype: tuple"""
    return point.real, point.imag


def describe_game_sessions(FleetId=None, GameSessionId=None, AliasId=None,
    StatusFilter=None, Limit=None, NextToken=None):
    """
    Retrieves a set of one or more game sessions. Request a specific game session or request all game sessions on a fleet. Alternatively, use  SearchGameSessions to request a set of active game sessions that are filtered by certain criteria. To retrieve protection policy settings for game sessions, use  DescribeGameSessionDetails .
    To get game sessions, specify one of the following: game session ID, fleet ID, or alias ID. You can filter this request by game session status. Use the pagination parameters to retrieve results as a set of sequential pages. If successful, a  GameSession object is returned for each game session matching the request.
    See also: AWS API Documentation

    :example: response = client.describe_game_sessions(
        FleetId='string',
        GameSessionId='string',
        AliasId='string',
        StatusFilter='string',
        Limit=123,
        NextToken='string'
    )

    :type FleetId: string
    :param FleetId: Unique identifier for a fleet to retrieve all game sessions for.

    :type GameSessionId: string
    :param GameSessionId: Unique identifier for the game session to retrieve. You can use either a GameSessionId or GameSessionArn value.

    :type AliasId: string
    :param AliasId: Unique identifier for an alias associated with the fleet to retrieve all game sessions for.

    :type StatusFilter: string
    :param StatusFilter: Game session status to filter results on. Possible game session statuses include ACTIVE , TERMINATED , ACTIVATING , and TERMINATING (the last two are transitory).

    :type Limit: integer
    :param Limit: Maximum number of results to return. Use this parameter with NextToken to get results as a set of sequential pages.

    :type NextToken: string
    :param NextToken: Token that indicates the start of the next sequential page of results. Use the token that is returned with a previous call to this action. To specify the start of the result set, do not specify a value.

    :rtype: dict
    :return: {
        'GameSessions': [
            {
                'GameSessionId': 'string',
                'Name': 'string',
                'FleetId': 'string',
                'CreationTime': datetime(2015, 1, 1),
                'TerminationTime': datetime(2015, 1, 1),
                'CurrentPlayerSessionCount': 123,
                'MaximumPlayerSessionCount': 123,
                'Status': 'ACTIVE'|'ACTIVATING'|'TERMINATED'|'TERMINATING'|'ERROR',
                'GameProperties': [
                    {
                        'Key': 'string',
                        'Value': 'string'
                    },
                ],
                'IpAddress': 'string',
                'Port': 123,
                'PlayerSessionCreationPolicy': 'ACCEPT_ALL'|'DENY_ALL',
                'CreatorId': 'string'
            },
        ],
        'NextToken': 'string'
    }

    """
    pass


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


def _get_pixmap_key(image_coords, image_rect, target_rect):
    """Convert params to hashable string.

    :param image_coords: the coordinates of the image center
    :param image_rect: the size of the portion of image to take
    :param target_rect: the size to scale the portion to
    :return: all the parameters combined in one string
    """
    return '{},{},{},{},{},{}'.format(*image_coords, *image_rect, *target_rect)


def get_output_shape(data):
    """Returns output shapes."""
    return data[1].shape[1:]


def is_model_managed(model):
    """True if managed is True in Meta class"""
    return model._meta.managed


def add_spelling(ix, fieldnames, commit=True):
    """Adds spelling files to an existing index that was created without
    them, and modifies the schema so the given fields have the ``spelling``
    attribute. Only works on filedb indexes.

    >>> ix = index.open_dir("testindex")
    >>> add_spelling(ix, ["content", "tags"])

    :param ix: a :class:`whoosh.filedb.fileindex.FileIndex` object.
    :param fieldnames: a list of field names to create word graphs for.
    :param force: if True, overwrites existing word graph files. This is only
        useful for debugging.
    """
    from whoosh.automata import fst
    from whoosh.reading import SegmentReader
    writer = ix.writer()
    storage = writer.storage
    schema = writer.schema
    segments = writer.segments
    for segment in segments:
        ext = segment.codec().FST_EXT
        r = SegmentReader(storage, schema, segment)
        f = segment.create_file(storage, ext)
        gw = fst.GraphWriter(f)
        for fieldname in fieldnames:
            gw.start_field(fieldname)
            for word in r.lexicon(fieldname):
                gw.insert(word)
            gw.finish_field()
        gw.close()
    for fieldname in fieldnames:
        schema[fieldname].spelling = True
    if commit:
        writer.commit(merge=False)


def is_python_file(fpath):
    """Naive Python module filterer"""
    return fpath.endswith('.py') and '__' not in fpath


def get_atomic_numbers(mol, indices):
    """Get the atomic numbers for the specified atoms.

    Parameters
    ----------
    mol : rdkit.Chem.rdchem.Mol
        RDKit molecule instance.
    indices : list of int
        Specifying atoms.

    Returns
    -------
    list of int
        Atomic numbers computed.
    """
    atomic_numbers = []
    for i in indices:
        atom = mol.GetAtomWithIdx(i)
        atomic_numbers.append(atom.GetAtomicNum())
    return atomic_numbers


def is_db_connection_error(args):
    """Return True if error in connecting to db."""
    conn_err_codes = '2002', '2003', '2006'
    for err_code in conn_err_codes:
        if args.find(err_code) != -1:
            return True
    return False


def bool_to_yes_no(val):
    """Convert True/False to Yes/No"""
    return 'Yes' if val else 'No'


def collection_unlink():
    """Unlink the collection from all objects

    """
    pass


def face_distance(face_encodings, face_to_compare):
    """
    Given a list of face encodings, compare them to a known face encoding and get a euclidean distance
    for each comparison face. The distance tells you how similar the faces are.
    :param faces: List of face encodings to compare
    :param face_to_compare: A face encoding to compare against
    :return: A numpy ndarray with the distance for each face in the same order as the 'faces' array
    """
    import numpy as np
    if len(face_encodings) == 0:
        return np.empty(0)
    return np.sum(face_encodings * face_to_compare, axis=1)


@staticmethod
def to_jwk(key_obj):
    """
        Serializes a given RSA key into a JWK
        """
    raise NotImplementedError


def serialise_go_point(move, size):
    """Serialise a Go Point, Move, or Stone value.

    move -- pair (row, col), or None for a pass

    Returns a bytes object.

    Only supports board sizes up to 26.

    The move coordinates are in the GTP coordinate system, where (0, 0) is the
    lower left.

    """
    if not 1 <= size <= 26:
        raise ValueError
    if move is None:
        if size <= 19:
            return b'tt'
        else:
            return b''
    row, col = move
    if not (0 <= col < size and 0 <= row < size):
        raise ValueError
    col_b = b'abcdefghijklmnopqrstuvwxy'[col]
    row_b = b'abcdefghijklmnopqrstuvwxy'[size - row - 1]
    return bytes((col_b, row_b))


@classmethod
def get_desc(cls, name):
    """Get description of given constant"""
    try:
        return cls.desc[name][1]
    except:
        return None


@staticmethod
def _reduce_datetimes(row):
    """Receives a row, converts datetimes to strings."""
    row = list(row)
    for i, val in enumerate(row):
        if hasattr(val, 'strftime'):
            row[i] = val.strftime('%Y-%m-%d %H:%M:%S')
        elif hasattr(val, 'isoformat'):
            row[i] = val.isoformat()
    return tuple(row)


def test_csv_file(names):
    """ On the top of each column within the csv file is the name of the
    columnn (Last Name, First Name, Middle Name, etc.).  Test and see if all
    the appropriate names are present.

    argements:
    names -- list of column headers that comes from the csv file, i.e.,
    ['Last Name', 'First Name', etc.]

    """
    appropriate_names = ['Last Name', 'First Name', 'Middle Name', 'Suffix',
        'Member', 'Home Street', 'Home City', 'Home State',
        'Home Postal Code', 'Business Phone', 'Home Phone', 'Mobile Phone',
        'E-mail Address', 'Photo URL', 'Photo secondary', 'Spouse',
        'Children', 'Notes', 'Job Title']
    s1 = set(names)
    s2 = set(appropriate_names)
    if len(s2 - s1) > 0:
        print(
            """
Your csv file's structure is not correct. These categories not being present
and/or not utilized may be part of the problem: """
            )
        print(list(s2 - s1))
        return list(s2 - s1)


def gizmo_tweak():
    """Tweak the active gizmo

    """
    pass


@classmethod
def process_collision_contacts(cls, args, geom1, geom2, contacts):
    """Process ``contacts`` of a collision between ``geom1`` and ``geom2``.

		This method should create movement constraints for the bodies
		attached to the geoms. This is necessary for the simulation to
		prevent bodies' volumes from penetrating each other, making them
		really collide (i.e. exert mutually opposing forces).

		.. warning::
		   Neither ``geom1`` nor ``geom2`` can be rays. If one of them is,
		   use method :meth:`process_ray_collision_contacts`.

		:param args:
		:type args: :class:`NearCallbackArgs`
		:param geom1:
		:type geom1: type of :attr:`Geom.inner_object`
		:param geom2:
		:type geom2: type of :attr:`Geom.inner_object`
		:param contacts: collision data returned by :meth:`calc_collision`
		:type contacts: list of contact data objects

		"""
    raise NotImplementedError()


def make_slow_waves(events, data, time, s_freq):
    """Create dict for each slow wave, based on events of time points.

    Parameters
    ----------
    events : ndarray (dtype='int')
        N x 5 matrix with start, trough, zero, peak, end samples
    data : ndarray (dtype='float')
        vector with the data
    time : ndarray (dtype='float')
        vector with time points
    s_freq : float
        sampling frequency

    Returns
    -------
    list of dict
        list of all the SWs, with information about start_time,
        trough_time, zero_time, peak_time, end_time, duration (s), trough_val,
        peak_val, peak-to-peak amplitude (signal units), area_under_curve
        (signal units * s)
    """
    slow_waves = []
    for ev in events:
        one_sw = {'start': time[ev[0]], 'trough_time': time[ev[1]],
            'zero_time': time[ev[2]], 'peak_time': time[ev[3]], 'end': time
            [ev[4] - 1], 'trough_val': data[ev[1]], 'peak_val': data[ev[3]],
            'dur': (ev[4] - ev[0]) / s_freq, 'area_under_curve': sum(data[
            ev[0]:ev[4]]) / s_freq, 'ptp': ev[3] - ev[1]}
        slow_waves.append(one_sw)
    return slow_waves


def _appendToDocstring(thingWithDoc, textToAppend):
    """
    Append the given text to the docstring of C{thingWithDoc}.

    If C{thingWithDoc} has no docstring, then the text just replaces the
    docstring. If it has a single-line docstring then it appends a blank line
    and the message text. If it has a multi-line docstring, then in appends a
    blank line a the message text, and also does the indentation correctly.
    """
    if thingWithDoc.__doc__:
        docstringLines = thingWithDoc.__doc__.splitlines()
    else:
        docstringLines = []
    if len(docstringLines) == 0:
        docstringLines.append(textToAppend)
    elif len(docstringLines) == 1:
        docstringLines.extend(['', textToAppend, ''])
    else:
        spaces = docstringLines.pop()
        docstringLines.extend(['', spaces + textToAppend, spaces])
    thingWithDoc.__doc__ = '\n'.join(docstringLines)


def remove_position_from_str(string, position):
    """Takes a string and a position as an input and removes the characters at
    the provided position from the string.

    Parameters
    ----------
    string : str
        The string which you want to perform this action on.
    position : int
        The single position you which to remove.

    Returns
    -------
    string : str
        The input string with the provided position removed.
    """
    return string[:position] + string[position + 1:]


@staticmethod
def _generate_id(**kwargs) ->str:
    """
        generates db primary key
        """
    if 'username' not in kwargs:
        raise
    return f"user:{kwargs['username']}"


@staticmethod
def escape(expression, quote=True):
    """
        >>> Syntax.escape("SELECT 'abcdefgh' FROM foobar") == u"SELECT 'abcdefgh' FROM foobar"
        True
        """
    return expression


def _recolumn(tmy3_dataframe):
    """
    Rename the columns of the TMY3 DataFrame.

    Parameters
    ----------
    tmy3_dataframe : DataFrame
    inplace : bool
        passed to DataFrame.rename()

    Returns
    -------
    Recolumned DataFrame.
    """
    raw_columns = (
        'ETR (W/m^2),ETRN (W/m^2),GHI (W/m^2),GHI source,GHI uncert (%),DNI (W/m^2),DNI source,DNI uncert (%),DHI (W/m^2),DHI source,DHI uncert (%),GH illum (lx),GH illum source,Global illum uncert (%),DN illum (lx),DN illum source,DN illum uncert (%),DH illum (lx),DH illum source,DH illum uncert (%),Zenith lum (cd/m^2),Zenith lum source,Zenith lum uncert (%),TotCld (tenths),TotCld source,TotCld uncert (code),OpqCld (tenths),OpqCld source,OpqCld uncert (code),Dry-bulb (C),Dry-bulb source,Dry-bulb uncert (code),Dew-point (C),Dew-point source,Dew-point uncert (code),RHum (%),RHum source,RHum uncert (code),Pressure (mbar),Pressure source,Pressure uncert (code),Wdir (degrees),Wdir source,Wdir uncert (code),Wspd (m/s),Wspd source,Wspd uncert (code),Hvis (m),Hvis source,Hvis uncert (code),CeilHgt (m),CeilHgt source,CeilHgt uncert (code),Pwat (cm),Pwat source,Pwat uncert (code),AOD (unitless),AOD source,AOD uncert (code),Alb (unitless),Alb source,Alb uncert (code),Lprecip depth (mm),Lprecip quantity (hr),Lprecip source,Lprecip uncert (code),PresWth (METAR code),PresWth source,PresWth uncert (code)'
        )
    new_columns = ['ETR', 'ETRN', 'GHI', 'GHISource', 'GHIUncertainty',
        'DNI', 'DNISource', 'DNIUncertainty', 'DHI', 'DHISource',
        'DHIUncertainty', 'GHillum', 'GHillumSource', 'GHillumUncertainty',
        'DNillum', 'DNillumSource', 'DNillumUncertainty', 'DHillum',
        'DHillumSource', 'DHillumUncertainty', 'Zenithlum',
        'ZenithlumSource', 'ZenithlumUncertainty', 'TotCld', 'TotCldSource',
        'TotCldUncertainty', 'OpqCld', 'OpqCldSource', 'OpqCldUncertainty',
        'DryBulb', 'DryBulbSource', 'DryBulbUncertainty', 'DewPoint',
        'DewPointSource', 'DewPointUncertainty', 'RHum', 'RHumSource',
        'RHumUncertainty', 'Pressure', 'PressureSource',
        'PressureUncertainty', 'Wdir', 'WdirSource', 'WdirUncertainty',
        'Wspd', 'WspdSource', 'WspdUncertainty', 'Hvis', 'HvisSource',
        'HvisUncertainty', 'CeilHgt', 'CeilHgtSource', 'CeilHgtUncertainty',
        'Pwat', 'PwatSource', 'PwatUncertainty', 'AOD', 'AODSource',
        'AODUncertainty', 'Alb', 'AlbSource', 'AlbUncertainty',
        'Lprecipdepth', 'Lprecipquantity', 'LprecipSource',
        'LprecipUncertainty', 'PresWth', 'PresWthSource', 'PresWthUncertainty']
    mapping = dict(zip(raw_columns.split(','), new_columns))
    return tmy3_dataframe.rename(columns=mapping)


def coord_str(x, y):
    """Return a string representation of x and y"""
    return '({0}, {1})'.format(x, y)


def psi_H_K_OH_HMW84(T, P):
    """c-c'-a: hydrogen potassium hydroxide [HMW84]."""
    psi = 0
    valid = T == 298.15
    return psi, valid


def weighted_count(instances_obj, m_weights):
    """Weight nt count by nt weights at each position"""
    weighted_counts = {}
    for letter in instances_obj.alphabet:
        weighted_counts[letter] = [0] * instances_obj.length
    for idx, instance in enumerate(instances_obj):
        for position, letter in enumerate(instance):
            weighted_counts[letter][position] += m_weights[idx]
    return weighted_counts


def first_of_month(date):
    """Return the first day of the month for a given date."""
    return date.replace(day=1)


@staticmethod
def scan_pr_dist(dist):
    """Add a distribution, empty by default."""
    dname = dist.project_name
    epmap = dist.get_entry_map()
    return dname, epmap


@staticmethod
def write_target_build_event_of_setting(cmake_file, property_indent,
    config_condition_expr, property_value, width, **kwargs):
    """ Write target build event functor (helper) """
    del kwargs
    for command in property_value:
        cmake_file.write('{0}    COMMAND {1:>{width}} {2}\n'.format(
            property_indent, config_condition_expr, command, width=width))


def escape(data):
    """
    Escape user-provided input data for safe inclusion in HTML _and_ JS to prevent XSS.
    """
    data = data.replace('&', '&')
    data = data.replace('>', '>')
    data = data.replace('<', '<')
    data = data.replace("'", '')
    data = data.replace('"', '')
    return data


@staticmethod
def is_event_valid(webhook_message_data, validated_message_data):
    """
        Notice "data" may contain a "previous_attributes" section
        """
    return ('object' in webhook_message_data and 'object' in
        validated_message_data and webhook_message_data['object'] ==
        validated_message_data['object'])


@staticmethod
def _create_wrapper(cls_spec, element_info, myself):
    """Create a wrapper object according to the specified element info"""
    if cls_spec != myself:
        obj = object.__new__(cls_spec)
        obj.__init__(element_info)
        return obj
    new_class = cls_spec.find_wrapper(element_info)
    obj = object.__new__(new_class)
    obj.__init__(element_info)
    return obj


def until(s, substr):
    """
        >>> until('0123456789','45')
        '0123'
        """
    try:
        idx = s.index(substr)
        return s[:idx]
    except ValueError:
        return s


def addon_refresh():
    """Scan add-on directories for new modules

    """
    pass


def span_pred_key(node):
    """
    For use as a node_key in SortDictDmrs.
    This sorts nodes by: cfrom (ascending), cto (descending), predstring (ascending)
    """
    return node.cfrom, -node.cto, str(node.pred)


def _process_glsl_template(template, colors):
    """Replace $color_i by color #i in the GLSL template."""
    for i in range(len(colors) - 1, -1, -1):
        color = colors[i]
        assert len(color) == 4
        vec4_color = 'vec4(%.3f, %.3f, %.3f, %.3f)' % tuple(color)
        template = template.replace('$color_%d' % i, vec4_color)
    return template


@classmethod
def _requires_ckan_version(cls, min_version, max_version=None):
    """Raise :py:exc:`~ckan.plugins.toolkit.CkanVersionException` if the
        CKAN version is not greater than or equal to ``min_version`` and
        less then or equal to ``max_version``.

        If no ``max_version`` is given, just check whether the CKAN version is
        greater than or equal to ``min_version``.

        Plugins can call this function if they require a certain CKAN version,
        other versions of CKAN will crash if a user tries to use the plugin
        with them.

        :param min_version: the minimum acceptable CKAN version,
            eg. ``'2.1'``
        :type min_version: string

        :param max_version: the maximum acceptable CKAN version,
            eg. ``'2.3'``
        :type max_version: string

        """
    from ckan.exceptions import CkanVersionException
    if not cls._check_ckan_version(min_version=min_version, max_version=
        max_version):
        if not max_version:
            error = 'Requires ckan version %s or higher' % min_version
        else:
            error = 'Requires ckan version between {0} and {1}'.format(
                min_version, max_version)
        raise CkanVersionException(error)


@staticmethod
def getRightWireVariables():
    """The IP5 Right Wire Variables (1 power supply, 5 motors, 4 temperatures gauges, 1 vacuum gauges,
        relay status and voltages on the two wires (internal and external))"""
    variablesWireR = ['RPMC.UL557.RBBCW.R5B2:I_MEAS',
        'RPMC.UL557.RBBCW.R5B2:I_REF', 'RPMC.UL557.RBBCW.R5B2:V_MEAS',
        'RPMC.UL557.RBBCW.R5B2:V_REF', 'RPMC.UL557.RBBCW.R5B2:STATE',
        'TCTPH.4R5.B2:MEAS_MOTOR_LD', 'TCTPH.4R5.B2:MEAS_MOTOR_LU',
        'TCTPH.4R5.B2:MEAS_MOTOR_RD', 'TCTPH.4R5.B2:MEAS_MOTOR_RU',
        'TCTPH.4R5.B2:MEAS_V_MOTOR_POS', 'TCTPH_4R5_B2_TTRD.POSST',
        'TCTPH_4R5_B2_TTRU.POSST', 'TCTPH_4R5_B2_TTLD.POSST',
        'TCTPH_4R5_B2_TTLU.POSST', 'BBCWE.R5.B2:RELAY_STATUS',
        'BBCWE.R5.B2:VOLTAGE', 'BBCWI.R5.B2:RELAY_STATUS',
        'BBCWI.R5.B2:VOLTAGE', 'VGPB.935.4R5.R.PR',
        'LHC.BPTDH.A4R5.B2:CALIBCORRECTEDPOS',
        'LHC.BPTUH.A4R5.B2:CALIBCORRECTEDPOS']
    return variablesWireR


@classmethod
def clearMtime(cls, f0):
    """Return a copy of f0 with no mtime specified, or None if f0 is None."""
    if (f0 is None or f0.owner is None and f0.dataset is None and f0.
        sizeGeq is None and f0.notPaths == [] and f0.regex is None):
        return None
    else:
        return cls(f0.owner, f0.dataset, f0.sizeGeq, None, f0.notPaths, f0.
            regex)


def adoptStreamConnection(fileDescriptor, addressFamily, factory):
    """
        Add an existing connected I{SOCK_STREAM} socket to the reactor to
        monitor for data.

        Note that the given factory won't have its C{startFactory} and
        C{stopFactory} methods called, as there is no sensible time to call
        them in this situation.

        @param fileDescriptor: A file descriptor associated with a socket which
            is already connected.  The socket must be set non-blocking.  Any
            additional flags (for example, close-on-exec) must also be set by
            application code.  Application code is responsible for closing the
            file descriptor, which may be done as soon as
            C{adoptStreamConnection} returns.
        @type fileDescriptor: C{int}

        @param addressFamily: The address family (or I{domain}) of the socket.
            For example, L{socket.AF_INET6}.

        @param factory: A L{ServerFactory} instance to use to create a new
            protocol to handle the connection via this socket.

        @raise UnsupportedAddressFamily: If the given address family is not
            supported by this reactor, or not supported with the given socket
            type.

        @raise UnsupportedSocketType: If the given socket type is not supported
            by this reactor, or not supported with the given socket type.
        """


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

        :param FileRequestCreateDetails val:
        :rtype: EventDetails
        """
    return cls('file_request_create_details', val)


def calculate_gain(Dbeta, Pn):
    """calculate the gain of the 4 wave mixing
    ** here Pn is normalized such as Pn = gamma*P0"""
    return Pn ** 2 - (Dbeta / 2 + Pn) ** 2


def mean(iterable):
    """ Returns the arithmetic mean of the given list of values.
        For example: mean([1,2,3,4]) = 10/4 = 2.5.
    """
    a = iterable if isinstance(iterable, list) else list(iterable)
    return float(sum(a)) / (len(a) or 1)


def get_valid_periods():
    """Returns list of periods for which one may request time series data."""
    return ['1d', '7d', '30d', '1w', '1m', '3m', '6m', '1y', 'max']


def qbytearray_to_str(qba):
    """Convert QByteArray object to str in a way compatible with Python 2/3"""
    return str(bytes(qba.toHex().data()).decode())


def represent_argument(arg):
    """
    Represent argument in a string.

    If argument has spaces represents string with quotation marks ".
    """
    sarg = str(arg)
    if sarg.count(' ') > 0:
        return '{!r}'.format(sarg)
    else:
        return sarg


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

        :param NonTeamMemberLogInfo val:
        :rtype: ContextLogInfo
        """
    return cls('non_team_member', val)


@classmethod
def after_save(cls, info, instance, cleaned_input=None):
    """Perform "after save" operations.

        Override this to perform any operation on the instance
        after its `.save()` method is called.
        """
    pass


def align_structures(reference_traj, target_traj):
    """
        Given a reference trajectory, this function performs a structural alignment for a second input trajectory, with respect to the reference.

        :param reference_traj: The trajectory to use as a reference for alignment.
        :type reference_traj: `MDTraj() trajectory <http://mdtraj.org/1.6.2/api/generated/mdtraj.Trajectory.html>`_

        :param target_traj: The trajectory to align with the reference.
        :type target_traj: `MDTraj() trajectory <http://mdtraj.org/1.6.2/api/generated/mdtraj.Trajectory.html>`_

        :returns:
          - aligned_target_traj ( `MDTraj() trajectory <http://mdtraj.org/1.6.2/api/generated/mdtraj.Trajectory.html>`_ ) - The coordinates for the aligned trajectory.

        """
    aligned_target_traj = target_traj.superpose(reference_traj)
    return aligned_target_traj


@classmethod
def record_id(cls, event, stamp):
    """
        Return a string suitable for use as the document id.

        :param event: A event identifier
        :param stamp: Datetime for this event
        :type event: str
        :type stamp: datetime.datetime

        """
    period = cls._period(stamp)
    info = {'event': event, 'year': period.year, 'month': period.month,
        'day': period.day, 'hour': period.hour, 'minute': period.minute}
    return cls.config_id_format % info


def _get_widths(jstat_data=None, short_fields=False):
    """Function that returns the recommended field widths of the jstat output"""
    widths = dict()
    for field in jstat_data:
        max_width = max(list(map(len, list(map(str, jstat_data[field])))))
        field_width = len(field)
        if field_width > max_width:
            widths[field] = field_width
        else:
            widths[field] = max_width
    if short_fields:
        survivor_max = 6
        newgen_max = 6
        oldgen_max = 6
    else:
        survivor_max = max(widths['S0C'], widths['S1C'], widths['S0U'],
            widths['S1U'])
        newgen_max = max(widths['EC'], widths['EU'])
        oldgen_max = max(widths['OC'], widths['OU'])
    widths['OC'] = oldgen_max
    widths['OU'] = oldgen_max
    widths['EC'] = newgen_max
    widths['EU'] = newgen_max
    widths['S0C'] = survivor_max
    widths['S1C'] = survivor_max
    widths['S0U'] = survivor_max
    widths['S1U'] = survivor_max
    widths['EP'] = 6
    widths['OP'] = 6
    return widths


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 dump(x, **kwargs):
    """Print a description of an object.

    If the object has a `!dump` method then this is used to create the
    output, so that ``cf.dump(f)`` is equivalent to ``print
    f.dump()``. Otherwise ``cf.dump(x)`` is equivalent to
    ``print(x)``.

    :Parameters:

        x:
            The object to print.

        kwargs : *optional*
            As for the input variable's `!dump` method, if it has one.

    :Returns:

        None

    **Examples:**

    >>> x = 3.14159
    >>> cf.dump(x)
    3.14159

    >>> f
    <CF Field: rainfall_rate(latitude(10), longitude(20)) kg m2 s-1>
    >>> cf.dump(f)
    >>> cf.dump(f, complete=True)

    """
    if hasattr(x, 'dump') and callable(x.dump):
        print(x.dump(**kwargs))
    else:
        print(x)


def read_uint(data, start, length):
    """Extract a uint from a position in a sequence."""
    return int.from_bytes(data[start:start + length], byteorder='big')


def findIterative(pair, iteratives):
    """
    Function to find the two 'iteratives' that corresponds to the groups in 'pair'
    """
    for iterative in iteratives:
        if iterative.group == pair[0]:
            iterative0 = iterative
        elif iterative.group == pair[1]:
            iterative1 = iterative
    return iterative0, iterative1


def is_obsolete(obo_tags):
    """ checks if an "is_obsolete" flag is in the tags for an obo entry

    Args:
        obo_tags: tags for an obo entry

    Returns:
        True/False for whether the entry is obsolete
    """
    return 'is_obsolete' in obo_tags and str(obo_tags['is_obsolete'][0]
        ) == 'true'


@classmethod
def set_known_classes(cls, known_classes):
    """ Set protected member _known_classes """
    cls._known_classes = known_classes


def find_all(string, sub, start=None, end=None, ignore_case=False, **kwargs):
    """
    Return all indices in string s where substring sub is
    found, such that sub is contained in the slice s[start:end].

    >>> list(find_all('The quick brown fox jumps over the lazy dog', 'fox'))
    [16]

    >>> list(find_all('The quick brown fox jumps over the lazy dog', 'mountain'))
    []

    >>> list(find_all('The quick brown fox jumps over the lazy dog', 'The'))
    [0]

    >>> list(find_all(
    ... 'Carved symbols in a mountain hollow on the bank of an inlet irritated an eccentric person',
    ... 'an'))
    [44, 51, 70]

    >>> list(find_all(
    ... 'Carved symbols in a mountain hollow on the bank of an inlet irritated an eccentric person',
    ... 'an',
    ... 50,
    ... 60))
    [51]

    :param string: the input string
    :type string: str
    :param sub: the substring
    :type sub: str
    :return: all indices in the input string
    :rtype: __generator[str]
    """
    if ignore_case:
        sub = sub.lower()
        string = string.lower()
    while True:
        start = string.find(sub, start, end)
        if start == -1:
            return
        yield start
        start += len(sub)


def clipboard_copy():
    """Copies selected nodes to the clipboard

    """
    pass


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


def trivial(x):
    """Trivial function returning its argument."""
    return x


def _metadata_url(obs_point):
    """ construct a url for retrieving gsv metadata
        at obs point location"""
    lat = obs_point.geometry.y
    lng = obs_point.geometry.x
    base = 'https://maps.googleapis.com/maps/api/streetview/metadata?'
    latlng = 'location={},{}'.format(lat, lng)
    source = 'source=outdoor'
    url = '{}&{}&{}'.format(base, latlng, source)
    return url


@classmethod
def show(cls, room_id):
    """Get information about a single room.

        Returns a `Room` object with information about the room specified by
        the `room_id` argument. If there's no room with that ID, the
        `hipchat.api.NotFoundError` exception will be raised.

        """
    data = cls.api._get('rooms/show', room_id=str(room_id))
    return cls._parse(data['room'])


def none_to_zero(x):
    """Return 0 if value is None"""
    if x is None:
        return 0
    return x


def attributive(adjective):
    """ For a predicative adjective, returns the attributive form.
    """
    raise NotImplementedError


@staticmethod
def extract_line(text, line_number):
    """
        Extracts specified line from the supplied text based on line number.

        :param text: Text from which line is to be extracted.
        :param line_number: Line number to be extracted.

        :return: The extracted line.
        :rtype: str
        """
    text_lines = text.split('\n')
    if len(text_lines) > 0:
        return text_lines[line_number - 1]
    return False


def describe_environment_health(EnvironmentName=None, EnvironmentId=None,
    AttributeNames=None):
    """
    Returns information about the overall health of the specified environment. The DescribeEnvironmentHealth operation is only available with AWS Elastic Beanstalk Enhanced Health.
    See also: AWS API Documentation

    Examples
    The following operation retrieves overall health information for an environment named my-env:
    Expected Output:

    :example: response = client.describe_environment_health(
        EnvironmentName='string',
        EnvironmentId='string',
        AttributeNames=[
            'Status'|'Color'|'Causes'|'ApplicationMetrics'|'InstancesHealth'|'All'|'HealthStatus'|'RefreshedAt',
        ]
    )

    :type EnvironmentName: string
    :param EnvironmentName: Specify the environment by name.
            You must specify either this or an EnvironmentName, or both.

    :type EnvironmentId: string
    :param EnvironmentId: Specify the environment by ID.
            You must specify either this or an EnvironmentName, or both.

    :type AttributeNames: list
    :param AttributeNames: Specify the response elements to return. To retrieve all attributes, set to All . If no attribute names are specified, returns the name of the environment.
            (string) --

    :rtype: dict
    :return: {
        'EnvironmentName': 'string',
        'HealthStatus': 'string',
        'Status': 'Green'|'Yellow'|'Red'|'Grey',
        'Color': 'string',
        'Causes': [
            'string',
        ],
        'ApplicationMetrics': {
            'Duration': 123,
            'RequestCount': 123,
            'StatusCodes': {
                'Status2xx': 123,
                'Status3xx': 123,
                'Status4xx': 123,
                'Status5xx': 123
            },
            'Latency': {
                'P999': 123.0,
                'P99': 123.0,
                'P95': 123.0,
                'P90': 123.0,
                'P85': 123.0,
                'P75': 123.0,
                'P50': 123.0,
                'P10': 123.0
            }
        },
        'InstancesHealth': {
            'NoData': 123,
            'Unknown': 123,
            'Pending': 123,
            'Ok': 123,
            'Info': 123,
            'Warning': 123,
            'Degraded': 123,
            'Severe': 123
        },
        'RefreshedAt': datetime(2015, 1, 1)
    }

    :returns:
    (string) --

    """
    pass


@staticmethod
def _event_headers(flask_request, port):
    """
        Constructs an APIGW equivalent headers dictionary

        Parameters
        ----------
        flask_request request
            Request from Flask
        int port
            Forwarded Port
        cors_headers dict
            Dict of the Cors properties

        Returns dict (str: str), dict (str: list of str)
        -------
            Returns a dictionary of key to list of strings

        """
    headers_dict = {}
    multi_value_headers_dict = {}
    for header_key in flask_request.headers.keys():
        headers_dict[header_key] = flask_request.headers.get(header_key)
        multi_value_headers_dict[header_key] = flask_request.headers.getlist(
            header_key)
    headers_dict['X-Forwarded-Proto'] = flask_request.scheme
    multi_value_headers_dict['X-Forwarded-Proto'] = [flask_request.scheme]
    headers_dict['X-Forwarded-Port'] = str(port)
    multi_value_headers_dict['X-Forwarded-Port'] = [str(port)]
    return headers_dict, multi_value_headers_dict


def StripUnicode(string, subs='.'):
    """Strip non-ASCII characters from strings

    :param str string: string to strip Unicode characters from
    :param str subs: character(s) to place into string in place of each
      Unicode character. Defaults to '.'

    :returns: a new string with only ASCII characters
    """
    s = ''
    for c in string:
        if ord(c) < 128:
            s += c
        else:
            s += subs
    return s


def element_in_string(string, word_list):
    """Check if there is one of the strings in the word list inside the string."""
    for word in word_list:
        if word.lower() in string.lower().split(' '):
            return True
        if ' ' in word:
            if word.lower() in string.lower():
                return True
    return False


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


@staticmethod
def get_headers() ->dict:
    """Gets the headers for all url queries to the validator"""
    return {'Connection': 'keep-alive', 'Cache-Control': 'max-age=0',
        'Upgrade-Insecure-Requests': 1, 'User-Agent':
        'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'
        , 'Accept':
        'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3'
        , 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language':
        'en-US,en;q=0.9'}


def modMarker(mod, fn_name, args):
    """
	Returns the stringified extra_repr() of a module.
	"""
    assert fn_name == 'forward'
    assert len(args) > 0
    d = {}
    d['mod'] = mod.__name__
    d['strRepr'] = args[0].extra_repr()
    return str(d)


def get_binary_annotations(request, response):
    """Helper method for getting all binary annotations from the request.
    :param request: the Pyramid request object
    :param response: the Pyramid response object
    :returns: binary annotation dict of {str: str}
    """
    return {'http.uri': request.path, 'http.uri.qs': request.META[
        'QUERY_STRING'], 'response.status_code': str(response.status_code),
        '/http/url': request.path, '/http/user_agent': request.META.get(
        'HTTP_USER_AGENT', ''), '/http/status_code': str(response.
        status_code), '/http/method': request.method}


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

    The ".dev0" means dirty.

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


@staticmethod
def addable_cells(obj):
    """
        List object addable cells

        TESTS ::

            sage: from sage.combinat.partition import Partition
            sage: from sage_widget_adapters.combinat.partition_grid_view_adapter import PartitionGridViewAdapter
            sage: p = Partition([6, 5, 2, 1])
            sage: PartitionGridViewAdapter.addable_cells(p)
            [(0, 6), (1, 5), (2, 2), (3, 1), (4, 0)]
        """
    return obj.outside_corners()


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

        :param PaperDocTrashedType val:
        :rtype: EventType
        """
    return cls('paper_doc_trashed', val)


@classmethod
def get_user(cls, pk):
    """Return user instance for given id"""
    raise NotImplementedError('Implement in subclass')


def can_paginate(operation_name=None):
    """
    Check if an operation can be paginated.

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

    """
    pass


def quads_to_triangles(mesh):
    """
    Convert Quadrilateral faces to Triangular ones.

    Inputs:
        mesh - an OBJ object loaded from load_obj()
    Outputs:
        Modifies the mesh.f and returns mesh.
    """
    newFaces = []
    for i, face in enumerate(mesh.f):
        if len(face) != 3:
            assert len(face) == 4
            newFaces.append((face[0], face[1], face[2]))
            newFaces.append((face[2], face[3], face[0]))
        else:
            newFaces.append(face)
    mesh.f = newFaces
    return mesh


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

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


def parse_debug(response):
    """
    Parse the result of Redis's DEBUG command into a Python dict
    :param bytearray response:
    :return disc:
    """
    info = {}
    response = response.decode('utf8')
    for line in response.split(','):
        if line.find(':') != -1:
            key, value = line.split(':', 1)
            info[key.strip()] = int(value)
        else:
            info.setdefault('__raw__', []).append(line)
    return info


@staticmethod
def deposit(data, *args, **kwargs):
    """
        Returns deposit address as str
        :param data: requests.response() obj
        :param args:
        :param kwargs:
        :return: str
        """
    return data


def resetseq():
    """
    Returns the reset terminal escape sequence
    """
    return '\x1b[m'