def query(TableName=None, IndexName=None, Select=None, AttributesToGet=None,
    Limit=None, ConsistentRead=None, KeyConditions=None, QueryFilter=None,
    ConditionalOperator=None, ScanIndexForward=None, ExclusiveStartKey=None,
    ReturnConsumedCapacity=None, ProjectionExpression=None,
    FilterExpression=None, KeyConditionExpression=None,
    ExpressionAttributeNames=None, ExpressionAttributeValues=None):
    """
    A Query operation uses the primary key of a table or a secondary index to directly access items from that table or index.
    Use the KeyConditionExpression parameter to provide a specific value for the partition key. The Query operation will return all of the items from the table or index with that partition key value. You can optionally narrow the scope of the Query operation by specifying a sort key value and a comparison operator in KeyConditionExpression . You can use the ScanIndexForward parameter to get results in forward or reverse order, by sort key.
    Queries that do not return results consume the minimum number of read capacity units for that type of read operation.
    If the total number of items meeting the query criteria exceeds the result set size limit of 1 MB, the query stops and results are returned to the user with the LastEvaluatedKey element to continue the query in a subsequent operation. Unlike a Scan operation, a Query operation never returns both an empty result set and a LastEvaluatedKey value. LastEvaluatedKey is only provided if you have used the Limit parameter, or if the result set exceeds 1 MB (prior to applying a filter).
    You can query a table, a local secondary index, or a global secondary index. For a query on a table or on a local secondary index, you can set the ConsistentRead parameter to true and obtain a strongly consistent result. Global secondary indexes support eventually consistent reads only, so do not specify ConsistentRead when querying a global secondary index.
    See also: AWS API Documentation

    Examples
    This example queries items in the Music table. The table has a partition key and sort key (Artist and SongTitle), but this query only specifies the partition key value. It returns song titles by the artist named "No One You Know".
    Expected Output:

    :example: response = client.query(
        TableName='string',
        IndexName='string',
        Select='ALL_ATTRIBUTES'|'ALL_PROJECTED_ATTRIBUTES'|'SPECIFIC_ATTRIBUTES'|'COUNT',
        AttributesToGet=[
            'string',
        ],
        Limit=123,
        ConsistentRead=True|False,
        KeyConditions={
            'string': {
                'AttributeValueList': [
                    {
                        'S': 'string',
                        'N': 'string',
                        'B': b'bytes',
                        'SS': [
                            'string',
                        ],
                        'NS': [
                            'string',
                        ],
                        'BS': [
                            b'bytes',
                        ],
                        'M': {
                            'string': {'... recursive ...'}
                        },
                        'L': [
                            {'... recursive ...'},
                        ],
                        'NULL': True|False,
                        'BOOL': True|False
                    },
                ],
                'ComparisonOperator': 'EQ'|'NE'|'IN'|'LE'|'LT'|'GE'|'GT'|'BETWEEN'|'NOT_NULL'|'NULL'|'CONTAINS'|'NOT_CONTAINS'|'BEGINS_WITH'
            }
        },
        QueryFilter={
            'string': {
                'AttributeValueList': [
                    {
                        'S': 'string',
                        'N': 'string',
                        'B': b'bytes',
                        'SS': [
                            'string',
                        ],
                        'NS': [
                            'string',
                        ],
                        'BS': [
                            b'bytes',
                        ],
                        'M': {
                            'string': {'... recursive ...'}
                        },
                        'L': [
                            {'... recursive ...'},
                        ],
                        'NULL': True|False,
                        'BOOL': True|False
                    },
                ],
                'ComparisonOperator': 'EQ'|'NE'|'IN'|'LE'|'LT'|'GE'|'GT'|'BETWEEN'|'NOT_NULL'|'NULL'|'CONTAINS'|'NOT_CONTAINS'|'BEGINS_WITH'
            }
        },
        ConditionalOperator='AND'|'OR',
        ScanIndexForward=True|False,
        ExclusiveStartKey={
            'string': {
                'S': 'string',
                'N': 'string',
                'B': b'bytes',
                'SS': [
                    'string',
                ],
                'NS': [
                    'string',
                ],
                'BS': [
                    b'bytes',
                ],
                'M': {
                    'string': {'... recursive ...'}
                },
                'L': [
                    {'... recursive ...'},
                ],
                'NULL': True|False,
                'BOOL': True|False
            }
        },
        ReturnConsumedCapacity='INDEXES'|'TOTAL'|'NONE',
        ProjectionExpression='string',
        FilterExpression='string',
        KeyConditionExpression='string',
        ExpressionAttributeNames={
            'string': 'string'
        },
        ExpressionAttributeValues={
            'string': {
                'S': 'string',
                'N': 'string',
                'B': b'bytes',
                'SS': [
                    'string',
                ],
                'NS': [
                    'string',
                ],
                'BS': [
                    b'bytes',
                ],
                'M': {
                    'string': {'... recursive ...'}
                },
                'L': [
                    {'... recursive ...'},
                ],
                'NULL': True|False,
                'BOOL': True|False
            }
        }
    )

    :type TableName: string
    :param TableName: [REQUIRED]
            The name of the table containing the requested items.

    :type IndexName: string
    :param IndexName: The name of an index to query. This index can be any local secondary index or global secondary index on the table. Note that if you use the IndexName parameter, you must also provide TableName.

    :type Select: string
    :param Select: The attributes to be returned in the result. You can retrieve all item attributes, specific item attributes, the count of matching items, or in the case of an index, some or all of the attributes projected into the index.
            ALL_ATTRIBUTES - Returns all of the item attributes from the specified table or index. If you query a local secondary index, then for each matching item in the index DynamoDB will fetch the entire item from the parent table. If the index is configured to project all item attributes, then all of the data can be obtained from the local secondary index, and no fetching is required.
            ALL_PROJECTED_ATTRIBUTES - Allowed only when querying an index. Retrieves all attributes that have been projected into the index. If the index is configured to project all attributes, this return value is equivalent to specifying ALL_ATTRIBUTES .
            COUNT - Returns the number of matching items, rather than the matching items themselves.
            SPECIFIC_ATTRIBUTES - Returns only the attributes listed in AttributesToGet . This return value is equivalent to specifying AttributesToGet without specifying any value for Select . If you query or scan a local secondary index and request only attributes that are projected into that index, the operation will read only the index and not the table. If any of the requested attributes are not projected into the local secondary index, DynamoDB will fetch each of these attributes from the parent table. This extra fetching incurs additional throughput cost and latency. If you query or scan a global secondary index, you can only request attributes that are projected into the index. Global secondary index queries cannot fetch attributes from the parent table.
            If neither Select nor AttributesToGet are specified, DynamoDB defaults to ALL_ATTRIBUTES when accessing a table, and ALL_PROJECTED_ATTRIBUTES when accessing an index. You cannot use both Select and AttributesToGet together in a single request, unless the value for Select is SPECIFIC_ATTRIBUTES . (This usage is equivalent to specifying AttributesToGet without any value for Select .)
            Note
            If you use the ProjectionExpression parameter, then the value for Select can only be SPECIFIC_ATTRIBUTES . Any other value for Select will return an error.

    :type AttributesToGet: list
    :param AttributesToGet: This is a legacy parameter. Use ProjectionExpression instead. For more information, see AttributesToGet in the Amazon DynamoDB Developer Guide .
            (string) --

    :type Limit: integer
    :param Limit: The maximum number of items to evaluate (not necessarily the number of matching items). If DynamoDB processes the number of items up to the limit while processing the results, it stops the operation and returns the matching values up to that point, and a key in LastEvaluatedKey to apply in a subsequent operation, so that you can pick up where you left off. Also, if the processed data set size exceeds 1 MB before DynamoDB reaches this limit, it stops the operation and returns the matching values up to the limit, and a key in LastEvaluatedKey to apply in a subsequent operation to continue the operation. For more information, see Query and Scan in the Amazon DynamoDB Developer Guide .

    :type ConsistentRead: boolean
    :param ConsistentRead: Determines the read consistency model: If set to true , then the operation uses strongly consistent reads; otherwise, the operation uses eventually consistent reads.
            Strongly consistent reads are not supported on global secondary indexes. If you query a global secondary index with ConsistentRead set to true , you will receive a ValidationException .

    :type KeyConditions: dict
    :param KeyConditions: This is a legacy parameter. Use KeyConditionExpression instead. For more information, see KeyConditions in the Amazon DynamoDB Developer Guide .
            (string) --
            (dict) --Represents the selection criteria for a Query or Scan operation:
            For a Query operation, Condition is used for specifying the KeyConditions to use when querying a table or an index. For KeyConditions , only the following comparison operators are supported: EQ | LE | LT | GE | GT | BEGINS_WITH | BETWEEN Condition is also used in a QueryFilter , which evaluates the query results and returns only the desired values.
            For a Scan operation, Condition is used in a ScanFilter , which evaluates the scan results and returns only the desired values.
            AttributeValueList (list) --One or more values to evaluate against the supplied attribute. The number of values in the list depends on the ComparisonOperator being used.
            For type Number, value comparisons are numeric.
            String value comparisons for greater than, equals, or less than are based on ASCII character code values. For example, a is greater than A , and a is greater than B . For a list of code values, see http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters .
            For Binary, DynamoDB treats each byte of the binary data as unsigned when it compares binary values.
            (dict) --Represents the data for an attribute.
            Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself.
            For more information, see Data Types in the Amazon DynamoDB Developer Guide .
            S (string) --An attribute of type String. For example:
            'S': 'Hello'
            N (string) --An attribute of type Number. For example:
            'N': '123.45'
            Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations.
            B (bytes) --An attribute of type Binary. For example:
            'B': 'dGhpcyB0ZXh0IGlzIGJhc2U2NC1lbmNvZGVk'
            SS (list) --An attribute of type String Set. For example:
            'SS': ['Giraffe', 'Hippo' ,'Zebra']
            (string) --
            NS (list) --An attribute of type Number Set. For example:
            'NS': ['42.2', '-19', '7.5', '3.14']
            Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations.
            (string) --
            BS (list) --An attribute of type Binary Set. For example:
            'BS': ['U3Vubnk=', 'UmFpbnk=', 'U25vd3k=']
            (bytes) --
            M (dict) --An attribute of type Map. For example:
            'M': {'Name': {'S': 'Joe'}, 'Age': {'N': '35'}}
            (string) --
            (dict) --Represents the data for an attribute.
            Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself.
            For more information, see Data Types in the Amazon DynamoDB Developer Guide .

            L (list) --An attribute of type List. For example:
            'L': ['Cookies', 'Coffee', 3.14159]
            (dict) --Represents the data for an attribute.
            Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself.
            For more information, see Data Types in the Amazon DynamoDB Developer Guide .
            NULL (boolean) --An attribute of type Null. For example:
            'NULL': true
            BOOL (boolean) --An attribute of type Boolean. For example:
            'BOOL': true

            ComparisonOperator (string) -- [REQUIRED]A comparator for evaluating attributes. For example, equals, greater than, less than, etc.
            The following comparison operators are available:
            EQ | NE | LE | LT | GE | GT | NOT_NULL | NULL | CONTAINS | NOT_CONTAINS | BEGINS_WITH | IN | BETWEEN
            The following are descriptions of each comparison operator.
            EQ : Equal. EQ is supported for all data types, including lists and maps. AttributeValueList can contain only one AttributeValue element of type String, Number, Binary, String Set, Number Set, or Binary Set. If an item contains an AttributeValue element of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not equal {'N':'6'} . Also, {'N':'6'} does not equal {'NS':['6', '2', '1']} .
            NE : Not equal. NE is supported for all data types, including lists and maps. AttributeValueList can contain only one AttributeValue of type String, Number, Binary, String Set, Number Set, or Binary Set. If an item contains an AttributeValue of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not equal {'N':'6'} . Also, {'N':'6'} does not equal {'NS':['6', '2', '1']} .
            LE : Less than or equal.  AttributeValueList can contain only one AttributeValue element of type String, Number, or Binary (not a set type). If an item contains an AttributeValue element of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not equal {'N':'6'} . Also, {'N':'6'} does not compare to {'NS':['6', '2', '1']} .
            LT : Less than.  AttributeValueList can contain only one AttributeValue of type String, Number, or Binary (not a set type). If an item contains an AttributeValue element of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not equal {'N':'6'} . Also, {'N':'6'} does not compare to {'NS':['6', '2', '1']} .
            GE : Greater than or equal.  AttributeValueList can contain only one AttributeValue element of type String, Number, or Binary (not a set type). If an item contains an AttributeValue element of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not equal {'N':'6'} . Also, {'N':'6'} does not compare to {'NS':['6', '2', '1']} .
            GT : Greater than.  AttributeValueList can contain only one AttributeValue element of type String, Number, or Binary (not a set type). If an item contains an AttributeValue element of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not equal {'N':'6'} . Also, {'N':'6'} does not compare to {'NS':['6', '2', '1']} .
            NOT_NULL : The attribute exists. NOT_NULL is supported for all data types, including lists and maps.
            Note
            This operator tests for the existence of an attribute, not its data type. If the data type of attribute 'a ' is null, and you evaluate it using NOT_NULL , the result is a Boolean true . This result is because the attribute 'a ' exists; its data type is not relevant to the NOT_NULL comparison operator.
            NULL : The attribute does not exist. NULL is supported for all data types, including lists and maps.
            Note
            This operator tests for the nonexistence of an attribute, not its data type. If the data type of attribute 'a ' is null, and you evaluate it using NULL , the result is a Boolean false . This is because the attribute 'a ' exists; its data type is not relevant to the NULL comparison operator.
            CONTAINS : Checks for a subsequence, or value in a set. AttributeValueList can contain only one AttributeValue element of type String, Number, or Binary (not a set type). If the target attribute of the comparison is of type String, then the operator checks for a substring match. If the target attribute of the comparison is of type Binary, then the operator looks for a subsequence of the target that matches the input. If the target attribute of the comparison is a set ('SS ', 'NS ', or 'BS '), then the operator evaluates to true if it finds an exact match with any member of the set. CONTAINS is supported for lists: When evaluating 'a CONTAINS b ', 'a ' can be a list; however, 'b ' cannot be a set, a map, or a list.
            NOT_CONTAINS : Checks for absence of a subsequence, or absence of a value in a set. AttributeValueList can contain only one AttributeValue element of type String, Number, or Binary (not a set type). If the target attribute of the comparison is a String, then the operator checks for the absence of a substring match. If the target attribute of the comparison is Binary, then the operator checks for the absence of a subsequence of the target that matches the input. If the target attribute of the comparison is a set ('SS ', 'NS ', or 'BS '), then the operator evaluates to true if it does not find an exact match with any member of the set. NOT_CONTAINS is supported for lists: When evaluating 'a NOT CONTAINS b ', 'a ' can be a list; however, 'b ' cannot be a set, a map, or a list.
            BEGINS_WITH : Checks for a prefix.  AttributeValueList can contain only one AttributeValue of type String or Binary (not a Number or a set type). The target attribute of the comparison must be of type String or Binary (not a Number or a set type).
            IN : Checks for matching elements in a list. AttributeValueList can contain one or more AttributeValue elements of type String, Number, or Binary. These attributes are compared against an existing attribute of an item. If any elements of the input are equal to the item attribute, the expression evaluates to true.
            BETWEEN : Greater than or equal to the first value, and less than or equal to the second value.  AttributeValueList must contain two AttributeValue elements of the same type, either String, Number, or Binary (not a set type). A target attribute matches if the target value is greater than, or equal to, the first element and less than, or equal to, the second element. If an item contains an AttributeValue element of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not compare to {'N':'6'} . Also, {'N':'6'} does not compare to {'NS':['6', '2', '1']}
            For usage examples of AttributeValueList and ComparisonOperator , see Legacy Conditional Parameters in the Amazon DynamoDB Developer Guide .

    :type QueryFilter: dict
    :param QueryFilter: This is a legacy parameter. Use FilterExpression instead. For more information, see QueryFilter in the Amazon DynamoDB Developer Guide .
            (string) --
            (dict) --Represents the selection criteria for a Query or Scan operation:
            For a Query operation, Condition is used for specifying the KeyConditions to use when querying a table or an index. For KeyConditions , only the following comparison operators are supported: EQ | LE | LT | GE | GT | BEGINS_WITH | BETWEEN Condition is also used in a QueryFilter , which evaluates the query results and returns only the desired values.
            For a Scan operation, Condition is used in a ScanFilter , which evaluates the scan results and returns only the desired values.
            AttributeValueList (list) --One or more values to evaluate against the supplied attribute. The number of values in the list depends on the ComparisonOperator being used.
            For type Number, value comparisons are numeric.
            String value comparisons for greater than, equals, or less than are based on ASCII character code values. For example, a is greater than A , and a is greater than B . For a list of code values, see http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters .
            For Binary, DynamoDB treats each byte of the binary data as unsigned when it compares binary values.
            (dict) --Represents the data for an attribute.
            Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself.
            For more information, see Data Types in the Amazon DynamoDB Developer Guide .
            S (string) --An attribute of type String. For example:
            'S': 'Hello'
            N (string) --An attribute of type Number. For example:
            'N': '123.45'
            Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations.
            B (bytes) --An attribute of type Binary. For example:
            'B': 'dGhpcyB0ZXh0IGlzIGJhc2U2NC1lbmNvZGVk'
            SS (list) --An attribute of type String Set. For example:
            'SS': ['Giraffe', 'Hippo' ,'Zebra']
            (string) --
            NS (list) --An attribute of type Number Set. For example:
            'NS': ['42.2', '-19', '7.5', '3.14']
            Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations.
            (string) --
            BS (list) --An attribute of type Binary Set. For example:
            'BS': ['U3Vubnk=', 'UmFpbnk=', 'U25vd3k=']
            (bytes) --
            M (dict) --An attribute of type Map. For example:
            'M': {'Name': {'S': 'Joe'}, 'Age': {'N': '35'}}
            (string) --
            (dict) --Represents the data for an attribute.
            Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself.
            For more information, see Data Types in the Amazon DynamoDB Developer Guide .

            L (list) --An attribute of type List. For example:
            'L': ['Cookies', 'Coffee', 3.14159]
            (dict) --Represents the data for an attribute.
            Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself.
            For more information, see Data Types in the Amazon DynamoDB Developer Guide .
            NULL (boolean) --An attribute of type Null. For example:
            'NULL': true
            BOOL (boolean) --An attribute of type Boolean. For example:
            'BOOL': true

            ComparisonOperator (string) -- [REQUIRED]A comparator for evaluating attributes. For example, equals, greater than, less than, etc.
            The following comparison operators are available:
            EQ | NE | LE | LT | GE | GT | NOT_NULL | NULL | CONTAINS | NOT_CONTAINS | BEGINS_WITH | IN | BETWEEN
            The following are descriptions of each comparison operator.
            EQ : Equal. EQ is supported for all data types, including lists and maps. AttributeValueList can contain only one AttributeValue element of type String, Number, Binary, String Set, Number Set, or Binary Set. If an item contains an AttributeValue element of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not equal {'N':'6'} . Also, {'N':'6'} does not equal {'NS':['6', '2', '1']} .
            NE : Not equal. NE is supported for all data types, including lists and maps. AttributeValueList can contain only one AttributeValue of type String, Number, Binary, String Set, Number Set, or Binary Set. If an item contains an AttributeValue of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not equal {'N':'6'} . Also, {'N':'6'} does not equal {'NS':['6', '2', '1']} .
            LE : Less than or equal.  AttributeValueList can contain only one AttributeValue element of type String, Number, or Binary (not a set type). If an item contains an AttributeValue element of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not equal {'N':'6'} . Also, {'N':'6'} does not compare to {'NS':['6', '2', '1']} .
            LT : Less than.  AttributeValueList can contain only one AttributeValue of type String, Number, or Binary (not a set type). If an item contains an AttributeValue element of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not equal {'N':'6'} . Also, {'N':'6'} does not compare to {'NS':['6', '2', '1']} .
            GE : Greater than or equal.  AttributeValueList can contain only one AttributeValue element of type String, Number, or Binary (not a set type). If an item contains an AttributeValue element of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not equal {'N':'6'} . Also, {'N':'6'} does not compare to {'NS':['6', '2', '1']} .
            GT : Greater than.  AttributeValueList can contain only one AttributeValue element of type String, Number, or Binary (not a set type). If an item contains an AttributeValue element of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not equal {'N':'6'} . Also, {'N':'6'} does not compare to {'NS':['6', '2', '1']} .
            NOT_NULL : The attribute exists. NOT_NULL is supported for all data types, including lists and maps.
            Note
            This operator tests for the existence of an attribute, not its data type. If the data type of attribute 'a ' is null, and you evaluate it using NOT_NULL , the result is a Boolean true . This result is because the attribute 'a ' exists; its data type is not relevant to the NOT_NULL comparison operator.
            NULL : The attribute does not exist. NULL is supported for all data types, including lists and maps.
            Note
            This operator tests for the nonexistence of an attribute, not its data type. If the data type of attribute 'a ' is null, and you evaluate it using NULL , the result is a Boolean false . This is because the attribute 'a ' exists; its data type is not relevant to the NULL comparison operator.
            CONTAINS : Checks for a subsequence, or value in a set. AttributeValueList can contain only one AttributeValue element of type String, Number, or Binary (not a set type). If the target attribute of the comparison is of type String, then the operator checks for a substring match. If the target attribute of the comparison is of type Binary, then the operator looks for a subsequence of the target that matches the input. If the target attribute of the comparison is a set ('SS ', 'NS ', or 'BS '), then the operator evaluates to true if it finds an exact match with any member of the set. CONTAINS is supported for lists: When evaluating 'a CONTAINS b ', 'a ' can be a list; however, 'b ' cannot be a set, a map, or a list.
            NOT_CONTAINS : Checks for absence of a subsequence, or absence of a value in a set. AttributeValueList can contain only one AttributeValue element of type String, Number, or Binary (not a set type). If the target attribute of the comparison is a String, then the operator checks for the absence of a substring match. If the target attribute of the comparison is Binary, then the operator checks for the absence of a subsequence of the target that matches the input. If the target attribute of the comparison is a set ('SS ', 'NS ', or 'BS '), then the operator evaluates to true if it does not find an exact match with any member of the set. NOT_CONTAINS is supported for lists: When evaluating 'a NOT CONTAINS b ', 'a ' can be a list; however, 'b ' cannot be a set, a map, or a list.
            BEGINS_WITH : Checks for a prefix.  AttributeValueList can contain only one AttributeValue of type String or Binary (not a Number or a set type). The target attribute of the comparison must be of type String or Binary (not a Number or a set type).
            IN : Checks for matching elements in a list. AttributeValueList can contain one or more AttributeValue elements of type String, Number, or Binary. These attributes are compared against an existing attribute of an item. If any elements of the input are equal to the item attribute, the expression evaluates to true.
            BETWEEN : Greater than or equal to the first value, and less than or equal to the second value.  AttributeValueList must contain two AttributeValue elements of the same type, either String, Number, or Binary (not a set type). A target attribute matches if the target value is greater than, or equal to, the first element and less than, or equal to, the second element. If an item contains an AttributeValue element of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not compare to {'N':'6'} . Also, {'N':'6'} does not compare to {'NS':['6', '2', '1']}
            For usage examples of AttributeValueList and ComparisonOperator , see Legacy Conditional Parameters in the Amazon DynamoDB Developer Guide .

    :type ConditionalOperator: string
    :param ConditionalOperator: This is a legacy parameter. Use FilterExpression instead. For more information, see ConditionalOperator in the Amazon DynamoDB Developer Guide .

    :type ScanIndexForward: boolean
    :param ScanIndexForward: Specifies the order for index traversal: If true (default), the traversal is performed in ascending order; if false , the traversal is performed in descending order.
            Items with the same partition key value are stored in sorted order by sort key. If the sort key data type is Number, the results are stored in numeric order. For type String, the results are stored in order of ASCII character code values. For type Binary, DynamoDB treats each byte of the binary data as unsigned.
            If ScanIndexForward is true , DynamoDB returns the results in the order in which they are stored (by sort key value). This is the default behavior. If ScanIndexForward is false , DynamoDB reads the results in reverse order by sort key value, and then returns the results to the client.

    :type ExclusiveStartKey: dict
    :param ExclusiveStartKey: The primary key of the first item that this operation will evaluate. Use the value that was returned for LastEvaluatedKey in the previous operation.
            The data type for ExclusiveStartKey must be String, Number or Binary. No set data types are allowed.
            (string) --
            (dict) --Represents the data for an attribute.
            Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself.
            For more information, see Data Types in the Amazon DynamoDB Developer Guide .
            S (string) --An attribute of type String. For example:
            'S': 'Hello'
            N (string) --An attribute of type Number. For example:
            'N': '123.45'
            Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations.
            B (bytes) --An attribute of type Binary. For example:
            'B': 'dGhpcyB0ZXh0IGlzIGJhc2U2NC1lbmNvZGVk'
            SS (list) --An attribute of type String Set. For example:
            'SS': ['Giraffe', 'Hippo' ,'Zebra']
            (string) --
            NS (list) --An attribute of type Number Set. For example:
            'NS': ['42.2', '-19', '7.5', '3.14']
            Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations.
            (string) --
            BS (list) --An attribute of type Binary Set. For example:
            'BS': ['U3Vubnk=', 'UmFpbnk=', 'U25vd3k=']
            (bytes) --
            M (dict) --An attribute of type Map. For example:
            'M': {'Name': {'S': 'Joe'}, 'Age': {'N': '35'}}
            (string) --
            (dict) --Represents the data for an attribute.
            Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself.
            For more information, see Data Types in the Amazon DynamoDB Developer Guide .

            L (list) --An attribute of type List. For example:
            'L': ['Cookies', 'Coffee', 3.14159]
            (dict) --Represents the data for an attribute.
            Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself.
            For more information, see Data Types in the Amazon DynamoDB Developer Guide .
            NULL (boolean) --An attribute of type Null. For example:
            'NULL': true
            BOOL (boolean) --An attribute of type Boolean. For example:
            'BOOL': true

    :type ReturnConsumedCapacity: string
    :param ReturnConsumedCapacity: Determines the level of detail about provisioned throughput consumption that is returned in the response:
            INDEXES - The response includes the aggregate ConsumedCapacity for the operation, together with ConsumedCapacity for each table and secondary index that was accessed. Note that some operations, such as GetItem and BatchGetItem , do not access any indexes at all. In these cases, specifying INDEXES will only return ConsumedCapacity information for table(s).
            TOTAL - The response includes only the aggregate ConsumedCapacity for the operation.
            NONE - No ConsumedCapacity details are included in the response.

    :type ProjectionExpression: string
    :param ProjectionExpression: A string that identifies one or more attributes to retrieve from the table. These attributes can include scalars, sets, or elements of a JSON document. The attributes in the expression must be separated by commas.
            If no attribute names are specified, then all attributes will be returned. If any of the requested attributes are not found, they will not appear in the result.
            For more information, see Accessing Item Attributes in the Amazon DynamoDB Developer Guide .

    :type FilterExpression: string
    :param FilterExpression: A string that contains conditions that DynamoDB applies after the Query operation, but before the data is returned to you. Items that do not satisfy the FilterExpression criteria are not returned.
            A FilterExpression does not allow key attributes. You cannot define a filter expression based on a partition key or a sort key.
            Note
            A FilterExpression is applied after the items have already been read; the process of filtering does not consume any additional read capacity units.
            For more information, see Filter Expressions in the Amazon DynamoDB Developer Guide .

    :type KeyConditionExpression: string
    :param KeyConditionExpression: The condition that specifies the key value(s) for items to be retrieved by the Query action.
            The condition must perform an equality test on a single partition key value. The condition can also perform one of several comparison tests on a single sort key value. Query can use KeyConditionExpression to retrieve one item with a given partition key value and sort key value, or several items that have the same partition key value but different sort key values.
            The partition key equality test is required, and must be specified in the following format:
            partitionKeyName = :partitionkeyval
            If you also want to provide a condition for the sort key, it must be combined using AND with the condition for the sort key. Following is an example, using the = comparison operator for the sort key:
            partitionKeyName = :partitionkeyval AND sortKeyName = :sortkeyval
            Valid comparisons for the sort key condition are as follows:
            sortKeyName = :sortkeyval - true if the sort key value is equal to :sortkeyval .
            sortKeyName ```` :sortkeyval - true if the sort key value is less than :sortkeyval .
            sortKeyName = :sortkeyval - true if the sort key value is less than or equal to :sortkeyval .
            sortKeyName ```` :sortkeyval - true if the sort key value is greater than :sortkeyval .
            sortKeyName = :sortkeyval - true if the sort key value is greater than or equal to :sortkeyval .
            sortKeyName BETWEEN :sortkeyval1 AND :sortkeyval2 - true if the sort key value is greater than or equal to :sortkeyval1 , and less than or equal to :sortkeyval2 .
            begins_with ( sortKeyName , :sortkeyval ) - true if the sort key value begins with a particular operand. (You cannot use this function with a sort key that is of type Number.) Note that the function name begins_with is case-sensitive.
            Use the ExpressionAttributeValues parameter to replace tokens such as :partitionval and :sortval with actual values at runtime.
            You can optionally use the ExpressionAttributeNames parameter to replace the names of the partition key and sort key with placeholder tokens. This option might be necessary if an attribute name conflicts with a DynamoDB reserved word. For example, the following KeyConditionExpression parameter causes an error because Size is a reserved word:
            Size = :myval
            To work around this, define a placeholder (such a #S ) to represent the attribute name Size . KeyConditionExpression then is as follows:
            #S = :myval
            For a list of reserved words, see Reserved Words in the Amazon DynamoDB Developer Guide .
            For more information on ExpressionAttributeNames and ExpressionAttributeValues , see Using Placeholders for Attribute Names and Values in the Amazon DynamoDB Developer Guide .

    :type ExpressionAttributeNames: dict
    :param ExpressionAttributeNames: One or more substitution tokens for attribute names in an expression. The following are some use cases for using ExpressionAttributeNames :
            To access an attribute whose name conflicts with a DynamoDB reserved word.
            To create a placeholder for repeating occurrences of an attribute name in an expression.
            To prevent special characters in an attribute name from being misinterpreted in an expression.
            Use the # character in an expression to dereference an attribute name. For example, consider the following attribute name:
            Percentile
            The name of this attribute conflicts with a reserved word, so it cannot be used directly in an expression. (For the complete list of reserved words, see Reserved Words in the Amazon DynamoDB Developer Guide ). To work around this, you could specify the following for ExpressionAttributeNames :
            {'#P':'Percentile'}
            You could then use this substitution in an expression, as in this example:
            #P = :val
            Note
            Tokens that begin with the : character are expression attribute values , which are placeholders for the actual value at runtime.
            For more information on expression attribute names, see Accessing Item Attributes in the Amazon DynamoDB Developer Guide .
            (string) --
            (string) --

    :type ExpressionAttributeValues: dict
    :param ExpressionAttributeValues: One or more values that can be substituted in an expression.
            Use the : (colon) character in an expression to dereference an attribute value. For example, suppose that you wanted to check whether the value of the ProductStatus attribute was one of the following:
            Available | Backordered | Discontinued
            You would first need to specify ExpressionAttributeValues as follows:
            { ':avail':{'S':'Available'}, ':back':{'S':'Backordered'}, ':disc':{'S':'Discontinued'} }
            You could then use these values in an expression, such as this:
            ProductStatus IN (:avail, :back, :disc)
            For more information on expression attribute values, see Specifying Conditions in the Amazon DynamoDB Developer Guide .
            (string) --
            (dict) --Represents the data for an attribute.
            Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself.
            For more information, see Data Types in the Amazon DynamoDB Developer Guide .
            S (string) --An attribute of type String. For example:
            'S': 'Hello'
            N (string) --An attribute of type Number. For example:
            'N': '123.45'
            Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations.
            B (bytes) --An attribute of type Binary. For example:
            'B': 'dGhpcyB0ZXh0IGlzIGJhc2U2NC1lbmNvZGVk'
            SS (list) --An attribute of type String Set. For example:
            'SS': ['Giraffe', 'Hippo' ,'Zebra']
            (string) --
            NS (list) --An attribute of type Number Set. For example:
            'NS': ['42.2', '-19', '7.5', '3.14']
            Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations.
            (string) --
            BS (list) --An attribute of type Binary Set. For example:
            'BS': ['U3Vubnk=', 'UmFpbnk=', 'U25vd3k=']
            (bytes) --
            M (dict) --An attribute of type Map. For example:
            'M': {'Name': {'S': 'Joe'}, 'Age': {'N': '35'}}
            (string) --
            (dict) --Represents the data for an attribute.
            Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself.
            For more information, see Data Types in the Amazon DynamoDB Developer Guide .

            L (list) --An attribute of type List. For example:
            'L': ['Cookies', 'Coffee', 3.14159]
            (dict) --Represents the data for an attribute.
            Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself.
            For more information, see Data Types in the Amazon DynamoDB Developer Guide .
            NULL (boolean) --An attribute of type Null. For example:
            'NULL': true
            BOOL (boolean) --An attribute of type Boolean. For example:
            'BOOL': true

    :rtype: dict
    :return: {
        'Items': [
            {
                'string': {
                    'S': 'string',
                    'N': 'string',
                    'B': b'bytes',
                    'SS': [
                        'string',
                    ],
                    'NS': [
                        'string',
                    ],
                    'BS': [
                        b'bytes',
                    ],
                    'M': {
                        'string': {'... recursive ...'}
                    },
                    'L': [
                        {'... recursive ...'},
                    ],
                    'NULL': True|False,
                    'BOOL': True|False
                }
            },
        ],
        'Count': 123,
        'ScannedCount': 123,
        'LastEvaluatedKey': {
            'string': {
                'S': 'string',
                'N': 'string',
                'B': b'bytes',
                'SS': [
                    'string',
                ],
                'NS': [
                    'string',
                ],
                'BS': [
                    b'bytes',
                ],
                'M': {
                    'string': {'... recursive ...'}
                },
                'L': [
                    {'... recursive ...'},
                ],
                'NULL': True|False,
                'BOOL': True|False
            }
        },
        'ConsumedCapacity': {
            'TableName': 'string',
            'CapacityUnits': 123.0,
            'Table': {
                'CapacityUnits': 123.0
            },
            'LocalSecondaryIndexes': {
                'string': {
                    'CapacityUnits': 123.0
                }
            },
            'GlobalSecondaryIndexes': {
                'string': {
                    'CapacityUnits': 123.0
                }
            }
        }
    }

    :returns:
    (string) --

    """
    pass


@classmethod
def append_to_run_from_text(cls, r, text):
    """
        Create a "one-shot" ``_RunContentAppender`` instance and use it to
        append the run content elements corresponding to *text* to the
        ``<w:r>`` element *r*.
        """
    appender = cls(r)
    appender.add_text(text)


@classmethod
def get(klass, name):
    """
        Return a specific subclass by slug
        """
    for sub in klass.list():
        if sub.get_slug() == name:
            return sub
    raise ValueError('No {0} implementation with slug {1}'.format(klass, name))


def assert_almost_equal(a, b, delta=1e-08):
    """Asserts that abs(a - b) <= delta
    """
    assert abs(a - b) <= delta


def ensure_mpi(size=1, doc=None):
    """
 ensure that mpi-enabled python is being called with the appropriate size

 inputs:
   - size: minimum required size of the MPI world [default = 1]
   - doc: error string to throw if size restriction is violated
    """
    if doc == None:
        doc = 'Error: Requires MPI-enabled python with size >= %s' % size
    from pyina.mpi import world
    mpisize = world.Get_size()
    mpirank = world.Get_rank()
    if mpisize < size:
        if mpirank == 0:
            print(doc)
        import sys
        sys.exit()
    return


def acceleration_avt(delta_velocity, time):
    """Usage: acceleration_avt(change in speed, time taken)"""
    return delta_velocity / time


def clean_indicators(indicators):
    """Remove any extra details from indicators."""
    output = list()
    for indicator in indicators:
        strip = ['http://', 'https://']
        for item in strip:
            indicator = indicator.replace(item, '')
        indicator = indicator.strip('.').strip()
        parts = indicator.split('/')
        if len(parts) > 0:
            indicator = parts.pop(0)
        output.append(indicator)
    output = list(set(output))
    return output


def set_value(dictionary, keys, value):
    """
    Similar to Python's built in `dictionary[key] = value`,
    but takes a list of nested keys instead of a single key.
    set_value({'a': 1}, [], {'b': 2}) -> {'a': 1, 'b': 2}
    set_value({'a': 1}, ['x'], 2) -> {'a': 1, 'x': 2}
    set_value({'a': 1}, ['x', 'y'], 2) -> {'a': 1, 'x': {'y': 2}}
    """
    if not keys:
        dictionary.update(value)
        return
    for key in keys[:-1]:
        if key not in dictionary:
            dictionary[key] = {}
        dictionary = dictionary[key]
    dictionary[keys[-1]] = value


def reveal():
    """Show all Grease Pencil layers

    """
    pass


def delete_patch_baseline(BaselineId=None):
    """
    Deletes a patch baseline.
    See also: AWS API Documentation

    :example: response = client.delete_patch_baseline(
        BaselineId='string'
    )

    :type BaselineId: string
    :param BaselineId: [REQUIRED]
            The ID of the patch baseline to delete.

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

    """
    pass


@staticmethod
def evaluate(x, amplitude, x_0, fwhm):
    """
        One dimensional Drude model function
        """
    return amplitude * (fwhm / x_0) ** 2 / ((x / x_0 - x_0 / x) ** 2 + (
        fwhm / x_0) ** 2)


@classmethod
def Current(cls):
    """Access the currently active namespace context.

        If no context is active, C{None} is returned.  This probably
        represents mis-use of the infrastructure (viz., failure to record the
        context within which a QName must be resolved)."""
    if cls.__ContextStack:
        return cls.__ContextStack[-1]
    return None


def PRIN(val):
    """PartialRetractionIn"""
    return val


def fortran_to_python_short(line, unused_default_values):
    """the function used by the DRESP2"""
    func_str = 'def func(args):\n'
    func_str += '    return %s(args)\n' % line.strip()
    local_dict = {}
    exec(func_str, globals(), local_dict)
    return local_dict['func']


def textbox_remove(index: int=0):
    """Remove the textbox

    :param index: Index, The current text box
    :type index: int
    """
    pass


def cyan(string):
    """foreground color to cyan"""
    return '\x1b[36m' + string + '\x1b[0m'


def default_comparator(individual_1, individual_2):
    """
    individual_1: Individual class with

    """
    return individual_1.fitness < individual_2.fitness


def __iter__():
    """Return an iterator over the days of the month.

        Represents each day as a datetime.date.
        """


def check_permissions(permission_type, user, project):
    """
    Here we check permission types, and see if a user has proper perms.
    If a user has "edit" permissions on a project, they pretty much have
    carte blanche to do as they please, so we kick that back as true.
    Otherwise we go more fine grained and check their view and comment
    permissions
    """
    groups = user.groups.all()
    if user in project.users_can_edit.all():
        return True
    for x in groups:
        if x in project.groups_can_edit.all():
            return True
    if permission_type == 'view':
        if user in project.users_can_view.all():
            return True
        for x in groups:
            if x in project.groups_can_view.all():
                return True
        if project.allow_anon_viewing is True:
            return True
    if permission_type == 'comment':
        if user in project.users_can_comment.all():
            return True
        for x in groups:
            if x in project.groups_can_comment.all():
                return True
        if project.allow_anon_comment is True:
            return True
    return False


def succeeded(obj):
    """Return a Boolean that indicates if the value is an instance of smonad.types.ftry.Success

    >>> from smonad.types.ftry import Failure, Success
    >>> succeeded(Success(True))
    True
    >>> succeeded(Failure('fubar'))
    False
    """
    from smonad.types.ftry import Try, Success
    assert isinstance(obj, Try)
    return isinstance(obj, Success)


def locale_negotiator(request):
    """Return a locale name by looking at the ``Accept-Language`` HTTP
    header.
    """
    settings = request.registry.settings
    available_languages = settings['pyramid.available_languages'].split()
    return request.accept_language.best_match(available_languages)


def apply(f, x):
    """ Same as `f(x)`. """
    return f(x)


@staticmethod
def get_alexa_intent(data):
    """Gets the Intent's name from the Alexa response.

        Args:
            data: Response received from Alexa.

        Returns:
            A string representing the Intent's name from the interaction model that was requested,
            or ``None``, if no Intent was received.

        Examples:
            >>> intent = ADAPI.get_alexa_intent(data)

        """
    if 'request' in data and 'intent' in data['request'] and 'name' in data[
        'request']['intent']:
        return data['request']['intent']['name']
    else:
        return None


@classmethod
def DeregisterDecompressor(cls, decompressor):
    """Deregisters a decompressor for a specific compression method.

    Args:
      decompressor (type): decompressor class.

    Raises:
      KeyError: if the corresponding decompressor is not set.
    """
    compression_method = decompressor.COMPRESSION_METHOD.lower()
    if compression_method not in cls._decompressors:
        raise KeyError('Decompressor for compression method: {0:s} not set.'
            .format(decompressor.COMPRESSION_METHOD))
    del cls._decompressors[compression_method]


@classmethod
def select_old_method(cls, dim, old_method):
    """Retrieve all algorithms which are fitting the requirements from
        old_method. Valid input are "numpy", "cython", "bbox" or "splitpixel",
        "lut", "csr", "nosplit_csr", "full_csr", "lut_ocl" and "csr_ocl".
        """
    results = []
    for v in cls._registry.values():
        if v.dimension == dim and v.old_method_name == old_method:
            results.append(v)
    if results:
        return results
    dim = int(dim)
    method = cls.parse_old_method(old_method)
    _, split, algo, impl, target = method
    if target in ['cpu', 'gpu', None]:
        target_type = target
        target = None
    else:
        target_type = None
    return cls.select_method(dim, split, algo, impl, target_type=
        target_type, target=target)


def control_panel_permission_filter(session_user, *sections):
    """
        takes a blazeweb.user:User object and ControlPanelSections for *args
        and sets the user_has_perm attribute on the ControlPanelSection,
        ControlPanelGroup, and ControlPanelList objects as appropriate.
    """
    retval = []
    for sec in sections:
        sec_groups = []
        if sec.has_perm and not session_user.has_any_perm(sec.has_perm):
            continue
        for lg in sec.groups:
            group_links = []
            if lg.has_perm and not session_user.has_perm(lg.has_perm):
                continue
            for link in lg.links:
                if session_user.has_perm(link.has_perm) or not link.has_perm:
                    group_links.append(link)
            if group_links:
                sec_groups.append({'group': lg, 'group_links': group_links})
        if sec_groups:
            retval.append({'sec': sec, 'sec_groups': sec_groups})
    return retval


def bottom_index_iter(shape):
    """Iterator for the bottom boundary indices of a structured grid."""
    return range(0, shape[1])


def p_datatypedecl(p):
    """datatypedecl : DATA CONID EQUAL constructors"""
    p[0] = [p[1], [p[2], p[4]]]


def draw():
    """
    Draw an animation frame.

    You should redefine this function in your program.

    :return:
    """
    pass


def path_reference_copy(copy_set: set, report='print'):
    """Execute copying files of path_reference

    :param copy_set: set of (from, to) pairs to copy.
    :type copy_set: set
    :param report: function used for reporting warnings, takes a string argument.
    """
    pass


def angstrom_to_axunits(val, ax):
    """
    Converts value in Angstrom to units of x axis
    - used to scale bond widths regardless of axis size

    Args:
    val (float): value in Angstroms
    ax (plt.axis): matplotlib axis object used to scale value
    """
    xr = ax.get_xlim()[1] - ax.get_xlim()[0]
    fig = ax.get_figure()
    width = fig.bbox_inches.width * ax.get_position().width
    width *= 72
    return val * (width / xr)


def normalize_key(key, strip_prefix=False):
    """Use this function to normalize keys prior to adding to the PROPS
dictionary. Normalizing in this case means using a consistent format
for strings."""
    key = key.upper()
    key = key.replace('-', '_')
    if strip_prefix and key.startswith('PGHOPS_'):
        key = key.replace('PGHOPS_', '', 1)
    return key


@staticmethod
def _from_db_object(cluster_template, db_cluster_template):
    """Converts a database entity to a formal object."""
    for field in cluster_template.fields:
        cluster_template[field] = db_cluster_template[field]
    cluster_template.obj_reset_changes()
    return cluster_template


def current_service(request):
    """Return the Cornice service matching the specified request.

    :returns: the service or None if unmatched.
    :rtype: cornice.Service
    """
    if request.matched_route:
        services = request.registry.cornice_services
        pattern = request.matched_route.pattern
        name = request.matched_route.name
        service = services.get(pattern, services.get('__cornice' + name))
        return service


@staticmethod
def get_option_nibble(optionvalue):
    """
        Returns the 4-bit option header value.

        :param optionvalue: the option value (delta or length) to be encoded.
        :return: the 4-bit option header value.
         """
    if optionvalue <= 12:
        return optionvalue
    elif optionvalue <= 255 + 13:
        return 13
    elif optionvalue <= 65535 + 269:
        return 14
    else:
        raise AttributeError('Unsupported option delta ' + optionvalue)


def update_docstring(thing_with_docstring, deprecation):
    """Update an existing docstring based on a deprecation.

    Parameters
    ----------
    thing_with_docstring : object
        The deprecated class/method whose docstring should be modified.
    deprecation : :class:`.Deprecation`
        Deprecation instance.

    Returns
    -------
    str :
        updated docstring
    """
    docs = thing_with_docstring.__doc__
    if thing_with_docstring.__doc__ is None:
        docs = ''
    else:
        docs = thing_with_docstring.__doc__
    return docs + deprecation.docstring_message()


@staticmethod
def consumer_keyword(counts):
    """Return consumer or consumers depending on the process count.

        :param dict counts: The count dictionary to use process count
        :rtype: str

        """
    return 'consumer' if counts['processes'] == 1 else 'consumers'


@classmethod
def from_dict(cls, d):
    """
        Construct a new `UpdateByQuery` instance from a raw dict containing the search
        body. Useful when migrating from raw dictionaries.

        Example::

            ubq = UpdateByQuery.from_dict({
                "query": {
                    "bool": {
                        "must": [...]
                    }
                },
                "script": {...}
            })
            ubq = ubq.filter('term', published=True)
        """
    u = cls()
    u.update_from_dict(d)
    return u


def decode_response(client_message, to_object=None):
    """ Decode response from client message"""
    parameters = dict(response=None)
    parameters['response'] = client_message.read_long()
    return parameters


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 initialize(cls, *args, **kwargs):
    """
        Hook for performing specific output-specific tasks on initialization
        """
    return cls(*args, **kwargs)


def levenshtein(a, b):
    """Calculates the Levenshtein distance between a and b."""
    n, m = len(a), len(b)
    if n > m:
        a, b = b, a
        n, m = m, n
    current = range(n + 1)
    for i in range(1, m + 1):
        previous, current = current, [i] + [0] * n
        for j in range(1, n + 1):
            add, delete = previous[j] + 1, current[j - 1] + 1
            change = previous[j - 1]
            if a[j - 1] != b[i - 1]:
                change = change + 1
            current[j] = min(add, delete, change)
    return current[n]


def delete_assessment_run(assessmentRunArn=None):
    """
    Deletes the assessment run that is specified by the ARN of the assessment run.
    See also: AWS API Documentation

    Examples
    Deletes the assessment run that is specified by the ARN of the assessment run.
    Expected Output:

    :example: response = client.delete_assessment_run(
        assessmentRunArn='string'
    )

    :type assessmentRunArn: string
    :param assessmentRunArn: [REQUIRED]
            The ARN that specifies the assessment run that you want to delete.

    :return: response = client.delete_assessment_run(
        assessmentRunArn='arn:aws:inspector:us-west-2:123456789012:target/0-nvgVhaxX/template/0-it5r2S4T/run/0-11LMTAVe',
    )

    print(response)

    """
    pass


@classmethod
def can_handle_flow(cls, flow: 'OpenMLFlow') ->bool:
    """Check whether a given describes a Pytorch estimator.

        This is done by parsing the ``external_version`` field.

        Parameters
        ----------
        flow : OpenMLFlow

        Returns
        -------
        bool
        """
    return cls._is_pytorch_flow(flow)


def is_version_supported(api_version, version):
    """Check if a version is supported by the API.

    :param api_version: Reference endpoint API version.
    :param version: Version to check against API version.
    :return: boolean if the version is supported.
    """
    api_split = list(map(int, api_version.split('.')))
    ver_split = list(map(int, version.split('.')))
    if api_split[0] > ver_split[0] or api_split[0] == ver_split[0
        ] and api_split[1] >= ver_split[1]:
        return True
    return False


@staticmethod
def getJavaPackage():
    """ Returns package name String. """
    return 'com.microsoft.ml.spark.lime.TabularLIMEModel'


def quote_ident(value):
    """Indent the quotes."""
    return '"{}"'.format(value.replace('\\', '\\\\').replace('"', '\\"').
        replace('\n', '\\n'))


def get_field(key, obj):
    """
    Get field in dictionary.

    :param key: path to field in dictionary
    :type key: str

    :param obj: dictionary used for search
    :type obj: dict

    :returns: field value
    """
    val = obj
    for subkey in key.split('.'):
        val = val[subkey]
    return val


def remove_ttfa_table(tt):
    """Removes TTFA table from a fontTools.ttLib.TTFont object"""
    try:
        del tt['TTFA']
    except KeyError:
        pass


def format_length(length):
    """Return length in the format MM:SS or HH:MM:SS."""
    length = int(length)
    if length < 3600:
        minutes = length // 60
        seconds = length % 60
        return '{}:{}'.format(format(minutes, '02'), format(seconds, '02'))
    else:
        hours = length // 3600
        minutes = length % 3600 // 60
        seconds = length % 3600 % 60
        return '{}:{}:{}'.format(hours, format(minutes, '02'), format(
            seconds, '02'))


@classmethod
def _convert_to_stop(cls, stop_seq):
    """
        Convert ``stop_seq`` to a list of openpyxl v2 Color objects,
        suitable for initializing the ``GradientFill`` ``stop`` parameter.
        Parameters
        ----------
        stop_seq : iterable
            An iterable that yields objects suitable for consumption by
            ``_convert_to_color``.
        Returns
        -------
        stop : list of openpyxl.styles.Color
        """
    return map(cls._convert_to_color, stop_seq)


def recoverOrder(orderid):
    """ recover an order from the registry
        """


def __iter__():
    """Return an iterator which provides the values from the source."""


def quaternion_real(quaternion):
    """Return real part of quaternion.

    >>> quaternion_real([3, 0, 1, 2])
    3.0

    """
    return float(quaternion[0])


def SizeBenefitSickHosp(t):
    """Sickness hospitalization benefit per policy"""
    return 0


def theta_Ca_Na_HMW84(T, P):
    """c-c': calcium sodium [HMW84]."""
    theta = 0.07
    valid = T == 298.15
    return theta, valid


def average(old_avg, current_value, count):
    """
    Calculate the average. Count must start with 0

    >>> average(None, 3.23, 0)
    3.23
    >>> average(0, 1, 0)
    1.0
    >>> average(2.5, 5, 4)
    3.0
    """
    if old_avg is None:
        return current_value
    return (float(old_avg) * count + current_value) / (count + 1)


def dropping_label_categories(model, X, y, drop_label_categories, show_plot
    =True):
    """
    maximize success for a given problem by dropping the rows/samples containing the labels in the drop_label_categories list. This type of maximization is appropriate for problems such as credit default, where one wishes to simply ignore customers who will default.

    Arguments:
    ----------
        model: the model object of interest from which predictions will be made on the X dataset passed
        X, y: The features and labels the evaluation will be performed on
        drop_label_categories: list. The names of the label categories you wish to exclude for optimal results.

    Returns:
    -------
        df_lift: The lift score for each of the categories in the drop_label_categories list.
            - The lift is calculated as the original % of occurances / the % of occurances after dropping samples based on the predicted values
        y_drop: The true values corresponding to the samples selected after dropping the label categories from the y_pred
        y_pred_drop: The remaining predicted values after dropping the samples with values matching those in the drop_label_categories list
        y_drop_value_counts: Pandas df containg the value counts for the label categories before dropping based on the predicted values
        y_drop_value_counts: Pandas df containg the value counts for the label categories after dropping based on the predicted values
    """
    import pandas as pd
    y_pred = model.predict(X)
    y_pred = pd.DataFrame(y_pred, columns=list(y.columns))
    y_pred.index = y.index
    y_pred_drop = y_pred[~y_pred.iloc[:, (0)].isin(drop_label_categories)]
    drop_idx_list = list(y_pred[y_pred.iloc[:, (0)].isin(
        drop_label_categories)].index.values)
    y_drop = y.drop(drop_idx_list)
    assert y_drop.shape == y_pred_drop.shape
    y_value_counts = y.iloc[:, (0)].value_counts().reset_index()
    y_value_counts.columns = [y.columns[0], 'counts']
    y_value_counts['% of Total'] = y_value_counts['counts'] / y_value_counts[
        'counts'].sum() * 100
    y_drop_value_counts = y_drop.iloc[:, (0)].value_counts().reset_index()
    y_drop_value_counts.columns = [y_drop.columns[0], 'counts']
    y_drop_value_counts['% of Total'] = y_drop_value_counts['counts'
        ] / y_drop_value_counts['counts'].sum() * 100
    df_lift = (y_value_counts['% of Total'][y_value_counts.iloc[:, (0)].
        isin(drop_label_categories)] / y_drop_value_counts['% of Total'][
        y_drop_value_counts.iloc[:, (0)].isin(drop_label_categories)]
        ).reset_index()
    df_lift.columns = [y.columns[0], 'lift']
    if show_plot:
        import matplotlib.pyplot as plt
        fig, ax_list = plt.subplots(1, 2)
        p = 0
        for ylabel in ['counts', '% of Total']:
            for df_counts, label in [[y_value_counts, 'before drop'], [
                y_drop_value_counts, 'after drop']]:
                ax_list[p].bar(df_counts[y.columns[0]].astype(str),
                    df_counts[ylabel], label=label, alpha=0.5)
            ax_list[p].set_xticklabels(df_counts[y.columns[0]].astype(str),
                rotation=90)
            ax_list[p].legend()
            header = y.columns[0]
            if len(header) > 20:
                xlabel = '\n'.join(header.split(' '))
            else:
                xlabel = header
            ax_list[p].ticklabel_format(axis='y', style='sci', scilimits=(-
                3, 3))
            ax_list[p].set_xlabel(xlabel)
            ax_list[p].set_ylabel(ylabel)
            ax_list[p].grid(which='both', visible=False)
            p += 1
        fig.tight_layout(rect=(0, 0, 1.5, 1))
        plt.show()
    return df_lift, y_drop, y_pred_drop, y_value_counts, y_drop_value_counts


@staticmethod
def name_message_tuple_from_tag_ref(tag):
    """Convert a tag reference to a (name, message) tuple

        :param tag: tag reference
        :return: (name, message) tuple
        """
    return (tag.name, tag.tag.message if tag.tag else None) if tag else None


def Write_VCF(table, header, outname):
    """Write out vcf with filter info added

    Parameters
    ----------
    table : DataFrame
        final dataframe with updated filter info
    header : list
        stored header from original vcf with added FILTER lines
    outname : str
        output name for new vcf
    """
    with open(outname, 'w') as vcf_out:
        for line in header:
            vcf_out.write('%s' % line)
    table.to_csv(outname, sep='\t', header=False, mode='a', index=False)


@classmethod
def create_native(cls):
    """Creates a native socket.

        :returns: :class:`socket.socket`

        """


@classmethod
def promise(cls, fn, *args, **kwargs):
    """
        Used to build a task based on a callable function and the arguments.
        Kick it off and start execution of the task.

        :param fn: callable
        :param args: tuple
        :param kwargs: dict
        :return: SynchronousTask or AsynchronousTask
        """
    task = cls.task(target=fn, args=args, kwargs=kwargs)
    task.start()
    return task


def _whctrs(anchor):
    """Return width, height, x center, and y center for an anchor (window)."""
    w = anchor[2] - anchor[0] + 1
    h = anchor[3] - anchor[1] + 1
    ctr_x = anchor[0] + 0.5 * (w - 1)
    ctr_y = anchor[1] + 0.5 * (h - 1)
    return w, h, ctr_x, ctr_y


def pre_search(cs, term, planlove):
    """
    This hook is called before a (quicklove or regular) search, and is
    passed the same arguments as is the search function:

     - the search ``term``
     - ``planlove``, a boolean of whether to restrict search to planlove.

    """
    pass


def scrub_string(string, secrets):
    """Given a string and a list of secrets, scrubs s of every secret."""
    for secret in secrets:
        if secret is not None and len(secret) > 2:
            string = string.replace(secret, '.' * len(secret))
    return string


def get_crop_specs(proposal, classifier):
    """Converts a crater proposal into cropping function
    arguments.
    """
    lat = proposal[0]
    long = proposal[1]
    px = classifier.crater_pixels
    dim = classifier.input_dims
    r_im = proposal[2] * min(dim) / (2 * px)
    upper = lat - r_im
    left = long - r_im
    return (round(upper), round(left)), (round(2 * r_im), round(2 * r_im))


def p_suite_1(p):
    """suite : simple_stmt"""
    p[0] = p[1]


def frequencies(l):
    """
    Return number of times each item appears in the list.
    """
    result = {}
    for item in l:
        if not item in result:
            result[item] = 0
        result[item] += 1
    return result


def setNamedItem(selfm, jsAttr):
    """
    The setNamedItem() method adds the specified node to the NamedNodeMap.

    If the node already exists, it will be replaced, and the replaced node will be the return value, otherwise the return value will be null.

    Related Pages:

			https://www.w3schools.com/jsref/met_namednodemap_setnameditem.asp

    :return: A Node object, representing the replaced node (if any), otherwise null
    """
    return 'setNamedItem(%s)' % jsAttr


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

        :param AppUnlinkUserDetails val:
        :rtype: EventDetails
        """
    return cls('app_unlink_user_details', val)


def get_schema(path='', type=False):
    """
        Delivers a schema in a dictionary format, where keys are attribute names
        and there values are a dictionary of required, type and value information.
        e.g.:

        {'attribute_name':
            {'required': (True or False) or (1 or 0)
             'type': lines, text, boolean, etc.
             'value': ... }, ... }

        If type is 'True', then no object exists to get a schema from. path in
        this case is the type_name. This indicates two functionalities in one method.
        """


def _split_epi_lists(in_files, pe_dir, max_trs=50):
    """
    Split input EPIs and generate an output list of PEs.

    Inputs
    ------
    in_files : list of ``BIDSFile``s
        The EPI images that will be pooled into field estimation.
    pe_dir : str
        The phase-encoding direction of the IntendedFor EPI scan.
    max_trs : int
        Index of frame after which all volumes will be discarded
        from the input EPI images.

    """
    from os import path as op
    import nibabel as nb
    matched_pe = []
    opposed_pe = []
    for i, (epi_path, epi_pe) in enumerate(in_files):
        if epi_pe[0] == pe_dir[0]:
            img = nb.load(epi_path)
            if len(img.shape) == 3:
                splitnii = [img]
            else:
                splitnii = nb.four_to_three(img.slicer[:, :, :, :max_trs])
            for j, nii in enumerate(splitnii):
                out_name = op.abspath('dir-%s_tstep-%03d_pe-%03d.nii.gz' %
                    (epi_pe, i, j))
                nii.to_filename(out_name)
                if epi_pe == pe_dir:
                    matched_pe.append(out_name)
                else:
                    opposed_pe.append(out_name)
    if matched_pe:
        return [opposed_pe, matched_pe]
    return [opposed_pe]


def findall(p, s):
    """Yields all the positions of
    the pattern p in the string s."""
    i = s.find(p)
    while i != -1:
        yield i
        i = s.find(p, i + 1)


def get_label(node, data_property: str, id_hidden: bool):
    """
    Get label of node.

    :param ~ttree.Node node: Tree node instance
    :param data_property: Data property name
    :param id_hidden: Is ID hidden?
    :return:
    """
    result = getattr(node.data, data_property) if data_property else node.tag
    return result if id_hidden else f'{result}[{node.id}]'


def zero(sys):
    """
    Compute system zeros.

    Parameters
    ----------
    sys: StateSpace or TransferFunction
        Linear system

    Returns
    -------
    zeros: ndarray
        Array that contains the system's zeros.

    Raises
    ------
    NotImplementedError
        when called on a MIMO system

    See Also
    --------
    pole
    StateSpace.zero
    TransferFunction.zero

    """
    return sys.zero()


def ltrim1(l, proportiontocut, tail='right'):
    """
Slices off the passed proportion of items from ONE end of the passed
list (i.e., if proportiontocut=0.1, slices off 'leftmost' or 'rightmost'
10% of scores).  Slices off LESS if proportion results in a non-integer
slice index (i.e., conservatively slices off proportiontocut).

Usage:   ltrim1 (l,proportiontocut,tail='right')  or set tail='left'
Returns: trimmed version of list l
"""
    if tail == 'right':
        lowercut = 0
        uppercut = len(l) - int(proportiontocut * len(l))
    elif tail == 'left':
        lowercut = int(proportiontocut * len(l))
        uppercut = len(l)
    return l[lowercut:uppercut]


@classmethod
def format_target_elements(cls, results, t_format=None):
    """Format neo4j results as target sensors"""
    thermal_details = {'source': {}, 'targets': []}
    for record in results:
        thermal_details['source'] = dict(record.get('source'))
        if not t_format:
            t_format = lambda r: {**dict(r.get('targets')), **{'rel': list(
                map(dict, r.get('rel')))}}
        thermal_details['targets'].append(t_format(record))
    return thermal_details


@classmethod
def id_dict(self_or_cls):
    """
        Return dict representation of desired resource (allowing its localization).
        Stub, for easier implementation.
        """
    return {}


def fancy_string_time_from_seconds(input_seconds):
    """
        It converts a time in seconds into a string that is beautiful to read

        Args:
            input_seconds:  time in seconds

        Returns:
            a fancy string like 1h 21m 42s
    """
    try:
        input_seconds = float(input_seconds)
    except ValueError:
        return input_seconds
    minutes, seconds = divmod(input_seconds, 60)
    hours, minutes = divmod(minutes, 60)
    if hours > 0:
        return '%dh %dm %02ds' % (hours, minutes, seconds)
    if minutes > 0:
        return '%dm %02ds' % (minutes, seconds)
    return '%.2fs' % seconds


def get_readonly():
    """Return another IURI instance that represents a read-only form of
        this one. If is_readonly() is True, this returns self."""


def svm_read_problem(data_file_name):
    """
	svm_read_problem(data_file_name) -> [y, x]

	Read LIBSVM-format data from data_file_name and return labels y
	and data instances x.
	"""
    prob_y = []
    prob_x = []
    for line in open(data_file_name):
        line = line.split(None, 1)
        if len(line) == 1:
            line += ['']
        label, features = line
        xi = {}
        for e in features.split():
            ind, val = e.split(':')
            xi[int(ind)] = float(val)
        prob_y += [float(label)]
        prob_x += [xi]
    return prob_y, prob_x


def identity(arg):
    """
    Function which returns the argument. Used as a default lambda function.

    >>> obj = object()
    >>> obj is identity(obj)
    True

    :param arg: object to take identity of
    :return: return arg
    """
    return arg


@classmethod
def fromElement(Class, element):
    """
        Create a stanza from a L{domish.Element}.
        """
    stanza = Class()
    stanza.parseElement(element)
    return stanza


def get_keywords():
    """Get the keywords needed to look up the version information."""
    git_refnames = '$Format:%d$'
    git_full = '$Format:%H$'
    keywords = {'refnames': git_refnames, 'full': git_full}
    return keywords


def filtersplit(p, iterable):
    """
    filtersplit(p, iter) -> ifilter(p, iter), ifilterfalse(p, iter)

    >>> iseven = lambda x: (x % 2) == 0
    >>> filtersplit(iseven, [0, 1, 2, 3, 4])
    ([0, 2, 4], [1, 3])
    """
    t, f = [], []
    if p is None:
        p = bool
    for i in iterable:
        if p(i):
            t.append(i)
        else:
            f.append(i)
    return t, f


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

    The ".dev0" means dirty.

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


@classmethod
def search(cls, client=None):
    """A search query for all images.

        Return an `~descarteslabs.catalog.ImageSearch` instance for searching
        images in the Descartes Labs catalog.  This instance extends the
        :py:class:`~descarteslabs.catalog.Search` class with the
        :py:meth:`~descarteslabs.catalog.ImageSearch.summary` and
        :py:meth:`~descarteslabs.catalog.ImageSearch.summary_interval` methods
        which return summary statistics about the images that match the search query.

        Parameters
        ----------
        client : :class:`CatalogClient`, optional
            A `CatalogClient` instance to use for requests to the Descartes Labs
            catalog.

        Returns
        -------
        :class:`~descarteslabs.catalog.ImageSearch`
            An instance of the `~descarteslabs.catalog.ImageSearch` class

        Example
        -------
        >>> search = Image.search().limit(10)
        >>> for result in search:
                print(result.name)

        """
    from .search import ImageSearch
    return ImageSearch(cls, client=client)


@classmethod
def _from_object(cls, context, obj):
    """Construct a node from node object.

        @param context: the context used for DB operations;
        @param obj: a node object that contains all fields;
        """
    kwargs = {'id': obj.id, 'physical_id': obj.physical_id, 'user': obj.
        user, 'project': obj.project, 'domain': obj.domain, 'index': obj.
        index, 'role': obj.role, 'init_at': obj.init_at, 'created_at': obj.
        created_at, 'updated_at': obj.updated_at, 'status': obj.status,
        'status_reason': obj.status_reason, 'data': obj.data, 'metadata':
        obj.metadata, 'dependents': obj.dependents}
    return cls(obj.name, obj.profile_id, obj.cluster_id, context=context,
        **kwargs)


def _movetofloat(origvalue, fmtstring, neg, addseparators=False, sepchar=
    ',', fillchar=' '):
    """ addseparators = add separator character every three numerals if True
    """
    fmt0 = fmtstring.split('.')
    fmt1 = fmt0[0]
    fmt2 = fmt0[1]
    val = origvalue.split('.')[0].strip()
    ret = fillchar * (len(fmt1) - len(val)) + val + '.' + '0' * len(fmt2)
    if neg:
        ret = '-' + ret[1:]
    return ret, len(fmt1)


@staticmethod
def _check_targets(y_actual, y_predicted):
    """Check that y_actual and y_predicted have the same length.

        :param H2OFrame y_actual:
        :param H2OFrame y_predicted:

        :returns: None
        """
    if len(y_actual) != len(y_predicted):
        raise ValueError('Row mismatch: [{},{}]'.format(len(y_actual), len(
            y_predicted)))


def print_sale_invoice(sale_invoice, invoice_printer):
    """Utility function to print a sale invoice.

    :param sale: a :class:`stoqlib.domain.sale.Sale` instance
    :param invoice_printer: :class:`stoqlib.domain.invoice.InvoicePrinter` instance
    """
    sale_invoice.send_to_printer(invoice_printer.device_name)


@classmethod
def read_from_file(cls, filename):
    """
             gets a file name and load the file as a Signal class

            :param filename: signal file name
            :return: instance of Signal class

             """
    x_vec = []
    y_vec = []
    with open(filename) as signal_file:
        for line in signal_file:
            if '#' in line:
                continue
            values = line.split()
            if len(values) > 1:
                try:
                    x = float(values[0])
                    y = float(values[1])
                    x_vec.append(x)
                    y_vec.append(y)
                except ValueError:
                    continue
    return cls(x_vec, y_vec)


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

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

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


def _(message):
    """
    Dummy gettext function used to mark a string as translateable for
    xgettext.
    """
    return message


def fix_for_path(string):
    """
        Fixes special path characters in a
        given string to make it usuable in
        a file or directory name.

        :param str string: the string to fix

        :returns: the fixed string
        :rtype: str
    """
    return string.replace('/', '_')


def chunks(l, n):
    """ Yield n successive chunks from l.
    """
    newn = int(1.0 * len(l) / n + 0.5)
    for i in range(0, n - 1):
        yield l[i * newn:i * newn + newn]
    yield l[n * newn - newn:]


@classmethod
def _from_dict(cls, _dict):
    """Initialize a SpeechRecognitionAlternative object from a json dictionary."""
    args = {}
    if 'transcript' in _dict:
        args['transcript'] = _dict.get('transcript')
    else:
        raise ValueError(
            "Required property 'transcript' not present in SpeechRecognitionAlternative JSON"
            )
    if 'confidence' in _dict:
        args['confidence'] = _dict.get('confidence')
    if 'timestamps' in _dict:
        args['timestamps'] = _dict.get('timestamps')
    if 'word_confidence' in _dict:
        args['word_confidence'] = _dict.get('word_confidence')
    return cls(**args)


@staticmethod
def get_state_arguments_model():
    """
        This is needed so the BaseState can validate the provided
        model has the required or optional arguments for the state
        to function.
        return = {
            'required_state_arguments': {
                'required_state_arg_1': type,
                'required_state_arg_2': type,
            },
            'optional_state_arguments': {
                'optional_state_arg_1': type,
                'optional_state_arg_2': type,
            },
        }
        """
    return {'required_state_arguments': {'current_num': int, 'is_snapshot':
        bool}, 'required_State_arguments': {}}


def read_id(stream):
    """Reads a chunk ID from a stream."""
    return stream.read(4)


def hermann_adjustment_factors(bval, min_mag, mag_inc):
    """
    Returns the adjustment factors (fval, fival) proposed by Hermann (1978)

    :param float bval:
        Gutenberg & Richter (1944) b-value

    :param np.ndarray min_mag:
        Minimum magnitude of completeness table

    :param non-negative float mag_inc:
        Magnitude increment of the completeness table
    """
    fval = 10.0 ** (bval * min_mag)
    fival = 10.0 ** (bval * (mag_inc / 2.0)) - 10.0 ** (-bval * (mag_inc / 2.0)
        )
    return fval, fival


def mag_intersect(A, B):
    """
    Returns magnitude of multiset-intersection of A and B
    """
    val = 0
    for term in A:
        if term in B:
            val += min(A[term], B[term])
    return val


def tors_delta(universe, seg, i):
    """delta backbone dihedral

    The dihedral is computed based on position atoms for resid `i`.

    Parameters
    ----------
    universe : Universe
         :class:`~MDAnalysis.core.universe.Universe` containing the trajectory
    seg : str
        segment id for base
    i : int
        resid of the first base

    Returns
    -------
    delta : float
        torsion angle in degrees

    .. versionadded:: 0.7.6
    """
    d = universe.select_atoms(" atom {0!s} {1!s} C5' ".format(seg, i),
        " atom {0!s} {1!s} C4' ".format(seg, i), " atom {0!s} {1!s} C3' ".
        format(seg, i), " atom {0!s} {1!s} O3' ".format(seg, i))
    delta = d.dihedral.value() % 360
    return delta


def get_mark_function(metafunc):
    """Extract the name of the function being called."""
    for key in metafunc.function.__dict__:
        if key.lower().startswith('faux'):
            return getattr(metafunc.function, key)


def dotted_root(path: str) ->str:
    """ Return the root of a dotted path
    :param path: dotted path
    :return: dotted path sans rightmost node
    """
    return path.rsplit('.', 1)[0]


def update_gcm_channel(ApplicationId=None, GCMChannelRequest=None):
    """
    Use to update the GCM channel for an app.

    :example: response = client.update_gcm_channel(
        ApplicationId='string',
        GCMChannelRequest={
            'ApiKey': 'string'
        }
    )

    :type ApplicationId: string
    :param ApplicationId: [REQUIRED]

    :type GCMChannelRequest: dict
    :param GCMChannelRequest: [REQUIRED] Google Cloud Messaging credentials
            ApiKey (string) -- Platform credential API key from Google.

    :rtype: dict
    :return: {
        'GCMChannelResponse': {
            'ApplicationId': 'string',
            'CreationDate': 'string',
            'Credential': 'string',
            'Id': 'string',
            'IsArchived': True|False,
            'LastModifiedBy': 'string',
            'LastModifiedDate': 'string',
            'Platform': 'string',
            'Version': 123
        }
    }

    :returns:
    (dict) -- 200 response
    GCMChannelResponse (dict) -- Google Cloud Messaging channel definition
    ApplicationId (string) -- The ID of the application to which the channel applies.
    CreationDate (string) -- When was this segment created
    Credential (string) -- The GCM API key from Google.
    Id (string) -- The unique channel ID.
    IsArchived (boolean) -- Is this channel archived
    LastModifiedBy (string) -- Who last updated this entry
    LastModifiedDate (string) -- Last date this was updated
    Platform (string) -- The platform type. Will be GCM
    Version (integer) -- Version of channel

    """
    pass


def get_max(val, val_max, idx, idx_max):
    """Function to get the maximum value."""
    if val > val_max:
        return val, idx
    else:
        return val_max, idx_max


def new_core_text(db):
    """
    Returns /docProps/core.xml text

    :param pylightxl.Database db: database contains sheetnames, and their data
    :return str: /docProps/core.xml text
    """
    xml_base = (
        '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n<cp:coreProperties xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:dcmitype="http://purl.org/dc/dcmitype/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties">\r\n<dc:creator>pylightxl</dc:creator>\r\n<cp:lastModifiedBy>pylightxl</cp:lastModifiedBy>\r\n<dcterms:created xsi:type="dcterms:W3CDTF">2019-12-27T01:35:28Z</dcterms:created>\r\n<dcterms:modified xsi:type="dcterms:W3CDTF">2019-12-27T01:35:39Z</dcterms:modified>\r\n</cp:coreProperties>'
        )
    return xml_base


def paste():
    """Paste the material settings and nodes

    """
    pass


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

        :param SharedLinkSettingsAddPasswordType val:
        :rtype: EventType
        """
    return cls('shared_link_settings_add_password', val)


@classmethod
def set_login_cookie(cls, handler, user_id=None):
    """Call this on handlers to set the login cookie for success"""
    cookie_options = handler.settings.get('cookie_options', {})
    cookie_options.setdefault('httponly', True)
    if handler.settings.get('secure_cookie', handler.request.protocol ==
        'https'):
        cookie_options.setdefault('secure', True)
    cookie_options.setdefault('path', handler.base_url)
    handler.set_secure_cookie(handler.cookie_name, user_id, **cookie_options)
    return user_id


def attachment_reparented(attachment, old_parent_realm, old_parent_id):
    """Called when an attachment is reparented.

        :since 1.3.2: deprecated and will be removed in 1.5.1. Use
            `attachment_moved` instead.
        """


@classmethod
def getVersion(cls):
    """
        This method must be implemented by subclasses.
        """
    raise NotImplementedError('This method must be implemented by a subclass.')


def format_git_describe(git_str, pep440=False):
    """format the result of calling 'git describe' as a python version"""
    if '-' not in git_str:
        formatted_str = git_str
    else:
        git_str = git_str.replace('-', '.post', 1)
        if pep440:
            formatted_str = git_str.split('-')[0]
        else:
            formatted_str = git_str.replace('-g', '+git')
    if formatted_str.startswith('v'):
        formatted_str = formatted_str[1:]
    return formatted_str


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


def list_exploded(client, file_=None, name=None):
    """List views that match criteria and are exploded.

    Args:
        client (obj):
            creopyson Client.
        `file_` (str, optional):
            Model name. Defaults is current active model.
        name (str, optional):
            View name (wildcards allowed: True).
            Defaults is None: all views are listed.

    Returns:
        (list:str): List of view names.

    """
    data = {}
    if name is not None:
        data['name'] = name
    if file_ is not None:
        data['file'] = file_
    else:
        active_file = client.file_get_active()
        if active_file is not None:
            data['file'] = active_file['file']
    return client._creoson_post('view', 'list_exploded', data, 'viewlist')


def glValidateProgram(program: int):
    """Validates a program object

    :param program: Specifies the handle of the program object to be validated.
    :type program: int
    """
    pass


@staticmethod
def textjoin(a, b):
    """Join a and b, replacing either with an empty string
        if their value is not True"""
    return ''.join([a or '', b or ''])


def __str__():
    """Return a short description of the adapter"""


def prob_bv_rectangle(lower, upper, cdf):
    """helper function for probability of a rectangle in a bivariate distribution

    Parameters
    ----------
    lower : array_like
        tuple of lower integration bounds
    upper : array_like
        tuple of upper integration bounds
    cdf : callable
        cdf(x,y), cumulative distribution function of bivariate distribution

    how does this generalize to more than 2 variates ?
    """
    probuu = cdf(*upper)
    probul = cdf(upper[0], lower[1])
    problu = cdf(lower[0], upper[1])
    probll = cdf(*lower)
    return probuu - probul - problu + probll


def split(input, sizes_or_sections, dim):
    """Split the input tensor into chunks.

    If ``sizes_or_sections`` is an integer, then the tensor will
    be splitted into equal pieces.

    If ``sizes_or_sections`` is a list, then the tensor will be
    splitted into segments.

    Parameters
    ----------
    input : Tensor

    Returns
    -------
    list of Tensor
        The splitted tensors.
    """
    pass


@classmethod
def _stripe_object_to_default_tax_rates(cls, target_cls, data):
    """
        Retrieves TaxRates for a Subscription or Invoice
        :param target_cls:
        :param data:
        :param instance:
        :type instance: Union[djstripe.models.Invoice, djstripe.models.Subscription]
        :return:
        """
    tax_rates = []
    for tax_rate_data in data.get('default_tax_rates', []):
        tax_rate, _ = target_cls._get_or_create_from_stripe_object(
            tax_rate_data, refetch=False)
        tax_rates.append(tax_rate)
    return tax_rates


@classmethod
def case(cls, parent=None):
    """Create case node."""
    node = cls('case', parent)
    node.occur = 0
    return node


def merge(x, y):
    """Merge two ordered lists

    :param x:
    :param y: x,y are non decreasing ordered lists
    :returns: union of x and y in order
    :complexity: linear
    """
    z = []
    i = 0
    j = 0
    while i < len(x) or j < len(y):
        if j == len(y) or i < len(x) and x[i] <= y[j]:
            z.append(x[i])
            i += 1
        else:
            z.append(y[j])
            j += 1
    return z


def add_sequence(sequence):
    """Add sequence of related IORMModel providers into graph"""


def map_serial_number(facilities) ->str:
    """Map serial number."""
    facility = facilities.get('body', dict()).get('facilitiesList', list())[0]
    return str(facility.get('serialNumber', None))


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

        :param SharingUserError val:
        :rtype: AddFileMemberError
        """
    return cls('user_error', val)


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


def set_model_name(model, name):
    """Overwrite .name or ._name'"""
    if hasattr(model, 'name'):
        model.name = name
    elif hasattr(model, '_name'):
        model._name = name
    else:
        pass


def trailing_blank_lines(physical_line, lines, line_number, total_lines):
    """Trailing blank lines are superfluous.

    Okay: spam(1)
    W391: spam(1)\\n

    However the last line should end with a new line (warning W292).
    """
    if line_number == total_lines:
        stripped_last_line = physical_line.rstrip()
        if not stripped_last_line:
            return 0, 'W391 blank line at end of file'
        if stripped_last_line == physical_line:
            return len(physical_line), 'W292 no newline at end of file'


@classmethod
def greyple(cls):
    """A factory method that returns a :class:`Colour` with a value of ``0x99aab5``."""
    return cls(10070709)


def ARGMIN(agg_column, out_column):
    """
    Builtin arg minimum aggregator for groupby

    Example: Get the movie with minimum rating per user.

    >>> sf.groupby("user",
    ...            {'best_movie':tc.aggregate.ARGMIN('rating','movie')})
    """
    return '__builtin__argmin__', [agg_column, out_column]


def getPositiveCoordinateRangeOverlap(uStart1, uEnd1, uStart2, uEnd2):
    """@return: If the two coordinate ranges overlap on the same strand
    returns the overlap range. If no overlap it returns None.
    """
    if uEnd1 < uStart2 or uEnd2 < uStart1:
        return None
    l = [uStart1, uEnd1, uStart2, uEnd2]
    l.sort()
    return l[1], l[2]