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


def get_iex_symbols(*args, **kwargs):
    """
    Returns a list of all equity symbols available for trading on IEX. Accepts
    no additional parameters.

    Reference: https://www.iextrading.com/developer/docs/#symbols

    :return: DataFrame
    """
    from pandas_datareader.iex.ref import SymbolsReader
    return SymbolsReader(*args, **kwargs).read()


def parse_args(argument_parser, system_arguments):
    """Call `parse_args` on the argument parser.

    Parameters
    ----------
    - argument_parser - the main argument parser for awsume
    - system_arguments - the arguments from the system

    Returns
    -------
    The parsed arguments.
    """
    return argument_parser.parse_args(system_arguments)


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

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

    """
    pass


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


def _convert_color(color):
    """Convert a 24-bit color to 16-bit.

    The input `color` is assumed to be a 3-component list [R,G,B], each with
    8 bits for color level.

    This method will translate that list of colors into a 16-bit number,
    with first 5 bits indicating R component,
    last 5 bits indicating B component, and remaining
    6 bits in the middle indicating G component.
    i.e., 16-bit color -> (5 bits, 6 bits, 5 bits) -> (R,G,B).

    """
    for i in color:
        if i not in range(256):
            raise ValueError('Valid color value for R, G, B is 0 - 255.')
    red, green, blue = color
    return (blue & 248) << 8 | (green & 252) << 3 | (red & 248) >> 3


def find_subtree(root, label_parts):
    """Given a nested tree and a label to look for, find the associated node
    in the tree. Note that, unlike regulations, preamble trees _always_ encode
    their exact position in the tree."""
    cursor = root
    while cursor and cursor['label'] != label_parts:
        next_cursor = None
        for child in cursor['children']:
            if child['label'] == label_parts[:len(child['label'])]:
                next_cursor = child
        cursor = next_cursor
    return cursor


def save_graph_to_svg(G, labels, filename, backward=False):
    """ Generate a figure of a networkx's graph object and save it. """
    import networkx as nx
    if backward:
        G = G.reverse()
    pydot_graph = nx.drawing.nx_pydot.to_pydot(G)
    pydot_graph.set_rankdir('LR')
    pydot_graph.set_nodesep(0.5)
    for n in pydot_graph.get_nodes():
        name = n.get_name()
        n.set_style('rounded')
        n.set_style('filled')
        n.set_shape('box')
        n.set_fillcolor('#E5E5E5')
        n.set_width(0)
        n.set_height(0)
        n.set_label(labels[name.strip('"')])
    pydot_graph.write_svg(filename)


def validate_input(validator_func):
    """
    Wrapper around Validator funcs.
    """
    inp_str = input()
    return validator_func(inp_str)


def init():
    """Initialize features that are normally initialized in the CLI"""
    from metapack.appurl import SearchUrl
    import metapack as mp
    from os import environ
    SearchUrl.initialize()
    mp.Downloader.context.update(environ)


def ARRAY_ELEM_AT(array, idx):
    """
    Returns the element at the specified array index.
    See https://docs.mongodb.com/manual/reference/operator/aggregation/arrayElemAt/
    for more details
    :param array: An expression that can be any valid expression as long as it resolves to an array.
    :param idx: An expression can be any valid expression as long as it resolves to an integer.
    :return: Aggregation operator
    """
    return {'$arrayElemAt': [array, idx]}


def return_response_dimension(response):
    """Parses and prints the Analytics Reporting API V4 response
       Returns a dictionary of all the values"""
    for report in response.get('reports', []):
        columnHeader = report.get('columnHeader', {})
        dimensionHeaders = columnHeader.get('dimensions', [])
        metricHeaders = columnHeader.get('metricHeader', {}).get(
            'metricHeaderEntries', [])
        rows = report.get('data', {}).get('rows', [])
        returned = []
        for row in rows:
            dimensions = row.get('dimensions', [])
            dateRangeValues = row.get('metrics', [])
            for i, values in enumerate(dateRangeValues):
                d = {}
                d[dimensions[0]] = values.get('values')[0]
                returned.append(d)
            """
      for header, dimension in zip(dimensionHeaders, dimensions):
        print(header + ': ' + dimension)

      for i, values in enumerate(dateRangeValues):
        print('Date range (' + str(i) + ')')
        for metricHeader, value in zip(metricHeaders, values.get('values')):
          print(metricHeader.get('name') + ': ' + value)
      """
        return returned


def removeLanguage(lang):
    """Remove the object under the given language."""


@classmethod
def parse(cls, api, json):
    """Parse a JSON object into a model instance."""
    raise NotImplementedError


def __contains__(k):
    """ Return ``True`` if key ``k`` exists in the dictionary."""


@classmethod
def reset(cls):
    """
        Reset the blueprint. Blueprints are typically reset before being used to
        assemble a quota of documents. Resetting a Blueprint will in turn reset
        all the Maker instances defined as instructions for the Blueprint
        allowing internal counters and alike to be reset.
        """
    for maker in cls._instructions.values():
        maker.reset()


def write_text(filename, data, add=False):
    """ Write image data to text file

    :param filename: name of text file to write data to
    :type filename: str
    :param data: image data to write to text file
    :type data: numpy array
    :param add: whether to append to existing file or not. Default is `False`
    :type add: bool
    """
    write_type = 'a' if add else 'w'
    with open(filename, write_type) as file:
        print(data, end='', file=file)


def shell_clearance(DBundle=None, DShell=None):
    """Looks up the recommended clearance between a shell and tube bundle in
    a TEMA HX [1]. Either the bundle diameter or the shell diameter are needed
    provided.

    Parameters
    ----------
    DBundle : float, optional
        Outer diameter of tube bundle, [m]
    DShell : float, optional
        Shell inner diameter, [m]

    Returns
    -------
    c : float
        Shell-tube bundle clearance, [m]

    Notes
    -----
    Lower limits are extended up to the next limit where intermediate limits
    are not provided.

    Examples
    --------
    >>> shell_clearance(DBundle=1.245)
    0.0064

    References
    ----------
    .. [1] Standards of the Tubular Exchanger Manufacturers Association,
       Ninth edition, 2007, TEMA, New York.
    """
    DShell_data = [(0.457, 0.0032), (1.016, 0.0048), (1.397, 0.0064), (
        1.778, 0.0079), (2.159, 0.0095)]
    DBundle_data = [(0.457 - 0.0048, 0.0032), (1.016 - 0.0064, 0.0048), (
        1.397 - 0.0079, 0.0064), (1.778 - 0.0095, 0.0079), (2.159 - 0.011,
        0.0095)]
    if DShell:
        for DShell_tabulated, c in DShell_data:
            if DShell < DShell_tabulated:
                return c
        return 0.011
    elif DBundle:
        for DBundle_tabulated, c in DBundle_data:
            if DBundle < DBundle_tabulated:
                return c
        return 0.011
    else:
        raise Exception('Either DShell or DBundle must be specified')


def lua_bytes(text):
    """Convert some bytes into an escaped lua string literal."""
    out = b''
    for byte in text:
        byte = byte if isinstance(byte, int) else ord(byte)
        if byte == ord('\\'):
            out += b'\\\\'
        elif byte == ord("'"):
            out += b"\\'"
        elif 32 <= byte < 127:
            out += chr(byte).encode('ascii')
        else:
            out += '\\x{:02X}'.format(byte).encode('ascii')
    return b"'" + out + b"'"


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


def norm_point(pt):
    """normalize point to a tuple (x,y)"""
    return tuple(pt.reshape(2))


@classmethod
def should_run_forward(cls, config):
    """
        Returns True if Converter should be instantiated and run
        during the forward conversion process (NetJSON to native)
        """
    return cls.netjson_key in config


def supports(behavior_interface):
    """Determine if the context supports the given behavior, returning
        True or False.
        """


def quote_non_numeric(s):
    """return a prequoted string for non-numerics
    useful for perl and Rscript parameter passing?
    """
    try:
        float(s)
        return s
    except ValueError:
        return '"%s"' % s


def variant_is_good_to_keep(cur, g, log):
    """Check that the currently selected variant is good to keep.

    When this is called, it's after parsing the summary statistics and when
    looking up variants in the reference panel.

    This means that the filters being applied are:

    - Reference panel MAF filtering
    - Filters based on the availability in reference panels
    - Filters based on multiallelic / duplicates in reference panel

    """
    if len(g) == 0:
        if log.parameters['EXCLUDE_NO_REFERENCE']:
            log.record_excluded(cur, 'NOT_IN_REFERENCE_PANEL')
            return False
        else:
            log.record_included_special(cur, 'NOT_IN_REFERENCE',
                'Variant {} was absent from the reference panel but was still included in the GRS. It is important to validate that it is not correlated with other included variants.'
                .format(cur))
            return True
    elif len(g) == 1:
        maf = g[0].maf()
        if maf <= log.parameters['MAF_THRESHOLD']:
            log.record_excluded(cur, 'MAF_FILTER',
                'MAF from reference panel is {:g}'.format(maf))
            return False
    elif len(g) > 1:
        log.record_excluded(cur, 'DUP_OR_MULTIALLELIC_IN_REFERENCE_PANEL')
        return False
    return True


@classmethod
def create_job_resource(cls, **kwargs):
    """
        Create a suitable job resource from the kwargs specified
        """
    if cls._job_resource_class is None:
        raise NotImplementedError
    return cls._job_resource_class(**kwargs)


def get_fssnapshot(module, blade):
    """Return Snapshot or None"""
    try:
        filt = "source='" + module.params['name'
            ] + "' and suffix='" + module.params['suffix'] + "'"
        res = blade.file_system_snapshots.list_file_system_snapshots(filter
            =filt)
        return res.items[0]
    except Exception:
        return None


@classmethod
def count(cls, query=None, myindex=None):
    """Get the total of records. Return the count only.

    query: dict to request on specific result
    myindex: str example: pictures,albums <--- no space between the values

    return: number of result

    """
    conn = cls.get_connection()
    if query:
        query['size'] = 0
    else:
        query = {'query': {'match_all': {}}, 'size': 0}
    if not myindex:
        myindex = cls.get_index_name()
    result = conn.search(index=myindex, body=query)
    return result['hits']['total']


def sizeof_fmt(num, suffix='B', num_type='data'):
    """
    Convert bytes into a human readable format

    Straight rip from stackoverflow
    """
    if num_type == 'data':
        for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']:
            if abs(num) < 1024.0:
                return '%3.1f %s%s' % (num, unit, suffix)
            num /= 1024.0
        return '%.1f %s%s' % (num, 'Yi', suffix)
    else:
        if abs(num) < 1000:
            return num
        for unit in ['', 'K', 'M', 'B']:
            if abs(num) < 1000.0:
                return '%3.1f %s' % (num, unit)
            num /= 1000.0
        return '%.1f %s' % (num, 'T')


def no_match_load(key):
    """ If no match is made when loading, need to raise an exception
    """
    raise RuntimeError('Cannot load %s data type' % key)


def server_list(client, resource_group_name=None):
    """
    Lists servers in a resource group or subscription
    """
    if resource_group_name:
        return client.list_by_resource_group(resource_group_name=
            resource_group_name)
    return client.list()


@staticmethod
def _build_component_names_list(filename):
    """ Builds an ordered list of strings from a file
        containing strings on separate lines (e.g., the row
        and col files """
    ordered_names = list()
    with open(filename, 'r') as f:
        for line in f:
            ordered_names.append(line.strip('\n'))
    return ordered_names


def deactivate_user(UserId=None):
    """
    Deactivates the specified user, which revokes the user's access to Amazon WorkDocs.
    See also: AWS API Documentation

    :example: response = client.deactivate_user(
        UserId='string'
    )

    :type UserId: string
    :param UserId: [REQUIRED]
            The ID of the user.

    """
    pass


def _write_line(content, add, overwrite=False):
    """Append to content or replace

    append when overwrite is false,
    replace the last element when overwrite is true"""
    if overwrite == True:
        content[-1] = add
    else:
        content.append(add)
    return content


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

        :param AddFolderMemberError val:
        :rtype: UpdateFolderMemberError
        """
    return cls('no_explicit_access', val)


@staticmethod
def save_str_list(write_path, info_list, mode='w'):
    """
        save a list of info to a file
        :param write_path: string
        :param info_list: a list of info to save
        :param mode: file mode
        :return:
        """
    with open(write_path, mode) as file:
        for info in info_list:
            file.write(str(info))


def d_x_diffr_dx(x, y):
    """
    derivative of d(x/r)/dx
    equivalent to second order derivatives dr_dxx

    :param x:
    :param y:
    :return:
    """
    return y ** 2 / (x ** 2 + y ** 2) ** (3 / 2.0)


@staticmethod
def compress(tensor):
    """Returns the tensor unmodified."""
    return tensor, None


@classmethod
def expand_tags(cls, elem, tags):
    """Keep <elem></elem> instead of shortening to <elem/>"""
    if elem.tag in tags and elem.text is None:
        elem.text = ''
    for c in elem:
        cls.expand_tags(c, tags)


def iterbytes(bs):
    """
    >>> list(iterbytes(b'hello'))
    [b'h', b'e', b'l', b'l', b'o']
    """
    for b in bs:
        yield bytes((b,))


def to_str(value):
    """
    A wrapper over str(), but converts bool values to lower case strings.
    If None is given, just returns None, instead of converting it to string "None".
    """
    if isinstance(value, bool):
        return str(value).lower()
    elif value is None:
        return value
    else:
        return str(value)


@classmethod
def from_instrument(cls, instr_name):
    """
        Obtain an instrumental background spectrum corresponding
        to a registered instrument.

        Parameters
        ----------
        instr_name : string
            Name of the instrument in the instrument registry.
        """
    from soxs.instrument_registry import instrument_registry
    from soxs.background.instrument import instrument_backgrounds
    instr = instrument_registry[instr_name]
    return instrument_backgrounds[instr['bkgnd']]


def svn_basename(url):
    """
    Get basename from an SVN url
    """
    words = url.split('//')
    try:
        words = words[1].split('/')
        return '/'.join(words[1:])
    except IndexError:
        return None


def fromSuccessResponse(cls, success_response):
    """Create a C{L{Response}} object from a successful OpenID
        library response
        (C{L{openid.consumer.consumer.SuccessResponse}}) response
        message

        @param success_response: A SuccessResponse from consumer.complete()
        @type success_response: C{L{openid.consumer.consumer.SuccessResponse}}

        @rtype: Response or None
        @returns: A provider authentication policy response from the
            data that was supplied with the C{id_res} response or None
            if the provider sent no signed PAPE response arguments.
        """
    self = cls()
    args = success_response.getSignedNS(self.ns_uri)
    if args is not None:
        self.parseExtensionArgs(args)
        return self
    else:
        return None


@staticmethod
def supportedViews():
    """Return the views that this control supports.

        This method may be overridden by sub-classes to return a list of
        the view types that are supported by this control. For example, the
        :class:`.OrthoToolBar` control is intended to be used solely with the
        :class:`.OrthoPanel` view.

        The default implementation returns ``None``, which is interpreted
        as being compatible with all views.
        """
    return None


def get_time_units(time_amount):
    """
    Get a nomralized length of time in the largest unit of time (hours,
    minutes, or seconds.)

    :param time_amount: length of time in seconds
    :returns: A touple of (length of time, unit of time) where unit of time is
              one of ('h', 'm', 's')
    """
    time_unit = 's'
    if time_amount > 60:
        time_amount /= 60
        time_unit = 'm'
        if time_amount > 60:
            time_amount /= 60
            time_unit = 'h'
    return time_amount, time_unit


@classmethod
def _shared_key(cls, *args, **kwargs):
    """
        Given the constructor arguments, returns an immutable key representing
        the instance. The default simply assumes all positional arguments are
        immutable.
        """
    return args


@classmethod
def accepts_default_mpiprocs_per_machine(cls):
    """
        Return True if this JobResource accepts a 'default_mpiprocs_per_machine'
        key, False otherwise.
        """
    return False


def split_command_line(command_line):
    """This splits a command line into a list of arguments. It splits arguments
    on spaces, but handles embedded quotes, doublequotes, and escaped
    characters. It's impossible to do this with a regular expression, so I
    wrote a little state machine to parse the command line. """
    arg_list = []
    arg = ''
    state_basic = 0
    state_esc = 1
    state_singlequote = 2
    state_doublequote = 3
    state_whitespace = 4
    state = state_basic
    for c in command_line:
        if state == state_basic or state == state_whitespace:
            if c == '\\':
                state = state_esc
            elif c == "'":
                state = state_singlequote
            elif c == '"':
                state = state_doublequote
            elif c.isspace():
                if state == state_whitespace:
                    None
                else:
                    arg_list.append(arg)
                    arg = ''
                    state = state_whitespace
            else:
                arg = arg + c
                state = state_basic
        elif state == state_esc:
            arg = arg + c
            state = state_basic
        elif state == state_singlequote:
            if c == "'":
                state = state_basic
            else:
                arg = arg + c
        elif state == state_doublequote:
            if c == '"':
                state = state_basic
            else:
                arg = arg + c
    if arg != '':
        arg_list.append(arg)
    return arg_list


def write_to_file(bib, outfile):
    """
    Write bibliography to file.
    :param bib: Bibliography in pybtex format.
    :param outfile: Path of output file.
    """
    bib.to_file(outfile, bib_format='bibtex')


def svg(filepath: str='', filter_glob: str='*.svg'):
    """Load a SVG file

    :param filepath: File Path, Filepath used for importing the file
    :type filepath: str
    :param filter_glob: filter_glob
    :type filter_glob: str
    """
    pass


def run_xz_anisotropy_calculations(resolution=10, submit=True):
    """
    Perform static calculations with the magnetic axis along
    several directions between 100 and 001.

    Kwargs:
        resolution (int): step size between axes. The total
            number of calculations will be 90 / `resolution`.
        submit (bool): Whether or not to submit the job.
    """


def check_harmony(tone, harmony_steps, basic_scale):
    """checks if harmony is buildable on current tone with current scale"""
    harmony_ok = True
    for harmony_step in harmony_steps:
        next_tone = (tone + harmony_step) % 12
        if basic_scale[next_tone] == 1:
            tone += harmony_step
        else:
            harmony_ok = False
            break
    return harmony_ok


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

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

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


def delete_nat_gateway(NatGatewayId=None):
    """
    Deletes the specified NAT gateway. Deleting a NAT gateway disassociates its Elastic IP address, but does not release the address from your account. Deleting a NAT gateway does not delete any NAT gateway routes in your route tables.
    See also: AWS API Documentation

    Examples
    This example deletes the specified NAT gateway.
    Expected Output:

    :example: response = client.delete_nat_gateway(
        NatGatewayId='string'
    )

    :type NatGatewayId: string
    :param NatGatewayId: [REQUIRED]
            The ID of the NAT gateway.

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

    """
    pass


@classmethod
def from_PF_filename(cls, filename):
    """create a T1File instance from PFA or PFB font file of given name"""
    with open(filename, 'rb') as file:
        t1file = cls.from_PF_bytes(file.read())
    return t1file


@classmethod
def factory(cls, table_map):
    """ Provide a protocol factory for a given map instance.
        """
    return lambda : cls(table_map)


def countOf(a, b):
    """Return the number of times b occurs in a."""
    count = 0
    for i in a:
        if i == b:
            count += 1
    return count


def hexbyte_2integer_normalizer(first_int_byte, second_int_btye):
    """Function to normalize integer bytes to a single byte

    Transform two integer bytes to their hex byte values and normalize
    their values to a single integer

    Parameters
    __________
    first_int_byte, second_int_byte : int
        integer values to normalize (0 to 255)

    Returns
    _______
    integer: int
        Single normalized integer
    """
    first_hex = f'{hex(first_int_byte)}'.lstrip('0x')
    second_hex = f'{hex(second_int_btye)}'.lstrip('0x')
    first_hex = first_hex if len(f'{first_hex}') == 2 else f'0{first_hex}'
    second_hex = second_hex if len(f'{second_hex}') == 2 else f'0{second_hex}'
    hex_string = f'{first_hex}{second_hex}'
    integer = int(hex_string, 16)
    return integer


def format_str(text):
    """
    Format some strings.

    This function replacing invalid chars in xml file.
    ex. RSS does't accept C{&} char so it should be replaced to C{&}

    @param text: Text to formating
    @type text: str
    @return: formated text
    @rtype: str
    """
    return text.replace('&', '&')


def _tr_magic(content):
    """Translate lines escaped with a percent sign: %"""
    name, _, args = content.partition(' ')
    return 'get_ipython().run_line_magic(%r, %r)' % (name, args)


def start_of_chunk(prev_tag, tag, prev_type, type_):
    """Checks if a chunk started between the previous and current word.

    Args:
        prev_tag: previous chunk tag.
        tag: current chunk tag.
        prev_type: previous type.
        type_: current type.

    Returns:
        chunk_start: boolean.
    """
    chunk_start = False
    if tag == 'B':
        chunk_start = True
    if tag == 'S':
        chunk_start = True
    if prev_tag == 'E' and tag == 'E':
        chunk_start = True
    if prev_tag == 'E' and tag == 'I':
        chunk_start = True
    if prev_tag == 'S' and tag == 'E':
        chunk_start = True
    if prev_tag == 'S' and tag == 'I':
        chunk_start = True
    if prev_tag == 'O' and tag == 'E':
        chunk_start = True
    if prev_tag == 'O' and tag == 'I':
        chunk_start = True
    if tag != 'O' and tag != '.' and prev_type != type_:
        chunk_start = True
    return chunk_start


def select_more():
    """Select more strips adjacent to the current selection

    """
    pass


def context_cycle_array(data_path: str='', reverse: bool=False):
    """Set a context array value (useful for cycling the active mesh edit mode)

    :param data_path: Context Attributes, RNA context string
    :type data_path: str
    :param reverse: Reverse, Cycle backwards
    :type reverse: bool
    """
    pass


def int_or_str(text):
    """Helper function for argument parsing."""
    try:
        return int(text)
    except ValueError:
        return text


def arctan(attrs, inputs, proto_obj):
    """Elementwise inverse tan of input array."""
    return 'arctan', attrs, inputs


@classmethod
def iter_session_classes_issues(cls):
    """Yield (Interface Type, Resource Class), Issues class pair for
        invalid sessions classes (i.e. those with import errors).
        """
    for key, val in cls._session_classes.items():
        try:
            yield key, getattr(val, 'session_issue')
        except AttributeError:
            pass


def start():
    """
        Start the remote batch process if it has not yet been started, otherwise
        do nothing.
        """


@classmethod
def increment(cls, metric_name, value=1, tags=None, **kwargs):
    """
        Increment a metric_name value (all the increments and decrements within
        a given minute are summed together).

        Args:
            metric_name (str): name of the metric to be incremented
            value (int or float): how much to increment the metric value
            tags (list or dict): miscellaneous tags to describe the value
        """
    cls.stats().increment(cls.get_metric_name(metric_name), value=value,
        tags=cls._convert_tags(tags), **kwargs)


def slope(p1, p2):
    """Returns the slope of the line from p1 to p2."""
    return float(p2[1] - p1[1]) / (p2[0] - p1[0])


def exception(__self, __message, *args, **kwargs):
    """Convenience method for logging an ``'ERROR'`` with exception information."""
    options = (True,) + __self._options[1:]
    __self._log('ERROR', None, False, options, __message, args, kwargs)


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

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

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


@staticmethod
def add_implicit_task_dep(targets, task, deps_list):
    """add implicit task_dep for `task` for newly added `file_dep`

        @param targets: (dict) fileName -> task_name
        @param task: (Task) task with newly added file_dep
        @param dep_list: (list - str): list of file_dep for task
        """
    for dep in deps_list:
        if dep in targets and targets[dep] not in task.task_dep:
            task.task_dep.append(targets[dep])


def _tex_comment(comment):
    """Prepends each line in string with the LaTeX comment key, '%'.
    """
    return '% ' + str.replace(comment, '\n', '\n% ') + '\n'


def para(conteudo='', classe='', Identificador=''):
    """Retorna um paragrafo para o codigo que o chamou"""
    return "
%s
" % (str(classe), str(Identificador
        ), str(conteudo))


@classmethod
def RenderLoadedAdd(cls, obj):
    """render loaded add"""
    raise 'not implemented'


def write_jcamp_pair(f, key, value):
    """
    Write out a line of a JCAMP file.

    a line might actually be more than one line of text for arrays.
    """
    line = '##$' + key + '= '
    if type(value) == float or type(value) == int:
        line = line + repr(value)
    elif isinstance(value, str):
        line = line + '<' + value + '>'
    elif type(value) == bool:
        if value:
            line = line + 'yes'
        else:
            line = line + 'no'
    elif isinstance(value, list):
        line = line + '(0..' + repr(len(value) - 1) + ')'
        f.write(line)
        f.write('\n')
        line = ''
        for v in value:
            if len(line) > 70:
                f.write(line)
                f.write('\n')
                line = ''
            if isinstance(v, str):
                to_add = '<' + v + '>'
            else:
                to_add = repr(v)
            if len(line + ' ' + to_add) > 80:
                f.write(line)
                f.write('\n')
                line = ''
            if line != '':
                line = line + to_add + ' '
            else:
                line = to_add + ' '
    f.write(line)
    f.write('\n')
    return


def escape_quotes(s: str) ->str:
    """Replaces double quotes in the input string with either ' or \\".

    Description:
        Given a string, returns that string with double quotes escaped in one of two ways.
        If the string contains single quotes, then \\" will be used to escape the double quotes.
        Otherwise, a single quote (') will be used instead.

    Examples:
        >>> escape_quotes('one "two" three')
        "one 'two' three"
        >>> escape_quotes('"He said he didn\\'t know."')
        '\\\\"He said he didn\\'t know.\\\\"'
    """
    if "'" in s:
        return s.replace('"', '\\"')
    return s.replace('"', "'")


def context_set_int(data_path: str='', value: int=0, relative: bool=False):
    """Set a context value

    :param data_path: Context Attributes, RNA context string
    :type data_path: str
    :param value: Value, Assign value
    :type value: int
    :param relative: Relative, Apply relative to the current value (delta)
    :type relative: bool
    """
    pass


def reset():
    """
    After everything has been closed, reset the array
    """
    global GARBAGE
    GARBAGE = []


def extract_favicon(bs4):
    """Extracting favicon url from BeautifulSoup object

    :param bs4: `BeautifulSoup`
    :return: `list` List of favicon urls
    """
    favicon = []
    selectors = ['link[rel="icon"]', 'link[rel="Icon"]', 'link[rel="ICON"]',
        'link[rel^="shortcut"]', 'link[rel^="Shortcut"]',
        'link[rel^="SHORTCUT"]']
    for selector in selectors:
        icons = bs4.select(selector)
        if icons:
            for icon in icons:
                if icon.has_attr('href'):
                    favicon.append(icon['href'])
    return favicon


def every_other(iterable):
    """
    Yield every other item from the iterable

    >>> ' '.join(every_other('abcdefg'))
    'a c e g'
    """
    items = iter(iterable)
    while True:
        try:
            yield next(items)
            next(items)
        except StopIteration:
            return


def lineAtPos(s, pos):
    """
	lineAtPos: return the line of a string containing the given index.
	s		a string
	pos		an index into s
	"""
    if len(s) < 1:
        return ''
    if pos > len(s):
        pos = len(s) - 1
    while pos > 0:
        if s[pos] == '\n':
            pos = pos + 1
            break
        else:
            pos = pos - 1
    s = s[pos:]
    list = s.split('\n')
    return list[0]


def lock_layer():
    """Lock and hide any color not used in any layer

    """
    pass


def end_frame_set():
    """Set the current frame as the preview or scene end frame

    """
    pass


@classmethod
def parse(cls, name, data_size, reader, parsers):
    """given a 4 byte name, data_size int, BitstreamReader
        and dict of {"atom":handler} sub-parsers,
        returns an atom of this class"""
    version, flags, byte_size = reader.parse('8u 24u 32u')
    return cls(version=version, flags=flags, byte_size=byte_size,
        block_sizes=[reader.read(32) for i in range(reader.read(32))])


def _get_pad_left_right(small, large):
    """ Compute left and right padding values.

    Here we use the convention that if the padding
    size is odd, we pad the odd part to the right
    and the even part to the left.

    Parameters
    ----------
    small : int
        Old size of original 1D array
    large : int
        New size off padded 1D array

    Returns
    -------
    (padleft, padright) : tuple
        The proposed padding sizes.
    """
    assert small < large, 'Can only pad when new size larger than old size'
    padsize = large - small
    if padsize % 2 != 0:
        leftpad = (padsize - 1) / 2
    else:
        leftpad = padsize / 2
    rightpad = padsize - leftpad
    return int(leftpad), int(rightpad)


@classmethod
def empty_value(cls, mark_name):
    """The fix for a mark with a empty_value

        Args:
            mark_name (str): the name of the mark to add

        Returns:
            str: the complete pytest mark to be added
        """
    return '@pytest.mark.{}()\n'.format(mark_name)


@staticmethod
def header_info():
    """Return a list of elements that should be added to the VCF header so:

    vcf_in.header.info.add(*mp.header_info())
    """
    return 'MAP', 1, 'Float', 'Mappability at variant location'


def get_account_id(context):
    """
    Return the AWS account id for the executing lambda function

    Args:
        context: AWS lambda Context Object http://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html

    Returns:
        str : AWS Account ID

    """
    return str(context.invoked_function_arn.split(':')[4])


@classmethod
def strip_off_start(cls, s: str, pre: str):
    """
		Strips the full string `pre` from the start of `str`.
		See `Tools.strip_off` for more info.
		"""
    assert isinstance(pre, str), '{} is not a string'.format(pre)
    if s.startswith(pre):
        s = s[len(pre):]
    return s


@staticmethod
def check_for_export(context, volume_id):
    """Make sure volume is exported.

        :param context: the context
        :param volume_id: the volume id
        """
    pass


def logical_not(data=None, name=None, attr=None, out=None, **kwargs):
    """Returns the result of logical NOT (!) function

    Example:
      logical_not([-2., 0., 1.]) = [0., 1., 0.]

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

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

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


def compareLayers(layer1, layer2):
    """
    Helper function to compare two layers. The layer with the lower id is considered to be before
    the other layer. This method is used when setting layers visible.
    """
    if layer1.id < layer2.id:
        return -1
    elif layer1.id == layer2.id:
        return 0
    else:
        return 1


def bool_from_env_string(string: str) ->bool:
    """Convert a string recieved from an environment variable into a
    bool.

    'true', 'TRUE', 'TrUe', 1, '1' =  True

    Everything else is False.

    :param string:  The string to convert to a bool.

    """
    if str(string).lower() == 'false' or str(string) == '':
        return False
    if str(string).lower() == 'true':
        return True
    try:
        int_value = int(string)
        if int_value == 1:
            return True
        else:
            return False
    except:
        return False


def __gt__(i1, i2):
    """ Test if i1.inf > i2.sup
        """
    return i1.inf > i2.sup


def parse_key_val_list(input_list):
    """
     Takes list of keyword value strings (seperated by =) and returns a dictionary with those keys and values
     **NOTE** if a key has no value, the key is stored and given the value True

    :param input_list: A list of strings which are keyword value pairs separated by =
    :return: A dictionary of the keywords and values
    """
    key_val_dict = {}
    for element in input_list:
        key_value = element.split('=')
        key = key_value[0]
        value = key_value[1] if len(key_value) > 1 else True
        key_val_dict[key] = value
    return key_val_dict


def _thumbnail_path_to_url(path):
    """
    Convert a local thumbnail path (string) to an absolute URL using the GitHub
    repository location detected using `get_continuous_integration_parameters`.
    """
    if not path:
        return None
    from .ci import get_continuous_integration_parameters
    info = get_continuous_integration_parameters()
    try:
        url = (
            f"https://github.com/{info['repo_slug']}/raw/{info['triggering_commit']}/{path}"
            )
    except (TypeError, KeyError):
        return None
    return url


def powint(xlow, xhigh, ylow, yhigh, xval, power):
    """Power-based interpolator
    :param xlow: x lower interval
    :param xhigh: x upper interval
    :param ylow: y lower interval
    :param yhigh: y upper interval
    :param xval: value on x
    :param power: power for interpolation
    :return: TODO
    """
    EPSLON = 1e-20
    if xhigh - xlow < EPSLON:
        powint = (yhigh + ylow) / 2.0
    else:
        powint = ylow + (yhigh - ylow) * ((xval - xlow) / (xhigh - xlow)
            ) ** power
    return powint


def _find_extension(pth):
    """
    Find the first HEALPIX extension in a fits file,
    and return the extension number. Else, raise an IndexError
    """
    for i, hdu in enumerate(pth):
        if hdu.header.get('PIXTYPE') == 'HEALPIX':
            return i
    else:
        raise IndexError('No HEALPIX extensions found in %s' % pth.filename())


def _get_input(layer, index=0):
    """
    :param layer : NN Layer Proto message
    :param index : Layer input index (Default 0)
    :returns name of input at provided index if present, otherwise None
    """
    if len(layer.input) <= index:
        return None
    return layer.input[index]


def is_rgb(in_col):
    """
	Check whether input is a valid RGB color.
	Return True if it is, otherwise False.
	"""
    if len(in_col) == 3 and type(in_col) == tuple:
        if type(in_col[0]) is int and type(in_col[1]) and type(in_col[2]
            ) and 0 <= in_col[0] <= 255 and 0 <= in_col[1
            ] <= 255 and 0 <= in_col[2] <= 255:
            return True
        else:
            return False
    else:
        return False


def batch_qs(qs, batch_size=10000):
    """
    Returns a (start, end, total, queryset) tuple for each batch in the given
    queryset.

    Usage:
        # Make sure to order your querset
        article_qs = Article.objects.order_by('id')
        for start, end, total, qs in batch_qs(article_qs):
            print "Now processing %s - %s of %s" % (start + 1, end, total)
            for article in qs:
                print article.body
    """
    total = qs.count()
    for start in range(0, total, batch_size):
        end = min(start + batch_size, total)
        yield start, end, total, qs[start:end]


def to_ascii(s):
    """ Force string to ascii
    :param s:
    :return:
    """
    s = s.split(b'\x00', 1)[0]
    return s.decode('ascii', 'ignore').lower()


def validate_ternary(setting, value, option_parser, config_parser=None,
    config_section=None):
    """Check/normalize three-value settings:
         True:  '1', 'on', 'yes', 'true'
         False: '0', 'off', 'no','false', ''
         any other value: returned as-is.
    """
    if isinstance(value, bool) or value is None:
        return value
    try:
        return option_parser.booleans[value.strip().lower()]
    except KeyError:
        return value


@classmethod
def _convert_to_fill(cls, fill_dict):
    """
        Convert ``fill_dict`` to an openpyxl v2 Fill object.

        Parameters
        ----------
        fill_dict : dict
            A dict with one or more of the following keys (or their synonyms),
                'fill_type' ('patternType', 'patterntype')
                'start_color' ('fgColor', 'fgcolor')
                'end_color' ('bgColor', 'bgcolor')
            or one or more of the following keys (or their synonyms).
                'type' ('fill_type')
                'degree'
                'left'
                'right'
                'top'
                'bottom'
                'stop'

        Returns
        -------
        fill : openpyxl.styles.Fill
        """
    from openpyxl.styles import PatternFill, GradientFill
    _pattern_fill_key_map = {'patternType': 'fill_type', 'patterntype':
        'fill_type', 'fgColor': 'start_color', 'fgcolor': 'start_color',
        'bgColor': 'end_color', 'bgcolor': 'end_color'}
    _gradient_fill_key_map = {'fill_type': 'type'}
    pfill_kwargs = {}
    gfill_kwargs = {}
    for k, v in fill_dict.items():
        pk = gk = None
        if k in _pattern_fill_key_map:
            pk = _pattern_fill_key_map[k]
        if k in _gradient_fill_key_map:
            gk = _gradient_fill_key_map[k]
        if pk in ['start_color', 'end_color']:
            v = cls._convert_to_color(v)
        if gk == 'stop':
            v = cls._convert_to_stop(v)
        if pk:
            pfill_kwargs[pk] = v
        elif gk:
            gfill_kwargs[gk] = v
        else:
            pfill_kwargs[k] = v
            gfill_kwargs[k] = v
    try:
        return PatternFill(**pfill_kwargs)
    except TypeError:
        return GradientFill(**gfill_kwargs)


def sort_by_contact_callback(contact):
    """sort by contact name"""
    return '{0} {1}'.format(contact.lastname, contact.firstname).upper()


def getQueriables():
    """Return an iterable of objects that can be queried

        The returned obects should be two-tuples with:

        - A unicode id

          The id must uniquely identify the queriable object within
          the set of queriable objects. Furthermore, in subsequent
          calls, the same id should be used for a given queriable
          object.

        - A queriable object

          This is an object for which there is a view provided for
          searching for items.

        """


def __getitem__(name):
    """Return the named subclass"""


@staticmethod
def capture_request():
    """
        Get a transaction capture :class:`paynlsdk2.api.transaction.capture.Request` instance

        :return: Transaction capture request instance
        :rtype: paynlsdk2.api.transaction.capture.Request
        """
    from paynlsdk2.api.transaction.capture import Request
    return Request()


def parent_set():
    """Set the mask’s parenting

    """
    pass


@classmethod
def fromParser(cls, arguments):
    """
        Builds an Intent, given arguments parsed by an ArgumentParser that was
        previously initialised with addArgumentsTo().
        """
    return cls(action=arguments.action, category=arguments.category,
        component=arguments.component, data_uri=arguments.data_uri, extras=
        arguments.extras, flags=arguments.flags, mimetype=arguments.mimetype)


def p_boolean_primary_predicate(p):
    """boolean_primary : predicate"""
    p[0] = 'predicate', p[1]


@classmethod
def filter_field(cls):
    """Return a field that can be used as a unique key for this Resource.

        :returns: A field that can be used as a unique key.
        :rtype: str
        """
    if cls._filter_field is None:
        with cls._filter_field_lock:
            if cls._filter_field is None:
                cls._filter_field = cls._schema().filterable_key()
    return cls._filter_field


def supported_versions():
    """Return the list of file format versions supported by h5features."""
    return ['0.1', '1.0', '1.1']


def gemv_c_code(y, A, x, z, alpha, beta, fail, force_init_beta=False,
    params=None):
    """
    z <- beta * y + alpha * dot(A, x)

    where A is a matrix, y and x are vectors (ergo z is vector)
    """
    code = """

    int elemsize;
    float fbeta;
    double dbeta;

    if (PyArray_DIMS(%(A)s)[0] != PyArray_DIMS(%(y)s)[0])
    {
        PyErr_SetString(PyExc_ValueError,
                        "Shape mismatch: A.shape[0] != y.shape[0]");
        %(fail)s;
    }
    if (PyArray_DIMS(%(A)s)[1] != PyArray_DIMS(%(x)s)[0])
    {
        PyErr_SetString(PyExc_ValueError,
                        "Shape mismatch: A.shape[1] != x.shape[0]");
        %(fail)s;
    }

    if  (PyArray_DESCR(%(y)s)->type_num == NPY_DOUBLE) { elemsize = 8; }
    else if (PyArray_DESCR(%(y)s)->type_num == NPY_FLOAT) { elemsize = 4;}
    else {
        PyErr_SetString(PyExc_NotImplementedError, "complex Gemv");
        %(fail)s;
    }

    fbeta = dbeta = ((dtype_%(beta)s*)PyArray_DATA(%(beta)s))[0];

    // copy y if not destructive
    if (!%(params)s->inplace)
    {
        if ((NULL == %(z)s)
            || (PyArray_DIMS(%(z)s)[0] != PyArray_DIMS(%(y)s)[0]))
        {
            Py_XDECREF(%(z)s);
            %(z)s = (PyArrayObject*)PyArray_SimpleNew(1,
                PyArray_DIMS(%(y)s), PyArray_TYPE(%(y)s));
            if(!%(z)s) {
                PyErr_SetString(PyExc_MemoryError,
                                "failed to alloc gemv output");
                %(fail)s
            }
        }
        if (dbeta != 0)
        {
            if (PyArray_CopyInto(%(z)s, %(y)s) != 0) {
                %(fail)s
            }
        }
        else if (%(force_init_beta)d)
        {
            PyObject *zero = PyFloat_FromDouble(0.);
            if (zero == NULL) %(fail)s;
            if (PyArray_FillWithScalar(%(z)s, zero) != 0) %(fail)s;
            Py_DECREF(zero);
        }
    }
    else
    {
        if (%(z)s != %(y)s)
        {
            Py_XDECREF(%(z)s);
            %(z)s = %(y)s;
            Py_INCREF(%(z)s);
        }
    }
    {
        char TRANS = 'T';
        char NOTRANS = 'N';
        int NA0 = PyArray_DIMS(%(A)s)[0];
        int NA1 = PyArray_DIMS(%(A)s)[1];
        /* This formula is needed in the case where A is actually a row or
         * column matrix, because BLAS sometimes insists that the strides:
         *  - are not smaller than the number of elements in the array
         *  - are not 0.
         */
        int SA0 = (NA0 > 1) ? (PyArray_STRIDES(%(A)s)[0] / elemsize) : (NA1 + 1);
        int SA1 = (NA1 > 1) ? (PyArray_STRIDES(%(A)s)[1] / elemsize) : (NA0 + 1);
        int Sz = PyArray_STRIDES(%(z)s)[0] / elemsize;
        int Sx = PyArray_STRIDES(%(x)s)[0] / elemsize;

        dtype_%(x)s* x_data = (dtype_%(x)s*) PyArray_DATA(%(x)s);
        dtype_%(z)s* z_data = (dtype_%(z)s*) PyArray_DATA(%(z)s);
        // gemv expects pointers to the beginning of memory arrays,
        // but numpy provides a pointer to the first element,
        // so when the stride is negative, we need to get the last one.
        if (Sx < 0)
            x_data += (NA1 - 1) * Sx;
        if (Sz < 0)
            z_data += (NA0 - 1) * Sz;

        if (NA0 * NA1)
        {
            // If A is neither C- nor F-contiguous, we make a copy.
            // TODO:
            // - if one stride is equal to "- elemsize", we can still call
            //   gemv on reversed matrix and vectors
            // - if the copy is too long, maybe call vector/vector dot on
            //   each row instead
            if ((PyArray_STRIDES(%(A)s)[0] < 0)
                || (PyArray_STRIDES(%(A)s)[1] < 0)
                || ((PyArray_STRIDES(%(A)s)[0] != elemsize)
                    && (PyArray_STRIDES(%(A)s)[1] != elemsize)))
            {
                npy_intp dims[2];
                dims[0] = NA0;
                dims[1] = NA1;

                PyArrayObject * A_copy = (PyArrayObject *) PyArray_Copy(
                                                                   %(A)s);
                if (!A_copy)
                    %(fail)s
                Py_XDECREF(%(A)s);
                %(A)s = A_copy;
                SA0 = (NA0 > 1) ? (PyArray_STRIDES(%(A)s)[0] / elemsize) : (NA1 + 1);
                SA1 = (NA1 > 1) ? (PyArray_STRIDES(%(A)s)[1] / elemsize) : (NA0 + 1);
            }

            if (PyArray_STRIDES(%(A)s)[0] == elemsize)
            {
                if (PyArray_DESCR(%(A)s)->type_num == NPY_FLOAT)
                {
                    float alpha = ((dtype_%(alpha)s*)PyArray_DATA(%(alpha)s))[0];
                    sgemv_(&NOTRANS, &NA0, &NA1,
                        &alpha,
                        (float*)(PyArray_DATA(%(A)s)), &SA1,
                        (float*)x_data, &Sx,
                        &fbeta,
                        (float*)z_data, &Sz);
                }
                else if (PyArray_DESCR(%(A)s)->type_num == NPY_DOUBLE)
                {
                    double alpha = ((dtype_%(alpha)s*)PyArray_DATA(%(alpha)s))[0];
                    dgemv_(&NOTRANS, &NA0, &NA1,
                        &alpha,
                        (double*)(PyArray_DATA(%(A)s)), &SA1,
                        (double*)x_data, &Sx,
                        &dbeta,
                        (double*)z_data, &Sz);
                }
                else
                {
                    PyErr_SetString(PyExc_AssertionError,
                                    "neither float nor double dtype");
                    %(fail)s
                }
            }
            else if (PyArray_STRIDES(%(A)s)[1] == elemsize)
            {
                if (PyArray_DESCR(%(A)s)->type_num == NPY_FLOAT)
                {
                    float alpha = ((dtype_%(alpha)s*)PyArray_DATA(%(alpha)s))[0];

                    // Check for vector-vector dot (NA0 == 1). The code may work
                    // for SA1 != 1 as well, but has not been tested for this case,
                    // so SA1 == 1 is required for safety.
                    if (NA0 == 1 && SA1 == 1)
                    {
                        if (fbeta != 0.f) {
                          z_data[0] = fbeta*z_data[0];
                        } else {
                          z_data[0] = 0.f;
                        }
                        z_data[0] += alpha*sdot_(&NA1,
                              (float*)(PyArray_DATA(%(A)s)), &SA1,
                              (float*)x_data, &Sx);
                    }
                    else
                    {
                        sgemv_(&TRANS, &NA1, &NA0,
                            &alpha,
                            (float*)(PyArray_DATA(%(A)s)), &SA0,
                            (float*)x_data, &Sx,
                            &fbeta,
                            (float*)z_data, &Sz);
                    }
                }
                else if (PyArray_DESCR(%(A)s)->type_num == NPY_DOUBLE)
                {
                    double alpha = ((dtype_%(alpha)s*)PyArray_DATA(%(alpha)s))[0];

                    // Check for vector-vector dot (NA0 == 1). The code may work
                    // for SA1 != 1 as well, but has not been tested for this case,
                    // so SA1 == 1 is required for safety.
                    if (NA0 == 1 && SA1 == 1)
                    {
                        if (dbeta != 0.) {
                          z_data[0] = dbeta*z_data[0];
                        } else {
                          z_data[0] = 0.;
                        }
                        z_data[0] += alpha*ddot_(&NA1,
                              (double*)(PyArray_DATA(%(A)s)), &SA1,
                              (double*)x_data, &Sx);
                    }
                    else
                    {
                        dgemv_(&TRANS, &NA1, &NA0,
                            &alpha,
                            (double*)(PyArray_DATA(%(A)s)), &SA0,
                            (double*)x_data, &Sx,
                            &dbeta,
                            (double*)z_data, &Sz);
                    }
                }
                else
                {
                    PyErr_SetString(PyExc_AssertionError,
                                    "neither float nor double dtype");
                    %(fail)s
                }
            }
            else
            {
                PyErr_SetString(PyExc_AssertionError,
                    "xx is a double-strided matrix, and should have been "
                    "copied into a memory-contiguous one.");
                %(fail)s
            }
        }
        else if (dbeta != 1.0)
        {
            // the matrix has at least one dim of length 0
            // so we do this loop, which either iterates over 0 elements
            // or else it does the right thing for length-0 A.
            dtype_%(z)s * zptr = (dtype_%(z)s*)(PyArray_DATA(%(z)s));
            for (int i = 0; i < NA0; ++i)
            {
                zptr[i * Sz] = (dbeta == 0.0 ? 0.0 : zptr[i * Sz] * dbeta);
            }
        }
    }
    """
    return code % locals()


def results(name):
    """Return the results of the query

        The query view should use `name` as the prefix for its widgets.

        The value returned is an iterable.

        None may be returned to indicate that there are no results.
        """


def docs_drop_param(docstring):
    """Drop the first parameter description for a string representation of a docstring.

    Parameters
    ----------
    docstring : str
        Docstring to drop first parameter from.

    Returns
    -------
    str
        New docstring, with first parameter dropped.

    Notes
    -----
    This function assumes numpy docs standards.
    It also assumes the parameter description to be dropped is only 2 lines long.
    """
    sep = '----------\n'
    ind = docstring.find(sep) + len(sep)
    front, back = docstring[:ind], docstring[ind:]
    for loop in range(2):
        back = back[back.find('\n') + 1:]
    return front + back


def simple_sink(riter):
    """This just consumes the reads so that our filter chain is processed. Comes in useful in
  some cases when we just drop the reads off at the end of the pipeline

  :param riter:
  :return:
  """
    for r in riter:
        pass


@classmethod
def _test_boundaries(cls, value):
    """Test if value is within defined range for this object."""
    return cls.value_min <= value <= cls.value_max


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

    .. math::
       square(x) = x^2

    Example::

       square([2, 3, 4]) = [4, 9, 16]

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

       - square(default) = default
       - square(row_sparse) = row_sparse
       - square(csr) = csr

    Defined in src/operator/tensor/elemwise_unary_op_pow.cc:L118

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

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

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


def maybe_unroll_group(g):
    """Unroll group with only one member."""
    try:
        size = len(g.tasks)
    except TypeError:
        try:
            size = g.tasks.__length_hint__()
        except (AttributeError, TypeError):
            return g
        else:
            return list(g.tasks)[0] if size == 1 else g
    else:
        return g.tasks[0] if size == 1 else g


def __enter__():
    """Marks the instance as active.

        Should return self.
        """


def is_kernelspec_model(spec_dict):
    """Returns True if spec_dict is already in proper form.  This will occur when using a gateway."""
    return (isinstance(spec_dict, dict) and 'name' in spec_dict and 'spec' in
        spec_dict and 'resources' in spec_dict)


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


def list_presets(Ascending=None, PageToken=None):
    """
    The ListPresets operation gets a list of the default presets included with Elastic Transcoder and the presets that you've added in an AWS region.
    See also: AWS API Documentation

    :example: response = client.list_presets(
        Ascending='string',
        PageToken='string'
    )

    :type Ascending: string
    :param Ascending: To list presets in chronological order by the date and time that they were created, enter true . To list presets in reverse chronological order, enter false .

    :type PageToken: string
    :param PageToken: When Elastic Transcoder returns more than one page of results, use pageToken in subsequent GET requests to get each successive page of results.

    :rtype: dict
    :return: {
        'Presets': [
            {
                'Id': 'string',
                'Arn': 'string',
                'Name': 'string',
                'Description': 'string',
                'Container': 'string',
                'Audio': {
                    'Codec': 'string',
                    'SampleRate': 'string',
                    'BitRate': 'string',
                    'Channels': 'string',
                    'AudioPackingMode': 'string',
                    'CodecOptions': {
                        'Profile': 'string',
                        'BitDepth': 'string',
                        'BitOrder': 'string',
                        'Signed': 'string'
                    }
                },
                'Video': {
                    'Codec': 'string',
                    'CodecOptions': {
                        'string': 'string'
                    },
                    'KeyframesMaxDist': 'string',
                    'FixedGOP': 'string',
                    'BitRate': 'string',
                    'FrameRate': 'string',
                    'MaxFrameRate': 'string',
                    'Resolution': 'string',
                    'AspectRatio': 'string',
                    'MaxWidth': 'string',
                    'MaxHeight': 'string',
                    'DisplayAspectRatio': 'string',
                    'SizingPolicy': 'string',
                    'PaddingPolicy': 'string',
                    'Watermarks': [
                        {
                            'Id': 'string',
                            'MaxWidth': 'string',
                            'MaxHeight': 'string',
                            'SizingPolicy': 'string',
                            'HorizontalAlign': 'string',
                            'HorizontalOffset': 'string',
                            'VerticalAlign': 'string',
                            'VerticalOffset': 'string',
                            'Opacity': 'string',
                            'Target': 'string'
                        },
                    ]
                },
                'Thumbnails': {
                    'Format': 'string',
                    'Interval': 'string',
                    'Resolution': 'string',
                    'AspectRatio': 'string',
                    'MaxWidth': 'string',
                    'MaxHeight': 'string',
                    'SizingPolicy': 'string',
                    'PaddingPolicy': 'string'
                },
                'Type': 'string'
            },
        ],
        'NextPageToken': 'string'
    }

    :returns:
    auto channel specified, with any input: Pass through up to eight input channels.
    0 channels specified, with any input: Audio omitted from the output.
    1 channel specified, with at least one input channel: Mono sound.
    2 channels specified, with any input: Two identical mono channels or stereo. For more information about tracks, see Audio:AudioPackingMode.

    """
    pass


def get_view_types():
    """Get all view types known to this registry.
        """


@classmethod
def database_name(cls):
    """ Get the database associated with this class. Meant to be overridden
        in subclasses. """
    return cls._schema.get('databaseName', None)


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 '+'


@staticmethod
def _get_artifacts(values):
    """Get artifacts from workflow values."""
    artifacts = []
    templates = values.get('templates')
    flow = values.get('flow')
    for template in templates:
        artifacts.extend(template.artifacts)
    for task in flow.tasks:
        args = task.arguments
        if not args:
            continue
        if not args.artifacts:
            continue
        artifacts.extend(args.artifacts)
    inputs = values.get('inputs')
    if inputs and inputs.artifacts:
        artifacts.extend(inputs.artifacts)
    outputs = values.get('outputs')
    if outputs and outputs.artifacts:
        artifacts.extend(outputs.artifacts)
    return artifacts


def total_grid_lines(major_scale, minor_scale, width, height, depth=0):
    """Given a width height and depth calculate the total grid lines that will fit in an area

    Args:
      width  (number): box  width
      height (number): box height
      depth  (number): box depth 0 for rectangle

    Returns:
      vector: direction of wr, ht, dt
    """
    return int(width / minor_scale), int(height / minor_scale), int(depth /
        minor_scale)


@staticmethod
def first_order_score(y, mean, scale, shape, skewness):
    """ GAS Exponential Update term using gradient only - native Python function

        Parameters
        ----------
        y : float
            datapoint for the time series

        mean : float
            location parameter for the Exponential distribution

        scale : float
            scale parameter for the Exponential distribution

        shape : float
            tail thickness parameter for the Exponential distribution

        skewness : float
            skewness parameter for the Exponential distribution

        Returns
        ----------
        - Score of the Exponential family
        """
    return 1 - mean * y


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

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


def _node_types_match(node, node_template):
    """
    Verifies whether input and output types of two nodes match. The first has fixed arities of
    the input type whereas the second is a template with variable arities.

    :param node: Node with fixed input types arities.
    :param node_template: A node template with variable arities.

    :return bool: True if the types of the nodes match.
    """
    if node.node_type[1] != node_template.out_type:
        return False
    in_types = node.node_type[0]
    template_types = node_template.type_arities
    if len(in_types) != len(template_types):
        return False
    for in_type_1, in_type_2 in zip(in_types, template_types):
        if in_type_1.name != in_type_2.prim_type:
            return False
        if not in_type_2.is_valid_arity(in_type_1.arity):
            return False
    return True


def W(ws):
    """
    c [w1 w2 ... wn]
    cfirst clast w
    """
    widths = {}
    while ws:
        t = ws.pop()
        if isinstance(t, list):
            c = ws.pop()
            for i, w in enumerate(t):
                widths[c + i] = w
        else:
            c2 = ws.pop()
            c1 = ws.pop()
            for c in range(c1, c2 + 1):
                widths[c] = t
    return widths


def deleteLocalRoles(obj, member_ids, reindex=True, recursive=False):
    """ Remove local roles of specified members from an object.

        o 'obj' is the object on which to remove the role.

        o 'member_ids' is a sequence of user IDs from which to remove the role.

        o If 'reindex' is True, then reindex the security-related attributes
          of the object and all subobjects.

        o if 'recursive' is True, recurse over all subobjects of 'object'.

        o Raise Unauthorized if the currently-authenticated member cannot
          assign 'member_role' on 'obj'.

        Permission:  Public
        """


def trunc_time(date):
    """
    Truncate an object of type DateTime with time to 00:00:00
    :param date: Date for truncate
    :return: Date truncated
    """
    return date.replace(hour=0, minute=0, second=0, microsecond=0)


def matches(line, query):
    """Both arguments must be of a type bytes"""
    return line == query or line.startswith(query + b' ')


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

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

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


@staticmethod
def get_elastic_mappings(es_major):
    """Get Elasticsearch mapping.

        :param es_major: major version of Elasticsearch, as string
        :returns:        dictionary with a key, 'items', with the mapping
        """
    mapping = """
        {
            "properties": {
                "text_analyzed": {
                  "type": "text",
                  "fielddata": true,
                  "index": true
                }
           }
        } """
    return {'items': mapping}


@classmethod
def first_or_create(cls, **attributes):
    """
        Get the first record matching the attributes or create it.

        :param attributes: The instance attributes
        :type attributes: dict

        :return: The new instance
        :rtype: Model
        """
    instance = cls.where(attributes).first()
    if instance is not None:
        return instance
    return cls.create(**attributes)


def set_misc(params):
    """Set any miscellaneous data associated with the object (contents,
        computed results, etc.)
        """


def scan_setup_py():
    """Validate the contents of setup.py against Versioneer's expectations."""
    found = set()
    setters = False
    errors = 0
    with open('setup.py', 'r') as f:
        for line in f.readlines():
            if 'import versioneer' in line:
                found.add('import')
            if 'versioneer.get_cmdclass()' in line:
                found.add('cmdclass')
            if 'versioneer.get_version()' in line:
                found.add('get_version')
            if 'versioneer.VCS' in line:
                setters = True
            if 'versioneer.versionfile_source' in line:
                setters = True
    if len(found) != 3:
        print('')
        print('Your setup.py appears to be missing some important items')
        print('(but I might be wrong). Please make sure it has something')
        print('roughly like the following:')
        print('')
        print(' import versioneer')
        print(' setup( version=versioneer.get_version(),')
        print('        cmdclass=versioneer.get_cmdclass(),  ...)')
        print('')
        errors += 1
    if setters:
        print("You should remove lines like 'versioneer.VCS = ' and")
        print("'versioneer.versionfile_source = ' . This configuration")
        print('now lives in setup.cfg, and should be removed from setup.py')
        print('')
        errors += 1
    return errors


def _merge_yaml(x, y):
    """Merge dictionary 'y' into 'x'.

    This transaction will overwrite existing data values in "y" with values
    from "x".
    """
    z = x.copy()
    z.update(y)
    return z


def str2tuple(tt):
    """
  Convert tagged token like 'fly/VB' into a tuple like ('fly', 'VB'). If no '/'
  is found, return (tt, None). If multiple '/' are found, ignore all but the
  last;  e.g., 'on/off/NN' results in ('on/off', 'NN')
  """
    token_tag = tt.rsplit('/', 1)
    assert token_tag[1] is not None
    return token_tag[0], token_tag[1].upper()


def build_relabel_dict(x):
    """Relabel the input ids to continuous ids that starts from zero.

    The new id follows the order of the given node id list.

    Parameters
    ----------
    x : list
      The input ids.

    Returns
    -------
    relabel_dict : dict
      Dict from old id to new id.
    """
    relabel_dict = {}
    for i, v in enumerate(x):
        relabel_dict[v] = i
    return relabel_dict


def __call__(value):
    """Convert the provided JSON value to a field value.
        """


def paste_if(head, args=None, closure='', args_separator='|'):
    """
    Paste only if argument exists, otherwise returns None.

    :param head: Text to be inserted before the argument
    :param args: Value to be inserted after the head, if the value is None, the title will not be shown
    :param closure: Text to be inserted after the argument
    :param args_separator: Character string to separate the results
    :return: a string or None
    """
    if isinstance(args, dict):
        raise Exception('Dictionary not accept in paste_if')
    elif isinstance(args, list):
        args_with_sep = ''
        for arg in args[0:len(args) - 1]:
            args_with_sep = args_with_sep + str(arg) + args_separator
        return head + args_with_sep + args[-1] + closure
    elif isinstance(args, str):
        return head + args + closure
    else:
        return None


def _test():
    """

    >>> a = NonZeroDimensionalComponent(dimension = 1, free_variables='x')
    >>> b = NonZeroDimensionalComponent(dimension = 1, free_variables='y')
    >>> c = {'z' : 4}
    >>> d = {'z' : 3}
    >>> e = ZeroDimensionalComponent([c, d])
    >>> f = utilities.MethodMappingList([a,b,e])
    >>> f.flatten()
    [{'z': 4}, {'z': 3}]
    >>> f.keys()[:-1]
    [NonZeroDimensionalComponent(dimension = 1, free_variables = 'x'), NonZeroDimensionalComponent(dimension = 1, free_variables = 'y')]
    >>> f.keys()[2].dimension
    0
    >>> set.union(*[set(keys) for keys in f.keys().flatten()]) == set('z')
    True
    """
    pass


def update_hit_review_status(HITId=None, Revert=None):
    """
    The UpdateHITReviewStatus operation updates the status of a HIT. If the status is Reviewable, this operation can update the status to Reviewing, or it can revert a Reviewing HIT back to the Reviewable status.
    See also: AWS API Documentation

    :example: response = client.update_hit_review_status(
        HITId='string',
        Revert=True|False
    )

    :type HITId: string
    :param HITId: [REQUIRED]
            The ID of the HIT to update.

    :type Revert: boolean
    :param Revert: Specifies how to update the HIT status. Default is False .
            Setting this to false will only transition a HIT from Reviewable to Reviewing
            Setting this to true will only transition a HIT from Reviewing to Reviewable

    :rtype: dict
    :return: {}

    :returns:
    (dict) --

    """
    pass


def histogram_to_point_data(values):
    """Transform histogram(s) to point data

    Parameters
    ----------
    values : :class:`~numpy:numpy.ndarray`
        Array with histogram data

    Returns
    -------
    :class:`~numpy:numpy.ndarray`
        Array with point data
    """
    if values.ndim == 1:
        return (values[1:] + values[:-1]) / 2.0
    else:
        return (values[:, 1:] + values[:, :-1]) / 2.0


def params_to_mongo(query_params):
    """Convert HTTP query params to mongodb query syntax.

    Converts the parse query params into a mongodb spec.

    :param dict query_params: return of func:`rest.process_params`
    """
    if not query_params:
        return {}
    for key, value in query_params.items():
        if isinstance(value, list):
            query_params[key] = {'$in': value}
    return query_params


def hidedot():
    """Toggle hide hidden dot files

    """
    pass


@staticmethod
def is_sdfile(string):
    """Test if input string is in ``SDfile`` format.

        :param string: Input string.
        :type string: :py:class:`str` or :py:class:`bytes`.
        :return: Input string if in ``SDfile`` format or False otherwise.
        :rtype: :py:class:`str` or :py:obj:`False`.
        """
    try:
        string = string.decode('utf-8')
    except AttributeError:
        pass
    if '$$$$\n' in string:
        return True
    return False


def enable_ANSI_colors():
    """
    Populates the global module dictionary `ansi` with ANSI escape sequences.
    """
    global _ansi
    color_order = ['black', 'red', 'green', 'yellow', 'blue', 'purple',
        'cyan', 'white']
    short_colors = {'black': 'k', 'red': 'r', 'green': 'g', 'yellow': 'y',
        'blue': 'b', 'purple': 'p', 'cyan': 'c', 'white': 'w'}
    _ansi = {'escape': '\x1b', 'reset': 0, '|': 0, 'boldon': 1, '!': 1,
        'italicson': 3, '/': 3, 'ulon': 4, '_': 4, 'invon': 7, 'boldoff':
        22, 'italicsoff': 23, 'uloff': 24, 'invoff': 27}
    for key in _ansi:
        if key != 'escape':
            _ansi[key] = '{0}[{1}m'.format(_ansi['escape'], _ansi[key])
    for index, color in enumerate(color_order):
        _ansi[color] = '{0}[{1}m'.format(_ansi['escape'], 30 + index)
        _ansi[color + 'f'] = _ansi[color]
        _ansi[short_colors[color] + 'f'] = _ansi[color + 'f']
    for index, color in enumerate(color_order):
        _ansi[color + 'b'] = '{0}[{1}m'.format(_ansi['escape'], 40 + index)
        _ansi[short_colors[color] + 'b'] = _ansi[color + 'b']
    _ansi['atexclimation'] = '@!'
    _ansi['atfwdslash'] = '@/'
    _ansi['atunderscore'] = '@_'
    _ansi['atbar'] = '@|'


def _heading_sort_order(msg_line):
    """
    Custom first (i.e. generic False first), then by message i.e. by title
    """
    custom = ' #### ' in msg_line[:10]
    return not custom, msg_line


def truncateWord64(value):
    """
    Truncate an unsigned integer to 64 bits.
    """
    return value & 18446744073709551615


def convert_segments(segment):
    """Converts a V3 segment parameter into an list with a V4 Segment object."""
    return [{'segmentId': segment}]


def dms2dd(d, m, s):
    """Convert degrees, minutes, seconds to decimal degrees
    """
    if d < 0:
        sign = -1
    else:
        sign = 1
    dd = sign * (int(abs(d)) + float(m) / 60 + float(s) / 3600)
    return dd


@staticmethod
def to_wikidata_group():
    """
        Get the portion of a SPARQL query in the GROUP BY clause.

        Returns (str):

        """
    return ''


@classmethod
def from_curve_map(cls, dt_valuation, curve_map):
    """Create market consisting of a map of curves.

        The map is a dictionary of dictionaries.
        The top level keys are currency strings.
        The next level are strings describing the curves in that currency.
        One curve key in each currency must be named 'discount'.
        The others are frequencies defined as an integer number of months.

        These 'frequency' curves are used to produce forward ibor rates,
        from pseudo-discount factors.
        """
    return cls(dt_valuation, curve_map)


def init(queue):
    """
    This is a wrapper script to be called by the 'multiprocessing.map' function
    to calculate the model functions in parallel.

    This function will be called upon initialization of the process.
    It sets a global variable denoting the ID of this process that can
    be read by any function of this process

    Parameters
    ----------
    queue : multiprocessing.Queue
             the queue object that manages the unique IDs of the process pool
    """
    global process_id
    process_id = queue.get()


def removeLeading(s, chars):
    """Remove all characters in chars from the front of s."""
    i = 0
    while i < len(s) and s[i] in chars:
        i += 1
    return s[i:]


@classmethod
def feature_log_list(cls, project_id, offset=None, limit=None):
    """ Retrieve the feature derivation log content and log length for a time series project.

        The Time Series Feature Log provides details about the feature generation process for a
        time series project. It includes information about which features are generated and their
        priority, as well as the detected properties of the time series data such as whether the
        series is stationary, and periodicities detected.

        This route is only supported for time series projects that have finished partitioning.

        The feature derivation log will include information about:

        * | Detected stationarity of the series:
          | e.g. 'Series detected as non-stationary'
        * | Detected presence of multiplicative trend in the series:
          | e.g. 'Multiplicative trend detected'
        * | Detected presence of multiplicative trend in the series:
          | e.g.  'Detected periodicities: 7 day'
        * | Maximum number of feature to be generated:
          | e.g. 'Maximum number of feature to be generated is 1440'
        * | Window sizes used in rolling statistics / lag extractors
          | e.g. 'The window sizes chosen to be: 2 months
          | (because the time step is 1 month and Feature Derivation Window is 2 months)'
        * | Features that are specified as known-in-advance
          | e.g. 'Variables treated as apriori: holiday'
        * | Details about why certain variables are transformed in the input data
          | e.g. 'Generating variable "y (log)" from "y" because multiplicative trend
          | is detected'
        * | Details about features generated as timeseries features, and their priority
          | e.g. 'Generating feature "date (actual)" from "date" (priority: 1)'

        Parameters
        ----------
        project_id : str
            project id to retrieve a feature derivation log for.
        offset : int
            optional, defaults is 0, this many results will be skipped.
        limit : int
            optional, defaults to 100, at most this many results are returned. To specify
        no limit, use 0. The default may change without notice.
        """
    url = 'projects/{}/timeSeriesFeatureLog/'.format(project_id)
    response = cls._client.get(url, params=dict(offset=offset, limit=limit))
    return response.json()


def from_python(value, state=None):
    """
        Convert `value` from its Python representation to the foreign
        representation.  `state` is for application-specific hooks.
        """


@classmethod
def Register5(cls, *args, **kwargs):
    """
`Register5(...)` is a shortcut for `RegisterAt(5, ...)`

**Also See**

* `phi.builder.Builder.RegisterAt`
* `phi.builder.Builder.RegisterMethod`
        """
    return cls.RegisterAt(5, *args, **kwargs)


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

    The ".dev0" means dirty.

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


def split_remote(ctx, param, value):
    """ Split remote/branch into tuple. """
    if value:
        try:
            remote, branch = value.split('/')
        except ValueError:
            remote, branch = value, None
        return remote, branch
    return value, value


@staticmethod
def set_solution_dirs_to_projects(projects_data, solution_folders_map,
    solution_folders):
    """ Evaluate locations of projects in Solution explorer tree of Visual Studio UI """
    for project_guid in projects_data:
        project_solution_dir = ''
        if project_guid in solution_folders_map:
            guid = project_guid
            while guid in solution_folders_map:
                if project_solution_dir:
                    project_solution_dir = '/' + project_solution_dir
                project_solution_dir = solution_folders[
                    solution_folders_map[guid]] + project_solution_dir
                guid = solution_folders_map[guid]
        projects_data[project_guid]['project_solution_dir'
            ] = project_solution_dir


def _analizar_valid(símismo):
    """
        Esta función procesa los resultados de la validación del modelo.

        :return: Un diccionario del análisis de la validación.
        :rtype: dict
        """
    raise NotImplementedError


def generate_inventory(inventory, to_stdout=False, tmp_dir=None):
    """
    Generates a host file to use with an ansible-playbook call.

    The first argument is a dictionary mapping that contains the group name as
    the key and a list of hostnames as values

    For example:

        {'mons': ['mon.host'], 'osds': ['osd1.host', 'osd1.host']}
    """
    result = []
    for section, hosts in inventory.items():
        group_name = section
        result.append('[{0}]'.format(group_name))
        if not isinstance(hosts, list):
            hosts = [hosts]
        result.extend(hosts)
    result_str = '\n'.join(result) + '\n'
    if to_stdout:
        print(result_str)
        return
    with open('hosts_file', 'w') as hosts_file:
        hosts_file.write(result_str)


def get_env_key(obj, key=None):
    """
    Return environment variable key to use for lookups within a
    namespace represented by the package name.

    For example, any varialbes for predix.security.uaa are stored
    as PREDIX_SECURITY_UAA_KEY
    """
    return str.join('_', [obj.__module__.replace('.', '_').upper(), key.
        upper()])


def whitelisted(data, whitelist):
    """Remove all non-whitelisted keys from input dictionary
    `data`.

    Keys are specified as a list of strings; where each string
    defines the dotted-path to an attribute.

    Args:
        data (dict): the dictionary to be cleaned.
        whitelisted: a list containing the whitelisted keys.

    Returns:
        dict: the whitelisted keys from the dictionary.
    """
    return data


def deserialize_date(string):
    """
    Deserializes string to date.

    :param string: str.
    :type string: str
    :return: date.
    :rtype: date
    """
    try:
        from dateutil.parser import parse
        return parse(string).date()
    except ImportError:
        return string


def p_gcl_phrase_cont(t):
    """phrase : STRING COMMA phrase"""
    items = []
    items.append(t[1])
    items.extend(t[3])
    t[0] = items


def true():
    """
    Always returns True.

    Complexity: O(1)
    returns: True
    """
    return True


def _guess_model_type(path):
    """
        Guess the type of a file.
        If allow_directory is False, don't consider the possibility that the
        file is a directory.
    """
    if path.endswith('.ipynb'):
        return 'notebook'
    elif '.' not in path.split('/')[-1]:
        return 'directory'
    else:
        return 'file'


def CarbfromfCO2HCO3(fCO2, HCO3, K0, K1, K2):
    """Calculate carbonate ion from CO2 fugacity and bicarbonate ion."""
    return HCO3 ** 2 * K2 / (K0 * fCO2 * K1)


def _process_dimension_kwargs(direction, kwargs):
    """
    process kwargs for AxDimension instances by stripping off the prefix
    for the appropriate direction
    """
    acceptable_keys = ['unit', 'pad', 'lim', 'label']
    processed_kwargs = {}
    for k, v in kwargs.items():
        if k.startswith(direction):
            processed_key = k.lstrip(direction)
        else:
            processed_key = k
        if processed_key in acceptable_keys:
            processed_kwargs[processed_key] = v
    return processed_kwargs


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

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


def supplements(parms, countrate=None):
    u"""Supplementary parameters:
        [8] n₁ = n*F₁     Particle number of species 1
        [9] n₂ = n*(1-F₁) Particle number of species 2
    """
    n = parms[0]
    F1 = parms[3]
    Info = list()
    Info.append([u'n₁', n * F1])
    Info.append([u'n₂', n * (1.0 - F1)])
    if countrate is not None:
        cpp = countrate / n
        Info.append(['cpp [kHz]', cpp])
    return Info


def _divide_and_round(a, b):
    """divide a by b and round result to the nearest integer

    When the ratio is exactly half-way between two integers,
    the even integer is returned.
    """
    q, r = divmod(a, b)
    r *= 2
    greater_than_half = r > b if b > 0 else r < b
    if greater_than_half or r == b and q % 2 == 1:
        q += 1
    return q


def write_frame(grid_obj, path_to_file):
    """
        Write framework coordinates into any format supported by ase.

        :type grid_obj:instance of the grid3D class
        :param grid_obj: contains all the information regarding the grid calculation
        :type path_to_file: str
        :param path_to_file: path of the output file including the full extension
        :raises:
        :rtype: None, just writes the framework coordinates in desired format
        """
    from ase.io import write
    write(path_to_file, grid_obj.ase)


@classmethod
def get_version(cls):
    """Get the current version as a tuple."""
    if not cls.table_exists():
        return 0, 0
    return cls.get(part='major').value, cls.get(part='minor').value


def strip_dollars(text):
    """
    Remove all dollar symbols from text

    Parameters
    ----------
    text : str
        Text to remove dollars from
    """
    return text.strip('$')


def __init__(size=5):
    """Construct a new keyring for a specified number of keys.
        """


def ae_3(provider):
    """Issue A-ASSOCIATE confirmation (accept) primitive."""
    provider.to_service_user.put(provider.primitive)
    return 'Sta6'


def plot(ad1, ad2, **kwargs):
    """ Alias for double plot.
    """
    ad1.plot(ad=ad2, **kwargs)


def commit_headline(commit, unused=None):
    """
    A helper function to retrieve the headline from a git.Commit message
    :param commit: a git.Commit object
    :param unused: n/a (Jinja passes it anyway)
    :return: a headline of the commit - first, stripped line of the message
    """
    return commit.message.split('\n', 1)[0].strip()


def scan_setup_py():
    """Validate the contents of setup.py against Versioneer's expectations."""
    found = set()
    setters = False
    errors = 0
    with open('setup.py', 'r') as f:
        for line in f.readlines():
            if 'import versioneer' in line:
                found.add('import')
            if 'versioneer.get_cmdclass()' in line:
                found.add('cmdclass')
            if 'versioneer.get_version()' in line:
                found.add('get_version')
            if 'versioneer.VCS' in line:
                setters = True
            if 'versioneer.versionfile_source' in line:
                setters = True
    if len(found) != 3:
        print('')
        print('Your setup.py appears to be missing some important items')
        print('(but I might be wrong). Please make sure it has something')
        print('roughly like the following:')
        print('')
        print(' import versioneer')
        print(' setup( version=versioneer.get_version(),')
        print('        cmdclass=versioneer.get_cmdclass(),  ...)')
        print('')
        errors += 1
    if setters:
        print("You should remove lines like 'versioneer.VCS = ' and")
        print("'versioneer.versionfile_source = ' . This configuration")
        print('now lives in setup.cfg, and should be removed from setup.py')
        print('')
        errors += 1
    return errors


def authenticate(request):
    """Identify a principal for a request.

        If a principal can be identified, then return the
        principal. Otherwise, return None.

        The request object is fairly opaque. We may decide
        that it implements some generic request interface.

        .. note::

           Implementation note: It is likely that the component will dispatch
           to another component based on the actual
           request interface. This will allow different
           kinds of requests to be handled correctly.

           For example, a component that authenticates
           based on user names and passwords might request
           an adapter for the request as in::

              getpw = getAdapter(request, context=self)

           The ``context`` keyword argument is used to control
           where the :class:`ILoginPassword` component is searched for.
           This is necessary because requests are placeless.
        """


def draw_text(ax, x, y, text, fontsize, color='black'):
    """Wrapper for drawing text"""
    ax.text(x, y, text, fontsize=fontsize, color=color, horizontalalignment
        ='center', verticalalignment='center')


@classmethod
def is_user_active(cls, user):
    """This method can be overwritten to implement custom user/session mechanizms
        currently it uses standard django.contrib.auth"""
    return user.is_active if user else False


def tidy_split(df, column, sep='|', keep=False):
    """
    Split the values of a column and expand so the new DataFrame has one split
    value per row. Filters rows where the column is missing.

    Params
    ------
    df : pandas.DataFrame
        dataframe with the column to split and expand
    column : str
        the column to split and expand
    sep : str
        the string used to split the column's values
    keep : bool
        whether to retain the presplit value as it's own row

    Returns
    -------
    pandas.DataFrame
        Returns a dataframe with the same columns as `df`.
    """
    indexes = list()
    new_values = list()
    df = df.dropna(subset=[column])
    for i, presplit in enumerate(df[column].astype(str)):
        values = presplit.split(sep)
        if keep and len(values) > 1:
            indexes.append(i)
            new_values.append(presplit)
        for value in values:
            indexes.append(i)
            new_values.append(value)
    new_df = df.iloc[(indexes), :].copy()
    new_df[column] = new_values
    return new_df


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


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 performance_measure(tp, tn, fp, fn):
    """
    For output of confusion table gives various perfomance performance_measures:
      :return: tpr, fpr, precision, recall, balanced accuracy, accuracy, f1-score
    """
    tpr = float(tp) / (tp + fn) if tp + fn != 0 else 0
    fpr = float(fp) / (fp + tn) if fp + tn != 0 else 0
    tnr = float(tn) / (tn + fp) if tn + fp != 0 else 0
    recall = float(tp) / (tp + fn) if tp + fn != 0 else 0
    precision = float(tp) / (tp + fp) if tp + fp != 0 else 1
    bal_accur = 0.5 * tpr + 0.5 * tnr
    accur = float(tp + tn) / (tp + tn + fp + fn)
    if precision + recall != 0:
        f1 = 2 * precision * recall / (precision + recall)
    else:
        f1 = 0
    return tpr, fpr, precision, recall, bal_accur, accur, f1


def ct_mimetype(content_type):
    """Return the mimetype part of a content type."""
    return (content_type or '').split(';')[0].strip()


@classmethod
def get_queue_type(cls, queue_id):
    """ Return the queue type, currently determined only by its suffix. """
    for queue_type in ('timed_set', 'sorted_set', 'set', 'raw'):
        if queue_id.split('/')[0].endswith('_%s' % queue_type):
            return queue_type
    return 'regular'


def create_seconds_elapsed(row):
    """
    this function parses the string time column and converts it into game
    seconds elapsed

    Inputs:
    row - row of play by play dataframe

    Outputs:
    time_in_seconds - the elapsed game time expressed in seconds
    """
    time_list = row['pctimestring'].strip().split(':')
    max_time = 720
    ot_max_time = 300
    if row['period'] in [1, 2, 3, 4]:
        time_in_seconds = max_time - (int(time_list[0]) * 60 + int(
            time_list[1])) + 720 * (int(row['period']) - 1)
    elif row['period'] > 4:
        time_in_seconds = ot_max_time - (int(time_list[0]) * 60 + int(
            time_list[1])) + 300 * (int(row['period']) - 5) + 2880
    return time_in_seconds


@staticmethod
def _get_port(from_port, to_port):
    """
        will build a string that is a port range or a port number
        depending upon the from_port and to_port value
        """
    if from_port == to_port:
        return str(from_port)
    return '{0}-{1}'.format(str(from_port), str(to_port))


def time_to_ramp_value(time_msec):
    """Convert the given time into an LCN ramp value.

    :param    int    time_msec:    The time in milliseconds.

    :returns: The (LCN-internal) ramp value (0..250).
    :rtype: int
    """
    if time_msec < 250:
        ret = 0
    elif time_msec < 500:
        ret = 1
    elif time_msec < 660:
        ret = 2
    elif time_msec < 1000:
        ret = 3
    elif time_msec < 1400:
        ret = 4
    elif time_msec < 2000:
        ret = 5
    elif time_msec < 3000:
        ret = 6
    elif time_msec < 4000:
        ret = 7
    elif time_msec < 5000:
        ret = 8
    elif time_msec < 6000:
        ret = 9
    else:
        ret = (time_msec / 1000 - 6) / 2 + 10
        if ret >= 250:
            ret = 250
    return int(ret)


def _is_toolchain_for(cls, name):
    """see if this class can provide support for toolchain named name"""
    if name:
        if hasattr(cls, 'NAME') and name == cls.NAME:
            return True
        else:
            return False
    else:
        return hasattr(cls, 'NAME') and cls.NAME