def parse_timestamp(timestamp):
    """Convert hexagon timestamp to integer (time in milliseconds)."""
    return int(timestamp, 16)


def p_language_map(t):
    """language_map : LANGUAGE_MAP START_BLOCK language_mappings END_BLOCK"""
    from audiotools.toc import CDTextLanguageMap
    t[0] = CDTextLanguageMap(t[3])


def round_filters(filters, width_coefficient, depth_divisor):
    """Round number of filters based on width multiplier."""
    filters *= width_coefficient
    new_filters = int(filters + depth_divisor / 2
        ) // depth_divisor * depth_divisor
    new_filters = max(depth_divisor, new_filters)
    if new_filters < 0.9 * filters:
        new_filters += depth_divisor
    return int(new_filters)


def should_build_with_cython(package, release=None):
    """Returns the previously used Cython version (or 'unknown' if not
    previously built) if Cython should be used to build extension modules from
    pyx files.  If the ``release`` parameter is not specified an attempt is
    made to determine the release flag from `astropy.version`.
    """
    try:
        version_module = __import__(package + '.cython_version', fromlist=[
            'release', 'cython_version'])
    except ImportError:
        version_module = None
    if release is None and version_module is not None:
        try:
            release = version_module.release
        except AttributeError:
            pass
    try:
        cython_version = version_module.cython_version
    except AttributeError:
        cython_version = 'unknown'
    have_cython = False
    try:
        import Cython
        have_cython = True
    except ImportError:
        pass
    if have_cython and (not release or cython_version == 'unknown'):
        return cython_version
    else:
        return False


@staticmethod
def get_value(data, item, default=None):
    """Get the value of `value` field of a dictionary if the `name`field identifier.
        Used to get information from the JSON response."""
    try:
        for d in data:
            try:
                if d['key'] == item:
                    return d['value']
            except:
                continue
        return default
    except:
        return default


def generate_key(url, page_number):
    """
    >>> url_a = 'http://localhost:5009/search?keywords=a'
    >>> generate_key(url_a, 10)
    'http://localhost:5009/search?keywords=a&page=10'
    >>> url_b = 'http://localhost:5009/search?keywords=b&page=1'
    >>> generate_key(url_b, 10)
    'http://localhost:5009/search?keywords=b&page=10'
    """
    index = url.rfind('page')
    if index != -1:
        result = url[0:index]
        result += 'page=%s' % page_number
    else:
        result = url
        result += '&page=%s' % page_number
    return result


@classmethod
def has_fignum(cls, num):
    """
        Return *True* if figure *num* exists.
        """
    return num in cls.figs


def upper(s):
    """French-accents-aware variant of string.upper."""
    isUnicode = isinstance(s, str)
    if not isUnicode:
        s = s.decode('utf-8')
    res = s.upper()
    if not isUnicode:
        res = res.encode('utf-8')
    return res


def _get_token_resource(client, resource, parsed_name, parsed_domain=None):
    """Peek into the user's auth token to get resource IDs

    Look into a user's token to try and find the ID of a domain, project or
    user, when given the name. Typically non-admin users will interact with
    the CLI using names. However, by default, keystone does not allow look up
    by name since it would involve listing all entities. Instead opt to use
    the correct ID (from the token) instead.
    :param client: An identity client
    :param resource: A resource to look at in the token, this may be `domain`,
                     `project_domain`, `user_domain`, `project`, or `user`.
    :param parsed_name: This is input from parsed_args that the user is hoping
                        to find in the token.
    :param parsed_domain: This is domain filter from parsed_args that used to
                          filter the results.

    :returns: The ID of the resource from the token, or the original value from
              parsed_args if it does not match.
    """
    try:
        token = client.auth.client.get_token()
        token_data = client.tokens.get_token_data(token)
        token_dict = token_data['token']
        if resource == 'domain':
            token_dict = token_dict['project']
        obj = token_dict[resource]
        if parsed_domain and parsed_domain not in obj['domain'].values():
            return parsed_name
        if isinstance(obj, list):
            for item in obj:
                if item['name'] == parsed_name:
                    return item['id']
                if item['id'] == parsed_name:
                    return parsed_name
            return parsed_name
        return obj['id'] if obj['name'] == parsed_name else parsed_name
    except Exception:
        return parsed_name


@classmethod
def from_unpack_list(cls, *args):
    """
        Given a list of raw arguments, initialize a new cls instance.

        If this class has special rules for certain fields, apply them.
        """
    unpack_args = list(args)
    for i in range(len(args)):
        custom_rule = 'fix_unpack_' + cls.names[i]
        if hasattr(cls, custom_rule):
            unpack_args[i] = getattr(cls, custom_rule)(args[i])
    return cls(*unpack_args)


@staticmethod
def _jar_id(jar):
    """Create a string identifier for the IvyModuleRef key.

        :param IvyModuleRef jar: key for a resolved jar
        :returns: String representing the key as a maven coordinate
        """
    if jar.rev:
        return '{0}:{1}:{2}'.format(jar.org, jar.name, jar.rev)
    else:
        return '{0}:{1}'.format(jar.org, jar.name)


def get_sort_params(input_params, default_key='created_at', default_dir='desc'
    ):
    """Retrieves sort keys/directions parameters.

    Processes the parameters to create a list of sort keys and sort directions
    that correspond to the 'sort_key' and 'sort_dir' parameter values. These
    sorting parameters can be specified multiple times in order to generate
    the list of sort keys and directions.

    The input parameters are not modified.

    :param input_params: webob.multidict of request parameters (from
                         nova.wsgi.Request.params)
    :param default_key: default sort key value, added to the list if no
                        'sort_key' parameters are supplied
    :param default_dir: default sort dir value, added to the list if no
                        'sort_dir' parameters are supplied
    :returns: list of sort keys, list of sort dirs
    """
    params = input_params.copy()
    sort_keys = []
    sort_dirs = []
    while 'sort_key' in params:
        sort_keys.append(params.pop('sort_key').strip())
    while 'sort_dir' in params:
        sort_dirs.append(params.pop('sort_dir').strip())
    if len(sort_keys) == 0 and default_key:
        sort_keys.append(default_key)
    if len(sort_dirs) == 0 and default_dir:
        sort_dirs.append(default_dir)
    return sort_keys, sort_dirs


@classmethod
def translate_float(cls, val):
    """Default behavior for translation"""
    return cls.translate_raw_str(val)


@classmethod
def _do_register(cls, code, name, hash_name=None, hash_new=None):
    """Add hash function data to the registry without checks."""
    cls._func_from_name[name.replace('-', '_')] = code
    cls._func_from_name[name.replace('_', '-')] = code
    if hash_name:
        cls._func_from_hash[hash_name] = code
    cls._func_hash[code] = cls._hash(hash_name, hash_new)


@classmethod
def expire(cls, key, second):
    """Set the key to expire in specified second.

        :param string key: The key to set expire.
        :param int second: The number of seconds for the key to live.
        :returns boolean: True if the operation is successful.
        """
    return cls._instance.expire(key, second)


@classmethod
def from_dict(cls, json_dict, session):
    """Return an instance of this class formed from ``json_dict``."""
    return cls(json_dict, session)


def setMemberareaCreationFlag():
    """ Toggle the policy flag for create a member areas at login.

        o ???:  Toggle is a weak semantic here;  shouldn't we be passing
                the value we want the flag to have?

        o Permission:  Manage portal
        """


def _get_right(n, allwords, window):
    """
    For df.apply(), generate right

    This needs to be performant.
    """
    end = min(n + window[1], len(allwords) - 1)
    return ' '.join(allwords[n + 1:end])[:window[1]]


def load_MDAnalysis(universe, top=None):
    """load MDAnalysis' Universe object to pytra's traj object

    Notes
    -----
    All coords will be loaded

    See Also
    --------
    load_MDAnalysisIterator
    """
    from MDAnalysis import Universe
    from pytraj.Trajectory import Trajectory
    from ..Frame import Frame
    if not isinstance(universe, Universe):
        raise ValueError('must be a Universe')
    if top is None:
        raise ValueError('need a Topology or pdb/mol2/...')
    else:
        pseudotop = top
    ag = universe.atoms
    farray = Trajectory()
    farray.top = pseudotop
    for _ in universe.trajectory:
        frame = Frame(farray.top.n_atoms)
        frame.boxview[:] = farray.top.box[:]
        frame.xyz[:] = ag.positions
        farray.append(frame, copy=False)
    return farray


def is_data_value_ascending(dataset):
    """Checks if the data is ascending."""
    ascending = True
    starting_abscissa = list(dataset[0].items())[0][1]
    last_abscissa = starting_abscissa
    for item in dataset[1:]:
        current_abscisssa = list(item.items())[0]
        if current_abscisssa[1] <= last_abscissa:
            ascending = False
        last_abscissa = current_abscisssa[1]
    return ascending


@staticmethod
def auto_extract(payload):
    """
        Próbuje automatycznie wydobyć klucz.

        :param dict payload:
        :return: Wydobyty klucz
        :rtype: str
        """
    for key in payload.keys():
        if key not in ('Resources', 'Url'):
            return key
    return


def evaluate_bounding_box(ctrlpts):
    """ Computes the minimum bounding box of the point set.

    The (minimum) bounding box is the smallest enclosure in which all the input points lie.

    :param ctrlpts: points
    :type ctrlpts: list, tuple
    :return: bounding box in the format [min, max]
    :rtype: tuple
    """
    dimension = len(ctrlpts[0])
    bbmin = [float('inf') for _ in range(0, dimension)]
    bbmax = [float('-inf') for _ in range(0, dimension)]
    for cpt in ctrlpts:
        for i, arr in enumerate(zip(cpt, bbmin)):
            if arr[0] < arr[1]:
                bbmin[i] = arr[0]
        for i, arr in enumerate(zip(cpt, bbmax)):
            if arr[0] > arr[1]:
                bbmax[i] = arr[0]
    return tuple(bbmin), tuple(bbmax)


def arctanh(data=None, out=None, name=None, **kwargs):
    """Returns the element-wise inverse hyperbolic tangent of the input array, \\
    computed element-wise.

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

       - arctanh(default) = default
       - arctanh(row_sparse) = row_sparse
       - arctanh(csr) = csr

    Defined in src/operator/tensor/elemwise_unary_op_trig.cc:L515

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

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

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


def setSliceQueryParam(params, dims, sel):
    """
    Helper method - set query parameter for given shape + selection

        Query arg should be in the form: [<dim1>, <dim2>, ... , <dimn>]
            brackets are optional for one dimensional arrays.
            Each dimension, valid formats are:
                single integer: n
                start and end: n:m
                start, end, and stride: n:m:s
    """
    rank = len(dims)
    start = list(sel.start)
    count = list(sel.count)
    step = list(sel.step)
    if rank > 0:
        sel_param = '['
        for i in range(rank):
            sel_param += str(start[i])
            sel_param += ':'
            sel_param += str(start[i] + count[i])
            if step[i] > 1:
                sel_param += ':'
                sel_param += str(step[i])
            if i < rank - 1:
                sel_param += ','
        sel_param += ']'
        params['select'] = sel_param


def print_header(npart, niter, tol_type, tlevels, priors):
    """print header to screen
        Input:
        npart - number of particles
        niter - number of iterations
        tol_type - decreasing tolerance level setting
        tlevels - max/min threshold levels
        priors - priors for parameters
        """
    print('\t \t')
    print(
        '\t ########################     astroABC     ########################\t'
        )
    print('\t \t')
    print('\t Npart=%d \t numt=%d \t tol=[%.4f,%.4f] %s' % (npart, niter,
        tlevels[0], tlevels[1], tol_type))
    print('\t Priors=', priors)


def copyTo(target, new_name=None):
    """Copy this object to the `target` given.

        Returns the new name within the `target`. After the copy
        is created and before adding it to the target container,
        an `IObjectCopied` event is published.
        """


def gcd(a, b):
    """Compute the greatest common divisor of a and b"""
    while b > 0:
        a, b = b, a % b
    return a


def __call__(name, text, data, interface):
    """Return a transformer bound to those data.
        """


def parameters_dict_to_str(d):
    """
    Convert a dict of param section to a string

    Parameters
    ----------
    d : dict
        Parameters and their descriptions in a docstring

    Returns
    -------
    param_section : str
        Text in the parameter section

    See Also
    --------
    :func:`parameters_str_to_dict`
    """
    return '\n'.join(d.values())


def view_zoom(factor: float=0.0):
    """Zoom in/out the view

    :param factor: Factor, Zoom factor, values higher than 1.0 zoom in, lower values zoom out
    :type factor: float
    """
    pass


def convert_totals(report):
    """Converts the V4 report totals into the V3 report totals.

  Args:
    report: a Google Analytics V4 Report object.
  Returns:
    A list of rows of the V3 report object.
  """
    report_totals = report.get('data').get('totals')[0].get('values', [])
    metric_headers = report.get('columnHeader', {}).get('metricHeader').get(
        'metricHeaderEntries')
    totals = {}
    for metric_header, value in zip(metric_headers, report_totals):
        totals[metric_header.get('name')] = value
    return totals


def animation_cancel(restore_frame: bool=True):
    """Cancel animation, returning to the original frame

    :param restore_frame: Restore Frame, Restore the frame when animation was initialized
    :type restore_frame: bool
    """
    pass


def __contains__(name):
    """Return true if we contain the named instance"""


def editable_google_map(context):
    """
    Dependencies for editable_google_map gizmo.
    """
    return ('tethys_gizmos/vendor/farbtastic/farbtastic.css',
        'tethys_gizmos/vendor/farbtastic/farbtastic.js',
        'tethys_gizmos/js/tethys_editable_map.js')


def CDLLONGLEGGEDDOJI(df):
    """
    Long Legged Doji
    """


def releng_log_configuration(debug, nocolor, verbose):
    """
    configure the global logging state of the running instance

    Adjusts the running instance's active state for logging-related
    configuration values. This method is best invoked near the start of the
    process's life cycle to provide consistent logging output. This method does
    not required to be invoked to invoke provided logging methods.

    Args:
        debug: toggle the enablement of debug messages
        nocolor: toggle the disablement of colorized messages
        verbose: toggle the enablement of verbose messages
    """
    global RELENG_LOG_DEBUG_FLAG
    global RELENG_LOG_NOCOLOR_FLAG
    global RELENG_LOG_VERBOSE_FLAG
    RELENG_LOG_DEBUG_FLAG = debug
    RELENG_LOG_NOCOLOR_FLAG = nocolor
    RELENG_LOG_VERBOSE_FLAG = verbose


@staticmethod
def dynamic_init():
    """ dynamic part of the polder module
            initialising polders
        """
    pass


def extract_view_name(view):
    """
    Extract view name
    :param view:
    :return:
    """
    if hasattr(view, '__name__'):
        return view.__name__
    else:
        return view.__class__.__name__


def space_references(document):
    """Ensure a space around reference links, so there's a gap when they are removed."""
    for ref in document.xpath('.//a/sup/span[@class="sup_ref"]'):
        a = ref.getparent().getparent()
        if a is not None:
            atail = a.tail or ''
            if not atail.startswith(')') and not atail.startswith(','
                ) and not atail.startswith(' '):
                a.tail = ' ' + atail
    return document


@classmethod
def from_section(cls, config, section, **kwargs):
    """
        Creates a :class:`~vsgen.project.VSGProject` from a :class:`~configparser.ConfigParser` section.

        :param ConfigParser config:   A :class:`~configparser.ConfigParser` instance.
        :param str          section:  A :class:`~configparser.ConfigParser` section key.
        :param              kwargs:   List of additional keyworded arguments to be passed into the :class:`~vsgen.project.VSGProject`.
        :return:                      A valid :class:`~vsgen.project.VSGProject` instance if succesful; None otherwise.
        """
    p = cls(**kwargs)
    p.Name = config.get(section, 'name', fallback=p.Name)
    p.FileName = config.getfile(section, 'filename', fallback=p.FileName)
    p.SearchPath = config.getdirs(section, 'search_path', fallback=p.SearchPath
        )
    p.OutputPath = config.getdir(section, 'output_path', fallback=p.OutputPath)
    p.WorkingDirectory = config.getdir(section, 'working_directory',
        fallback=p.WorkingDirectory)
    p.RootNamespace = config.get(section, 'root_namespace', fallback=p.
        RootNamespace)
    p.ProjectHome = config.getdir(section, 'project_home', fallback=p.
        ProjectHome)
    p.StartupFile = config.getfile(section, 'startup_file', fallback=p.
        StartupFile)
    p.CompileFiles = config.getlist(section, 'compile_files', fallback=p.
        CompileFiles)
    p.ContentFiles = config.getlist(section, 'content_files', fallback=p.
        ContentFiles)
    p.CompileInFilter = config.getlist(section, 'compile_in_filter',
        fallback=p.CompileInFilter)
    p.CompileExFilter = config.getlist(section, 'compile_ex_filter',
        fallback=p.CompileExFilter)
    p.ContentInFilter = config.getlist(section, 'content_in_filter',
        fallback=p.ContentInFilter)
    p.ContentExFilter = config.getlist(section, 'content_ex_filter',
        fallback=p.ContentExFilter)
    p.DirectoryInFilter = config.getlist(section, 'directory_in_filter',
        fallback=p.DirectoryInFilter)
    p.DirectoryExFilter = config.getlist(section, 'directory_ex_filter',
        fallback=p.DirectoryExFilter)
    root_path = config.get(section, 'root_path', fallback='')
    p.insert_files(root_path)
    return p


def makeCentered(data):
    """Move the mean of the data matrix into the origin.

    Rows are perceived as datapoints.
    """
    return data - data.mean(axis=0)


def unpack(iterable, cls):
    """ Unpack the value

    Parameters
    ----------
    iterable
    cls

    Returns
    -------

    """
    if len(iterable) == 1:
        return iterable.pop()
    else:
        return cls(iterable)


def make_endpoint(model):
    """Make an endpoint for a given model

    See the :class:`repose.resources.Resource.Meta` for a description
    of endpoint URL formatting.
    """
    parent = model.parent_resource
    models = [model]
    while parent:
        models.append(parent)
        parent = parent.parent_resource
    values = {}
    for inst in models:
        for k in inst._fields:
            values['{}_{}'.format(inst.__class__.__name__.lower(), k)
                ] = getattr(inst, k)
            if inst is model:
                values[k] = getattr(inst, k)
    values.update(**model.get_endpoint_values())
    return model.Meta.endpoint.format(**values)


def is_email_link(href=None):
    """Utility function to determine whether the supplied href attribute
    is an email link."""
    print('email_link()')
    return href and 'mailto:' in href


@classmethod
def vol_type(cls):
    """The type of volume supported by this type."""
    return 'rbd'


def bin_paths(ops, raw):
    """ set which binary is being aligned to """
    raw_file_align = []
    raw_file_alt = []
    reg_file_align = []
    reg_file_alt = []
    if raw:
        if ops['nchannels'] > 1:
            if ops['functional_chan'] == ops['align_by_chan']:
                raw_file_align = ops['raw_file']
                raw_file_alt = ops['raw_file_chan2']
                reg_file_align = ops['reg_file']
                reg_file_alt = ops['reg_file_chan2']
            else:
                raw_file_align = ops['raw_file_chan2']
                raw_file_alt = ops['raw_file']
                reg_file_align = ops['reg_file_chan2']
                reg_file_alt = ops['reg_file']
        else:
            raw_file_align = ops['raw_file']
            reg_file_align = ops['reg_file']
    elif ops['nchannels'] > 1:
        if ops['functional_chan'] == ops['align_by_chan']:
            reg_file_align = ops['reg_file']
            reg_file_alt = ops['reg_file_chan2']
        else:
            reg_file_align = ops['reg_file_chan2']
            reg_file_alt = ops['reg_file']
    else:
        reg_file_align = ops['reg_file']
    return reg_file_align, reg_file_alt, raw_file_align, raw_file_alt


def luhn_check(card_number):
    """ checks to make sure that the card passes a luhn mod-10 checksum """
    sum = 0
    num_digits = len(card_number)
    oddeven = num_digits & 1
    for count in range(0, num_digits):
        digit = int(card_number[count])
        if not count & 1 ^ oddeven:
            digit *= 2
        if digit > 9:
            digit -= 9
        sum += digit
    return sum % 10 == 0


@classmethod
def _getChildren(cls, session, dn):
    """
        Get the children

        :param session: Session instance object
        :param dn: string containing the distinguished name
        :return: json dictionary containing the children objects
        """
    result = []
    mo_query_url = '/api/mo/' + dn + '.json?query-target=children'
    ret = session.get(mo_query_url)
    mo_data = ret.json()['imdata']
    for node in mo_data:
        for key in node:
            result.append((key, node[key]))
    return result


def list_param(current_scene_db, query_start, query_end):
    """lists the parameters in scene"""
    from src.praxxis.sqlite import sqlite_parameter
    from src.praxxis.display import display_param
    param_list = sqlite_parameter.list_param(current_scene_db, query_start,
        query_end)
    display_param.display_list_param(param_list)
    return param_list


@classmethod
def restore(cls, data):
    """
        cannot restore here because we don't know what type of enum it is
        """
    raise NotImplementedError


def ignoreCode(code, lineFlags):
    """
    Function to check, if the given code should be ignored as per line flags.

    @param code error code to be checked
    @type str
    @param lineFlags list of line flags to check against
    @type list of str
    @return flag indicating to ignore the code
    @rtype bool
    """
    if lineFlags:
        if '__IGNORE_WARNING__' in lineFlags or 'noqa' in lineFlags:
            return True
        for flag in lineFlags:
            if flag.startswith('__IGNORE_WARNING_'):
                ignoredCode = flag[2:-2].rsplit('_', 1)[-1]
                if code.startswith(ignoredCode):
                    return True
    return False


def flash_with_undo(msg, queue='', allow_duplicate=True):
    """Display a Pyramid ``flash message`` to the appropriate
        queue with a button to allow an undo of the commit."""


def vertex_group_select():
    """Select all the vertices assigned to the active vertex group

    """
    pass


def passFrame(*args):
    """Say frame is valid no matter what arguments are.

    Parameters
    ----------
    *args
        Any arguments required by API.

    Returns
    -------
    bool
        Always True to pass the frame check.
    """
    return True


def __regional_term_voxel(graph, regional_term_args):
    """Fake regional_term function with the appropriate signature."""
    return {}


def binance_interval(interval):
    """ Return the time interval in the specific format allowed by Binance.

    Parameters
    ----------
    interval : int
        Must be in seconds as 60, 180, 300, 900, 1800, 3600, 7200, 14400,
        21600, 28800, 43200, 86400, 259200, 604800, 2592000.

    Returns
    -------
    form : str
        Specific format allowed by Binance.

    Examples
    --------
    >>> binance_interval(7200)
    '2h'

    """
    if interval / 60 in [1, 3, 5, 15, 30]:
        return '{}m'.format(int(interval / 60))
    elif interval / 3600 in [1, 2, 4, 6, 8, 12]:
        return '{}h'.format(int(interval / 3600))
    elif interval / 86400 in [1, 3]:
        return '{}d'.format(int(interval / 86400))
    elif interval == 604800:
        return '1w'
    elif interval == 2592000:
        return '1M'
    else:
        print('No format allowed.')


def dfs_labeled_edges(G, source=None):
    """Produce edges in a depth-first-search (DFS) labeled by type.

    Parameters
    ----------
    G : NetworkX graph

    source : node, optional
       Specify starting node for depth-first search and return edges in
       the component reachable from source.

    Returns
    -------
    edges: generator
       A generator of edges in the depth-first-search labeled with 'forward',
       'nontree', and 'reverse'.

    Examples
    --------
    >>> G = nx.Graph()
    >>> G.add_path([0,1,2])
    >>> edges = (list(nx.dfs_labeled_edges(G,0)))

    Notes
    -----
    Based on http://www.ics.uci.edu/~eppstein/PADS/DFS.py
    by D. Eppstein, July 2004.

    If a source is not specified then a source is chosen arbitrarily and
    repeatedly until all components in the graph are searched.
    """
    if source is None:
        nodes = G
    else:
        nodes = [source]
    visited = set()
    for start in nodes:
        if start in visited:
            continue
        yield start, start, {'dir': 'forward'}
        visited.add(start)
        stack = [(start, iter(G[start]))]
        while stack:
            parent, children = stack[-1]
            try:
                child = next(children)
                if child in visited:
                    yield parent, child, {'dir': 'nontree'}
                else:
                    yield parent, child, {'dir': 'forward'}
                    visited.add(child)
                    stack.append((child, iter(G[child])))
            except StopIteration:
                stack.pop()
                if stack:
                    yield stack[-1][0], parent, {'dir': 'reverse'}
        yield start, start, {'dir': 'reverse'}


def _quote_str(o):
    """Escape a str/unicode object. Note that compiled code never uses ' for attributes and >
    doesn't needed to be escaped to form valid HTML. These replace calls are a big cost,
    so saving 40% of them is a win.
    """
    return o.replace(u'&', u'&').replace(u'<', u'<').replace(u"'",
        u''')


@staticmethod
def rand(*sizes):
    """Generate random ArithmeticSharedTensor uniform on [0, 1]"""
    raise NotImplementedError('HomomorphicProvider not implemented')


def makeSlideshow():
    """Make a folderish object a slideshowfolder"""


def get_form_element_entries_for_form_wizard_entry(form_wizard_entry):
    """Get form element entries for the form wizard entry."""
    form_element_entries = []
    for form_wizard_form_entry in form_wizard_entry.formwizardformentry_set.all(
        ):
        form_element_entries += (form_wizard_form_entry.form_entry.
            formelemententry_set.all()[:])
    return form_element_entries


@classmethod
def supports_from_pcm(cls):
    """returns True if all necessary components are available
        to support the .from_pcm() classmethod"""
    try:
        from audiotools.encoders import encode_tta
        return True
    except ImportError:
        return False


@classmethod
def unpack(cls, buf):
    """
        Unpack buffer into command, metadata (e.g. magic number, checksum), and payload.
        """
    raise NotImplementedError()


def longest_common_prefix(items1, items2):
    """
    Return the longest common prefix.

      >>> longest_common_prefix("abcde", "abcxy")
      'abc'

    :rtype:
      ``type(items1)``
    """
    n = 0
    for x1, x2 in zip(items1, items2):
        if x1 != x2:
            break
        n += 1
    return items1[:n]


@classmethod
def find_by_branch(cls, store, branch=None):
    """find results for this Inventory View that refenrences *Branch*

        :param store: the store that will be used for find the results
        :param branch: the |branch| used to filter the results
        :return: the matching views
        """
    if branch is not None:
        return store.find(cls, branch_id=branch.id)
    return store.find(cls)


def groupmodel(sum=None, ssd=None, jet=None, adaf=None):
    """
Groups the different components of a SED model into one dictionary for convenient
access. The model component SEDs are assumed to have been imported using the
SED class. This method is used in the plot method.

Example:

Imports the model SEDs:
>>> s=SED(file='sum.dat', logfmt=1)
>>> disk=SED(file='disk.dat', logfmt=1)
>>> a=SED(file='adaf.dat', logfmt=1)

Groups them together in a dictionary d:
>>> d=groupmodel(sum=s,ssd=disk,adaf=a)
returning {'sum':s,'ssd':disk,'adaf':a}.
	"""
    m = {}
    if sum != None:
        m['sum'] = sum
    if ssd != None:
        m['ssd'] = ssd
    if jet != None:
        m['jet'] = jet
    if adaf != None:
        m['adaf'] = adaf
    return m


@classmethod
def construct(cls, project, **desc):
    """Construct a driver from a project and a description."""
    return cls(maker=project.maker, **desc)


@classmethod
def label_with_text(cls, text):
    """Returns an XPath to find an HTML <label> containing the text in `text`."""
    return cls('//label[normalize-space()=normalize-space("%s")]' % text)


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 setting(name, default=None):
    """
        Gets settings from django.conf if exists, returns default value otherwise

        Example:

        DEBUG = setting('DEBUG', False)
    """
    from django.conf import settings
    return getattr(settings, name, default)


def delete_loose(use_verts: bool=True, use_edges: bool=True, use_faces:
    bool=False):
    """Delete loose vertices, edges or faces

    :param use_verts: Vertices, Remove loose vertices
    :type use_verts: bool
    :param use_edges: Edges, Remove loose edges
    :type use_edges: bool
    :param use_faces: Faces, Remove loose faces
    :type use_faces: bool
    """
    pass


@classmethod
def update_with_id(cls, id, **data):
    """Update a resource without retrieving it first."""
    resource = cls(id=id)
    resource.update(**data)
    return resource


def _allowed_file(filename):
    """Return True if file extension is allowed, False otherwise."""
    extensions = ['csv', 'xls', 'xlsx']
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in extensions


def check_if_channel_maps_are_same(channel_map_1, channel_map_2):
    """
    Determines if two channel maps are identical
    """
    if len(channel_map_1) != len(channel_map_2):
        return False
    channel_map_1_keys = sorted(list(channel_map_1.keys()))
    channel_map_2_keys = sorted(list(channel_map_2.keys()))
    for n_area in range(len(channel_map_1_keys)):
        if channel_map_1_keys[n_area] != channel_map_2_keys[n_area]:
            return False
    for area in channel_map_1_keys:
        if not all(channel_map_1[area]['list'] == channel_map_2[area]['list']):
            return False
    return True


def binary_search_continuous(f, target, low, high):
    """Perform a floating-point binary search over the interval
    [low,high], evaluating the monotonically increasing function f at
    each point until f(x)=target."""
    low = float(low)
    high = float(high)
    while True:
        x = (low + high) / 2
        y = f(x)
        if y == target:
            return x
        elif y < target:
            low = x
        else:
            high = x


def list_server_certificates(PathPrefix=None, Marker=None, MaxItems=None):
    """
    Lists the server certificates stored in IAM that have the specified path prefix. If none exist, the action returns an empty list.
    You can paginate the results using the MaxItems and Marker parameters.
    For more information about working with server certificates, including a list of AWS services that can use the server certificates that you manage with IAM, go to Working with Server Certificates in the IAM User Guide .
    See also: AWS API Documentation

    :example: response = client.list_server_certificates(
        PathPrefix='string',
        Marker='string',
        MaxItems=123
    )

    :type PathPrefix: string
    :param PathPrefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts .
            This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This paramater allows (per its regex pattern ) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes, containing any ASCII character from the ! (u0021) thru the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters.

    :type Marker: string
    :param Marker: Use this parameter only when paginating results and only after you receive a response indicating that the results are truncated. Set it to the value of the Marker element in the response that you received to indicate where the next call should start.

    :type MaxItems: integer
    :param MaxItems: (Optional) Use this only when paginating results to indicate the maximum number of items you want in the response. If additional items exist beyond the maximum you specify, the IsTruncated response element is true .
            If you do not include this parameter, it defaults to 100. Note that IAM might return fewer results, even when there are more results available. In that case, the IsTruncated response element returns true and Marker contains a value to include in the subsequent call that tells the service where to continue from.

    :rtype: dict
    :return: {
        'ServerCertificateMetadataList': [
            {
                'Path': 'string',
                'ServerCertificateName': 'string',
                'ServerCertificateId': 'string',
                'Arn': 'string',
                'UploadDate': datetime(2015, 1, 1),
                'Expiration': datetime(2015, 1, 1)
            },
        ],
        'IsTruncated': True|False,
        'Marker': 'string'
    }

    """
    pass


@classmethod
def from_fahrenheit(cls, val):
    """Convert `val` ºF to K"""
    return (val + 459.67) * (5 / 9) * cls.kelvin


def collapse_hide_unused_toggle():
    """Toggle collapsed nodes and hide unused sockets

    """
    pass


def cursorNextOrNone(cursor):
    """
    Given a Mongo cursor, return the next value if there is one.  If not,
    return None.

    :param cursor: a cursor to get a value from.
    :returns: the next value or None.
    """
    try:
        return cursor.next()
    except StopIteration:
        return None


def unauthenticated(f):
    """Adds 'unauthenticated' attribute to decorated function.

    Usage::

        @unauthenticated
        def mymethod(f):
            ...

    """
    f.unauthenticated = True
    return f


def height_gpemgh(GPE, mass, gravity):
    """Usage: Find height from gravitational potential energy, mass and gravity"""
    result = GPE / mass * gravity
    return result


def _extract_bv_segments(vmrk_fname):
    """Extract segments from BrainVision VMRK file."""
    pass


def get_metric_parent(metric):
    """
    Determine the parent of a metric.

    If no parent exists, the root ``#`` is given.

    Parameters
    ----------
    metric : str
        The dotted metric to act on.

    Returns
    -------
    parent : str

    Examples
    --------
    >>> get_metric_parent("foo")
    "#"
    >>> get_metric_parent("foo.bar")
    "foo"
    >>> get_metric_parent("foo.bar.baz.foo")
    "foo.bar.baz"
    """
    s = metric.split('.')
    if len(s) == 1:
        parent = '#'
    else:
        parent = '.'.join(s[:-1])
    return parent


def skip_bom(f):
    """
    Read past a BOM at the beginning of a source file.
    This could be added to the scanner, but it's *substantially* easier
    to keep it at this level.
    """
    if f.read(1) != u'\ufeff':
        f.seek(0)


def _overload_dummy(*args, **kwds):
    """Helper for @overload to raise when called."""
    raise NotImplementedError(
        'You should not call an overloaded function. A series of @overload-decorated functions outside a stub module should always be followed by an implementation that is not @overload-ed.'
        )


def _read_header(file):
    """Process the listfile header."""
    header = []
    while True:
        line = file.readline().decode('utf-8').strip()
        if line in ('[LISTDATA]', '[DATA]'):
            break
        header.append(line)
    is_ascii = False
    if '[MPA4A]' in header[0]:
        version = 4
        is_ascii = True
    else:
        version = 3
    return file, header, version, is_ascii


def add_debug_toolbar(app):
    """ Add debug toolbar capability """
    from boiler.feature.debug_toolbar import debug_toolbar_feature
    debug_toolbar_feature(app)


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


def start_gateway(GatewayARN=None):
    """
    Starts a gateway that you previously shut down (see  ShutdownGateway ). After the gateway starts, you can then make other API calls, your applications can read from or write to the gateway's storage volumes and you will be able to take snapshot backups.
    To specify which gateway to start, use the Amazon Resource Name (ARN) of the gateway in your request.
    See also: AWS API Documentation

    Examples
    Starts a gateway service that was previously shut down.
    Expected Output:

    :example: response = client.start_gateway(
        GatewayARN='string'
    )

    :type GatewayARN: string
    :param GatewayARN: [REQUIRED]
            The Amazon Resource Name (ARN) of the gateway. Use the ListGateways operation to return a list of gateways for your account and region.

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

    """
    pass


@classmethod
def trim_unsupported_chars(cls, string: str) ->str:
    """trim non-font characters"""
    s = string
    for char in ['\x1b', '\\u001b', '\x1b']:
        s = s.replace(char, '')
    return s


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 get_digitalization_links(record):
    """
    Given a marc record, just return all links (from 856.u).

    Same as:

        >>> record = marcx.Record()
        >>> record.add('856', u='http://google.com')
        >>> list(record.itervalues('856.u'))
        ['http://google.com']

    """
    for field_856 in record.get_fields('856'):
        is_digitalization = False
        for x in field_856.get_subfields('x'):
            if 'Digitalization' == x:
                is_digitalization = True
        if not is_digitalization:
            for z in field_856.get_subfields('z'):
                if 'digit' in z or 'Digit' in z and not ('Bach digital' in
                    z or 'Bach Digital' in z):
                    is_digitalization = True
                elif 'exemplar' in z or 'Exemplar' in z:
                    is_digitalization = True
        if is_digitalization:
            for url in field_856.get_subfields('u'):
                yield url


def bech32_polymod(values):
    """Internal function that computes the Bech32 checksum."""
    generator = [996825010, 642813549, 513874426, 1027748829, 705979059]
    chk = 1
    for value in values:
        top = chk >> 25
        chk = (chk & 33554431) << 5 ^ value
        for i in range(5):
            chk ^= generator[i] if top >> i & 1 else 0
    return chk


def get_workflow(path=''):
    """
        get_workflow returns the workflow state of the object.
        """


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


def isFile():
    """
        True if node is a file.
        """


def gradient_add(grad_1, grad_2, param, verbose=0):
    """
    Sum two gradients

    :param grad_1: (TensorFlow Tensor) The first gradient
    :param grad_2: (TensorFlow Tensor) The second gradient
    :param param: (TensorFlow parameters) The trainable parameters
    :param verbose: (int) verbosity level
    :return: (TensorFlow Tensor) the sum of the gradients
    """
    if verbose > 1:
        print([grad_1, grad_2, param.name])
    if grad_1 is None and grad_2 is None:
        return None
    elif grad_1 is None:
        return grad_2
    elif grad_2 is None:
        return grad_1
    else:
        return grad_1 + grad_2


def default_NDVI(widgets):
    """
    global panelA,modified_tif,bandarrays,workbandarrays
    if RGB is not None and Infrared is not None and Infrared.size==RGB.size:

        #upper=-(Inf0-RGBg)
        #lower=Inf0+RGBg
        #lower=np.where(lower==0,1,lower)

        upper=Infrared.bands[0,:,:]-RGB.bands[0,:,:]
        lower=Infrared.bands[0,:,:]+RGB.bands[0,:,:]
        lower=np.where(lower==0,1,lower)
        NDVI=upper/lower
        tempdict={'LabOstu':NDVI}
        bandarrays.update(tempdict)

        if 'LabOstu' not in workbandarrays:
            worktempdict={'LabOstu':cv2.resize(NDVI,(450,450),interpolation=cv2.INTER_LINEAR)}
            workbandarrays.update(worktempdict)
        if 'Greenness' not in workbandarrays:
            worktempdict={'Greenness':cv2.resize(Greenness,(450,450),interpolation=cv2.INTER_LINEAR)}
            workbandarrays.update(worktempdict)

        out_fn='tempNDVI.tif'
        gtiffdriver=gdal.GetDriverByName('GTiff')
        out_ds=gtiffdriver.Create(out_fn,upper.shape[1],upper.shape[0],1,3)
        out_band=out_ds.GetRasterBand(1)
        out_band.WriteArray(NDVI)
        out_ds.FlushCache()

        modified_tif=cv2.resize(NDVI,(450,450),interpolation=cv2.INTER_NEAREST)
        pyplt.imsave(out_png,modified_tif)
        image=cv2.imread(out_png)
        image=Image.fromarray(image)
        image=ImageTk.PhotoImage(image)
        if panelA is not None:
            panelA.destroy()
        panelA=Label(ctr_left,image=image)
        panelA.image=image
        panelA.grid(row=0,column=0)
    """
    global panelB
    (calframe, RGBframe, Infframe, Heightframe, Opframe, Numframe, Entframe,
        entbox, button) = widgets[:9]
    calframe.grid_forget()
    RGBframe.grid_forget()
    Infframe.grid_forget()
    Heightframe.grid_forget()
    Opframe.grid_forget()
    Numframe.grid_forget()
    Entframe.grid_forget()
    entbox.pack_forget()
    button.pack_forget()
    for widget in widgets[9:]:
        widget.pack_forget()
    pass


def group(*args):
    """TODO: group docstring.

  :param *args: TODO

  """
    pass


def _get_policy_package_name_for_test():
    """ Test hook method that returns a package name for policy modules. """
    return 'vint.linting.policy'


def fits_ccddata_writer(ccd_data, filename, hdu_mask='MASK',
    hdu_uncertainty='UNCERT', hdu_flags=None, key_uncertainty_type='UTYPE',
    **kwd):
    """
    Write CCDData object to FITS file.

    Parameters
    ----------
    filename : str
        Name of file.

    hdu_mask, hdu_uncertainty, hdu_flags : str or None, optional
        If it is a string append this attribute to the HDUList as
        `~astropy.io.fits.ImageHDU` with the string as extension name.
        Flags are not supported at this time. If ``None`` this attribute
        is not appended.
        Default is ``'MASK'`` for mask, ``'UNCERT'`` for uncertainty and
        ``None`` for flags.

    key_uncertainty_type : str, optional
        The header key name for the class name of the uncertainty (if any)
        that is used to store the uncertainty type in the uncertainty hdu.
        Default is ``UTYPE``.

        .. versionadded:: 3.1

    kwd :
        All additional keywords are passed to :py:mod:`astropy.io.fits`

    Raises
    -------
    ValueError
        - If ``self.mask`` is set but not a `numpy.ndarray`.
        - If ``self.uncertainty`` is set but not a
          `~astropy.nddata.StdDevUncertainty`.
        - If ``self.uncertainty`` is set but has another unit then
          ``self.data``.

    NotImplementedError
        Saving flags is not supported.
    """
    hdu = ccd_data.to_hdu(hdu_mask=hdu_mask, hdu_uncertainty=
        hdu_uncertainty, key_uncertainty_type=key_uncertainty_type,
        hdu_flags=hdu_flags)
    hdu.writeto(filename, **kwd)


def is_iterable(arg):
    """
    Determine if an object is iterable
    """
    return hasattr(arg, '__iter__')


def get_prop_filter_spec(client_factory, obj_spec, prop_spec):
    """Builds the Property Filter Spec Object."""
    prop_filter_spec = client_factory.create('ns0:PropertyFilterSpec')
    prop_filter_spec.propSet = prop_spec
    prop_filter_spec.objectSet = obj_spec
    return prop_filter_spec


def supplements(parms, countrate=None):
    u"""Supplementary parameters:
        [10]  n₁ = n*F₁     Particle number of species 1
        [11] 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 str_to_list(val, separator=','):
    """
    Split one string to a list by separator.
    """
    if val is None:
        return None
    return val.split(separator)


def full_width():
    """Resize the notebook to use it's full width"""
    from IPython.core.display import display, HTML
    display(HTML('<style>.container { width:100% !important; }</style>'))


def do_assert(condition, message='Assertion failed.'):
    """Assert that a ``condition`` holds or raise an ``Exception`` otherwise.

    This was added because `assert` statements are removed in optimized code.
    It replaced `assert` statements throughout the library, but that was
    reverted again for readability and performance reasons.

    Parameters
    ----------
    condition : bool
        If ``False``, an exception is raised.

    message : str, optional
        Error message.

    """
    if not condition:
        raise AssertionError(str(message))


def CurrentAmplifierThreePortWithoutDenom(G, Zi, Zo):
    """symbolic three port current amplifier without denominator
    @param G string current gain
    @param Zi string input impedance
    @param Zo string output impedance
    @return list of list of string s-parameter matrix
    containing LaTeX or ASCII strings for each element.
    @note strings can be any valid LaTeX
    @note this is the symbolic version of SignalIntegrity.Lib.Devices.CurrentAmplifier.CurrentAmplifierThreePort
    @remark this returns the s-parameter matrix without the denominator element
    @see CurrentAmplifierThreePortDenom
    """
    S11 = (Zo + '\\cdot ' + Zi + '+Z0\\cdot  (2\\cdot ' + Zi + '-' + G +
        '\\cdot ' + Zo + ' )-Z0^2')
    S12 = '2\\cdot Z0^2'
    S13 = '2\\cdot Z0^2+2\\cdot ' + Zo + '\\cdot Z0'
    S21 = '2\\cdot Z0^2+2\\cdot ' + G + '\\cdot ' + Zo + '\\cdot Z0'
    S22 = (Zo + '\\cdot ' + Zi + '+Z0\\cdot  (2\\cdot ' + Zo + '-' + G +
        '\\cdot ' + Zo + ' )-Z0^2')
    S23 = ('2\\cdot Z0^2+Z0\\cdot  (2\\cdot ' + Zi + '-2\\cdot ' + G +
        '\\cdot ' + Zo + ' )')
    S31 = ('2\\cdot Z0^2+Z0\\cdot  (2\\cdot ' + Zo + '-2\\cdot ' + G +
        '\\cdot ' + Zo + ' )')
    S32 = '2\\cdot Z0^2+2\\cdot ' + Zi + '\\cdot Z0'
    S33 = Zo + '\\cdot ' + Zi + '-Z0^2+' + G + '\\cdot ' + Zo + '\\cdot Z0'
    return [[S11, S12, S13], [S21, S22, S23], [S31, S32, S33]]


@staticmethod
def create(type_dict, *type_parameters):
    """
      Implemented by the TypeFactory to produce a new type.

      Should return:
        reified type
        (with usable type.__name__)
    """
    raise NotImplementedError('create unimplemented for: %s' % repr(
        type_parameters))


def filter_drivers(drivers):
    """This filters all of the drivers into separate lists."""
    supported_drivers = []
    unsupported_drivers = []
    for driver in drivers:
        if not driver.supported:
            unsupported_drivers.append(driver)
        else:
            supported_drivers.append(driver)
    return supported_drivers, unsupported_drivers


def auto_text_highlight(text):
    """
    Automatically highlight interesting parts in the text
    :param text:
    :return:
    """
    text = text.replace('In class', "Class")
    text = text.replace('In method', "Method"
        )
    text = text.replace('At ', "File")
    text = text.replace('line ', "line")
    text = text.replace('\n', '
')
    return text


@staticmethod
def pattern_to_char(n):
    """Returns a character corresponding to a 6-pixel pattern"""
    return chr(n + 63)


def __im_clone__():
    """Return a clone of itself.

        Important: This method produces a deep clone of itself in `transient`
        mode.
        """


@classmethod
def sensible_default(cls, num_workers: int, dimension: int) ->'Pruning':
    """ Very conservative pruning
        - keep at least 100 elements, or 7 times num_workers, whatever is biggest
        - keep at least 3 x min_len, or up to 10 x min_len if it does not exceed 1gb of data

        Parameters
        ----------
        num_workers: int
            number of evaluations which will be run in parallel at once
        dimension: int
            dimension of the optimization space
        """
    min_len = max(100, 7 * num_workers)
    max_len_1gb = 1024 ** 3 // (dimension * 8 * 2)
    max_len = max(3 * min_len, min(10 * min_len, max_len_1gb))
    return cls(min_len, max_len)


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 icon_for_field(fieldname):
    """Helper method for translating from field names to
    prototype classes"""
    if '.' in fieldname:
        fieldname = fieldname.split('.')[-1]
    default = 'icon-right-open'
    mapping = {'email': 'icon-mail', 'telephone': 'icon-phone', 'mobile':
        'icon-phone', 'address': 'icon-home', 'department': 'icon-building',
        'time_zone': 'icon-clock', 'primary_location': 'icon-globe'}
    return mapping.get(fieldname, default)


@classmethod
def get_icon(klass):
    """
        Default getter function - returns the `icon` property
        """
    return klass.icon


def Flatten(data=None, name=None, attr=None, out=None, **kwargs):
    """Flattens the input array into a 2-D array by collapsing the higher dimensions.
    .. note:: `Flatten` is deprecated. Use `flatten` instead.
    For an input array with shape ``(d1, d2, ..., dk)``, `flatten` operation reshapes
    the input array into an output array of shape ``(d1, d2*...*dk)``.
    Note that the behavior of this function is different from numpy.ndarray.flatten,
    which behaves similar to mxnet.ndarray.reshape((-1,)).
    Example::
        x = [[
            [1,2,3],
            [4,5,6],
            [7,8,9]
        ],
        [    [1,2,3],
            [4,5,6],
            [7,8,9]
        ]],
        flatten(x) = [[ 1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9.],
           [ 1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9.]]

    Defined in src/operator/tensor/matrix_op.cc:L250

    Parameters
    ----------
    data : Symbol
        Input array.

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

    Returns
    -------
    Symbol
        The result symbol.

    Examples
    --------
    Flatten is usually applied before `FullyConnected`, to reshape the 4D tensor
    produced by convolutional layers to 2D matrix:

    >>> data = Variable('data')  # say this is 4D from some conv/pool
    >>> flatten = Flatten(data=data, name='flat')  # now this is 2D
    >>> SymbolDoc.get_output_shape(flatten, data=(2, 3, 4, 5))
    {'flat_output': (2L, 60L)}

    >>> test_dims = [(2, 3, 4, 5), (2, 3), (2,)]
    >>> op = Flatten(name='flat')
    >>> for dims in test_dims:
    ... x = test_utils.random_arrays(dims)
    ... y = test_utils.simple_forward(op, flat_data=x)
    ... y_np = x.reshape((dims[0], np.prod(dims[1:]).astype('int32')))
    ... print('%s: %s' % (dims, test_utils.almost_equal(y, y_np)))
    (2, 3, 4, 5): True
    (2, 3): True
    (2,): True
    """
    return 0,


def non_single_character_dividers():
    """
    Get a list of all the "blacklisted" dividers.

    These dividers are not made of a single character.
    Some examples of this include:

    * Divider 18 - :code:`( ͡° ͜ʖ ͡°)`
    * Divider 33 - :code:`^,^,^,^,^,^,`
    * Divider 34 - :code:`&*&*&*&*&*&*`

    :return: A list of divider IDs.
    :rtype: List[int]
    """
    return [18, 19, 22, 33, 34, 35, 222, 223, 224, 226, 233, 234, 242, 244]


@staticmethod
def _power_of_two_range(start):
    """
        A generator that continually returns the next power of two value.
        E.g. 1, 2, 4, 8, 16, 32, etc.

        :param start: The value to start at.
        """
    while True:
        yield start
        start <<= 1


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 get(isamAppliance, check_mode=False, force=False):
    """
    Retrieving the general configuration
    """
    return isamAppliance.invoke_get('Retrieving the general configuration',
        '/isam/packet_tracing')


def resume():
    """
        Invoked when notification for this listener is being resumed.

        Any actions taken by L{suspend} may be reversed by this method.
        """


def metaDataStr(datObj):
    """
    Returns the meta data of an :class:`pyilt2.dataset` object as a *string*, like::

        Property:
          Specific density
        Reference:
          "Densities, isobaric expansivities and isothermal compressibilities [...].",
          Krolikowska, M.; Hofman, T. (2012) Thermochim. Acta 530, 1-6.
        Component(s):
          1) 1-ethyl-3-methylimidazolium thiocyanate
        Method: Vibrating tube method
        Phase(s): Liquid
        Data columns:
          1) Temperature/K
          2) Pressure/kPa
        ...

    :param datObj: dataset object
    :type datObj: :class:`pyilt2.dataset`
    :return: meta data
    :rtype: str
    """
    out = 'Property:\n  {0:s}\n'.format(datObj.setDict['title'].split(':')[
        -1].strip())
    out += 'Reference:\n'
    out += '  "{0:s}",\n'.format(datObj.setDict['ref']['title'])
    out += '  {0:s}\n'.format(datObj.setDict['ref']['full'])
    out += 'Component(s):\n'
    for i in range(0, datObj.numOfComp):
        out += '  {0:d}) {1:s}\n'.format(i + 1, datObj.listOfComp[i])
    if datObj.setDict['expmeth']:
        out += 'Method: {0:s}\n'.format(datObj.setDict['expmeth'])
    out += 'Phase(s): {0:s}\n'.format(', '.join(datObj.setDict['phases']))
    if datObj.setDict['solvent']:
        out += 'Solvent: {0:s}\n'.format(datObj.setDict['solvent'])
    out += 'Data columns:\n'
    for i in range(0, len(datObj.headerList)):
        out += '  {0:d}) {1:s}\n'.format(i + 1, datObj.headerList[i])
    out += 'Data points: {0:d}\n'.format(datObj.np)
    out += 'ILT2 setid: {0:s}\n'.format(datObj.setid)
    return out


def dirlog(d):
    """Obtain a manifest storage instance for a tree."""


def middle(y):
    """ Returns the middle column from 2d matrix """
    return y[:, (y.shape[1] // 2)]


def get_listOfReactions(model):
    """
    return list of reactions of a SBML model
    """
    listOfReactions = None
    for e in model:
        if e.tag[0] == '{':
            uri, tag = e.tag[1:].split('}')
        else:
            tag = e.tag
        if tag == 'listOfReactions':
            listOfReactions = e
            break
    return listOfReactions


def warn_with_traceback(message, category, filename, lineno, file=None,
    line=None):
    """

    See: https://stackoverflow.com/a/22376126/230468

    Add this to use: `warnings.showwarning = warn_with_traceback`

    """
    import traceback
    import warnings
    import sys
    log = file if hasattr(file, 'write') else sys.stderr
    traceback.print_stack(file=log)
    log.write(warnings.formatwarning(message, category, filename, lineno, line)
        )
    return


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


def _clamp(coordinate):
    """restrict a single coordinate to 0-255"""
    return max(0, min(255, coordinate))


def draw_head_none(context):
    """
    Draw an 'x' on the line end to indicate no navigability at
    association head.
    """
    cr = context.cairo
    cr.move_to(6, -4)
    cr.rel_line_to(8, 8)
    cr.rel_move_to(0, -8)
    cr.rel_line_to(-8, 8)
    cr.stroke()
    cr.move_to(0, 0)


@staticmethod
def is_duplication() ->bool:
    """Whether the rule is a duplication rule or not

        Returns
        ----------
        is_duplication : bool
            Whether the rule is a duplication rule or not
        """
    return False


def grouper(gen, batch_size=4):
    """Group together elements of an iterable without padding remainder."""
    while True:
        batch = []
        for i in range(batch_size):
            try:
                batch.append(next(gen))
            except StopIteration:
                if len(batch) > 0:
                    yield batch
                raise StopIteration
        yield batch


def formula_2013_01_01(foyer_fiscal, period):
    """
        Cf. docstring période précédente
        """
    v1_assiette_csg_plus_values = foyer_fiscal('assiette_csg_plus_values',
        period)
    v2_rfr_plus_values_hors_rni = foyer_fiscal('rfr_plus_values_hors_rni',
        period)
    f3we = foyer_fiscal('f3we', period)
    f3vz = foyer_fiscal('f3vz', period)
    f3sb = foyer_fiscal('f3sb', period)
    f3vl = foyer_fiscal('f3vl', period)
    f3wb = foyer_fiscal('f3wb', period)
    intersection_v1_v2 = f3we + f3vz
    ajouts_de_rev_cat_pv = f3sb + f3vl + f3wb
    return (v1_assiette_csg_plus_values + v2_rfr_plus_values_hors_rni -
        intersection_v1_v2 + ajouts_de_rev_cat_pv)


def ktoe_to_twh(ktoe):
    """Conversion of ktoe to TWh

    Arguments
    ----------
    ktoe : float
        Energy demand in ktoe

    Returns
    -------
    data_gwh : float
        Energy demand in TWh

    Notes
    -----
    https://www.iea.org/statistics/resources/unitconverter/
    """
    data_twh = ktoe * 0.01163
    return data_twh


@classmethod
def from_data(cls, data):
    """Create a new, populated message from some data

        This factory method is identical to doing the following, it just takes
        one line instead of two and looks nicer in general::

            m = MyMessage()
            m.unpack(data)

        Can be rewritten as just::

            m = MyMessage.from_data(data)

        """
    m = cls()
    m.unpack(data)
    return m


@classmethod
def from_boto_server_certificate(cls, server_certificate
    ) ->'IAMServerCertificate':
    """
        Converts an ServerCertificate as returned by server_certificates.all()
        """
    metadata = server_certificate.server_certificate_metadata
    certificate_body = server_certificate.certificate_body
    certificate_chain = server_certificate.certificate_chain
    return cls(metadata, certificate_body, certificate_chain)


def getvar(request, field_name, setsession=False):
    """Check field in POST/GET request and return field value
    if there is value you can also save a session variable
    """
    if request.method == 'GET':
        if field_name in request.GET:
            val = request.GET[field_name]
        else:
            val = ''
    if request.method == 'POST':
        if field_name in request.POST:
            val = request.POST[field_name]
        else:
            val = ''
    if setsession and val and val != '':
        request.session['session_' + field_name] = val
    return val


def banner():
    """Print a message when the terminal initializes

    """
    pass


@classmethod
def from_dict(cls, parameters: dict):
    """
        Создать экземпляр из словаря
        """
    return cls(**parameters)


def parse_solver_setting(s):
    """Parse a string containing a solver setting"""
    try:
        key, value = s.split('=', 1)
    except ValueError:
        key, value = s, 'yes'
    if key in ('rational', 'integer', 'quadratic'):
        value = value.lower() in ('1', 'yes', 'true', 'on')
    elif key in ('threads',):
        value = int(value)
    elif key in ('feasibility_tolerance', 'optimality_tolerance',
        'integrality_tolerance'):
        value = float(value)
    return key, value


def validate_vcf(path):
    """
    Validate VCF file

    Parameters
    ----------
    path : str
        File to check
    """
    raise NotImplementedError()


@staticmethod
def time_base_to_nr3(n, s):
    """
        converts the time base into the nr3 format
        Args:
            n: time base value (1, 2, 5)
            s: time base (ns, us, ms, s)

        Returns:
            a string in nr3 format that represents the time for example, 1.0E-9, 2.0E-9, 5.0E-9, ... 1.0E+00, 2.0E+00, 5.0E+00)

        """
    if s == 'ns':
        nr3 = 'E-9'
    if s == 'us':
        nr3 = 'E-6'
    if s == 'ms':
        nr3 = 'E-3'
    if s == 's':
        nr3 = 'E+00'
    return str(n) + '.0' + nr3


@staticmethod
def _eval_if_not_number(v, feed_dict):
    """ If v is not float (i.e. v is :class:`Express`), returns an evaluated value.

        Args:
            v (float/int/:class:`Coefficient`):
                The value to be evaluated.
            feed_dict (dict[str, float]):
                The value of :class:`Placeholder`.

        Returns:
            float: Evaluated value of the input :obj:`v`:
        """
    if isinstance(v, float) or isinstance(v, int):
        return v
    else:
        return v.evaluate(feed_dict)


def slots(n, k, normalized=False):
    """Generates distributions of n identical items into k distinct slots.

    A generator over distributions of n indistinguishable items into k
    distinguishable slots, where each slot can hold up to n items.
    Selection of items is done without replacement, and the order within the
    slots cannot matter since the items are indistinguishable.

    The number of distributions is (n + k - 1)! / n! / (k-1)!

    Parameters
    ----------
    n : int
        The number of indistinguishable items.
    k : int
        The number of distinguishable slots.
    normalized : bool
        If True, then we divide each term in the tuple by the number of items.
        The default value is False.

    Yields
    ------
    t : tuple
        A tuple of length k where each element is an integer representing
        the number of indistinguishable items within the slot.

    Examples
    --------
    >>> list(slots(3,2))
    [(0, 3), (1, 2), (2, 1), (3, 0)]

    """
    seq, i = [n] * k + [0], k
    if normalized:
        nf = float(n)
        while i:
            yield tuple((seq[i] - seq[i + 1]) / nf for i in range(k))
            i = seq.index(0) - 1
            seq[i:k] = [seq[i] - 1] * (k - i)
    else:
        while i:
            yield tuple(seq[i] - seq[i + 1] for i in range(k))
            i = seq.index(0) - 1
            seq[i:k] = [seq[i] - 1] * (k - i)


@classmethod
def diamond(cls, a):
    """Factory for Diamond type FCC like Si and Ge

        :param a: unit cell length
        """
    self = cls.cubic(a, lattice_type='F')
    self.selection_rules.append(lambda h, k, l: not (h % 2 == 0 and k % 2 ==
        0 and l % 2 == 0 and (h + k + l) % 4 != 0))
    return self


def index_by_modifier_as_list(sequence, modifier, target_index=None):
    """
    Create an index of objects in a sequence. The index's key will be provider by the modifier. Values are lists,
    so keys are not expected to be unique.

    The modifier is called for each object with that object as an argument and is supposed to
    return the key to be used for that object in the index.

    :param sequence: sequence of objects (list, tuple or otherwise iterable object)
    :param modifier: callable that takes an object and returns a hashable value.
    :param target_index: dict that will be populated with objects from the sequence (optional)
    :return: dict
    """
    index = target_index if target_index is not None else dict()
    for element in sequence:
        key = modifier(element)
        index.setdefault(key, [])
        index[key].append(element)
    return index


@classmethod
def has_resuming(cls):
    """Returns whether it supports to resume the fetch process.

        :returns: this backend supports items resuming
        """
    return True


def _html(tag):
    """
    Prefixes the given ``tag`` with the XHTML prefix. Block files saved with newer versions of App Inventor will have
    this XML namespace prepended when read with the ETree framework.
    :param tag: An XML element tag
    :type tag: basestring
    :return: A new string prefixed with the XHTML prefix.
    :rtype: str or unicode
    """
    return '{http://www.w3.org/1999/xhtml}' + tag


def pyplot_draw_point_cloud(points, output_filename):
    """ points is a Nx3 numpy array """
    import matplotlib.pyplot as plt
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    ax.scatter(points[:, (0)], points[:, (1)], points[:, (2)])
    ax.set_xlabel('x')
    ax.set_ylabel('y')
    ax.set_zlabel('z')


def register_world(world_id):
    """ Register a new simulation world

    At the moment simulation of only one world at a time is supported, so this calling this function will discard
    the previous world.

    Parameters
    ----------
    world_id
        The ID of the world
    -------
    """
    global current_world_ID
    current_world_ID = world_id


def checkUserManage(worksheet, request, redirect=True):
    """ Checks if the current user has granted access to the worksheet
        and if has also privileges for managing it. If the user has no
        granted access and redirect's value is True, redirects to
        /manage_results view. Otherwise, does nothing
    """
    allowed = worksheet.checkUserManage()
    if allowed == False and redirect == True:
        destination_url = worksheet.absolute_url() + '/manage_results'
        request.response.redirect(destination_url)


@classmethod
def remove_by_example(cls, collection, example_data, wait_for_sync=None,
    limit=None):
    """
            This will find all documents in the collection that match the specified example object.

            Note: the limit attribute is not supported on sharded collections. Using it will result in an error.
            The options attributes waitForSync and limit can given yet without an ecapsulation into a json object.
            But this may be deprecated in future versions of arango

            Returns result dict of the request.

            :param collection Collection instance
            :param example_data An example document that all collection documents are compared against.

            :param wait_for_sync  if set to true, then all removal operations will instantly be synchronised to disk.
            If this is not specified, then the collection's default sync behavior will be applied.

            :param limit an optional value that determines how many documents to replace at most. If limit is
            specified but is less than the number of documents in the collection, it is undefined which of the
            documents will be replaced.
        """
    kwargs = {'options': {'waitForSync': wait_for_sync, 'limit': limit}}
    return cls._construct_query(name='remove-by-example', collection=
        collection, example=example_data, result=False, **kwargs)


def fitsheader2dict(hdr, ext=0):
    """
    Convert a fits header object into a dict.  A dict provides more expected
    interface to the data but cannot be written back to a fits file without
    transformation.
    """
    hdict = {}
    for key in hdr:
        hdict[key.lower()] = hdr[key]
    return hdict


@staticmethod
def get_structure_name_and_type(rt_struct_ds):
    """Stripped down version of dicompylercore.dicomparser.GetStructures"""
    structures = {}
    if 'StructureSetROISequence' in rt_struct_ds:
        for item in rt_struct_ds.StructureSetROISequence:
            data = {}
            number = int(item.ROINumber)
            data['id'] = number
            data['name'] = item.ROIName
            structures[number] = data
    if 'RTROIObservationsSequence' in rt_struct_ds:
        for item in rt_struct_ds.RTROIObservationsSequence:
            number = item.ReferencedROINumber
            if number in structures:
                structures[number]['type'] = item.RTROIInterpretedType
    return structures


def get_code_cell(code, hidden=False):
    """Code cell containing `code` that may be `hidden`."""
    return {'cell_type': 'code', 'execution_count': 0, 'metadata': {
        'hide_input': hidden, 'trusted': True}, 'source': code, 'outputs': []}


def formula_2008_01_01(foyer_fiscal, period, parameters):
    """
        Prelèvement libératoire sur les revenus du capital
        """
    f2da = foyer_fiscal('f2da', period)
    f2dh = foyer_fiscal('f2dh', period)
    f2ee = foyer_fiscal('f2ee', period)
    param_pfl_av = (parameters(period).taxation_capital.pfl_av.
        bons_ou_contrats_de_capitalisation_et_placements_de_meme_nature_assurance_vie_lors_du_denouement_du_contrat
        )
    param_pfl = parameters(period).taxation_capital.pfl
    return -(f2da * param_pfl.dividendes + f2ee * param_pfl.
        autres_produits_de_placement_a_revenu_fixe_comptes_sur_livrets_creances_depots_cautionnement_et_comptes_courants
        .courus_entre_le_1_1_95_et_apres + f2dh * param_pfl_av.
        souscrits_apres_le_1_1_90_et_le_pour_une_duree_de.
        duree_8_ans_et_plus_pour_les_produits_acquis_apres_le_01_01_1998_avec_abattement_sur_l_ir_5
        )


def chomp(s):
    """Remove line terminator if it exists.
    """
    if s[-2:] == b'\r\n':
        return s[:-2]
    if s[-1:] == b'\r' or s[-1:] == b'\n':
        return s[:-1]
    return s


@staticmethod
def read_file(path):
    """
        Read tree model from a file.

        Parameters
        ----------

        path : String

            File path.

        Returns
        -------

        String

            The tree model content.
        """
    fd = open(path, 'r')
    data = fd.read()
    fd.close()
    return data


def _resource_endpoint(object_uri):
    """Determine the resource name and whether it is the plural endpoint from
    the specified `object_uri`. Returns `(None, None)` for the root URL plural
    endpoint.
    """
    obj_parts = object_uri.split('/')
    plural_endpoint = len(obj_parts) % 2 == 0
    if plural_endpoint:
        obj_parts = obj_parts[:-1]
    if len(obj_parts) <= 2:
        return '', False
    resource_name = obj_parts[-2]
    resource_name = resource_name.rstrip('s')
    return resource_name, plural_endpoint


def create_snapshot_repo(client, repo_name, s3_bucket):
    """
    Creates a repo to store ES snapshots on

    info about snapshots on AWS
    https://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/es-managedomains-snapshots.html
    """
    snapshot_body = {'type': 's3', 'settings': {'bucket': s3_bucket,
        'region': 'us-east-1', 'role_arn':
        'arn:aws:iam::643366669028:role/S3Roll'}}
    return client.snapshot.create_repository(repository=repo_name, body=
        snapshot_body)


def Odds(p):
    """Computes odds for a given probability.

    Example: p=0.75 means 75 for and 25 against, or 3:1 odds in favor.

    Note: when p=1, the formula for odds divides by zero, which is
    normally undefined.  But I think it is reasonable to define Odds(1)
    to be infinity, so that's what this function does.

    p: float 0-1

    Returns: float odds
    """
    if p == 1:
        return float('inf')
    return p / (1 - p)


def root_group(h5Dataset):
    """ Calls HDF5 groups parent recursively until HDF5 group parent is '/'

    :param h5Dataset: HDF5 to from which search must start
    :return: HDF5 root group (i.e. if h5Dataset is /path/to/dataset, it returns /path h5py Group)
    """
    root = h5Dataset.parent
    while root.parent.name != '/':
        root = root.parent
    return root


def merge_dicts(*dict_args):
    """
    Given any number of dicts, shallow copy and merge into a new dict,
    precedence goes to key value pairs in latter dicts.
    """
    result = {}
    for dictionary in dict_args:
        result.update(dictionary)
    return result


def timedelta_to_seconds(td):
    """Equivalent to ``td.total_seconds()`` (introduced in Python 2.7)."""
    return td.total_seconds()


@staticmethod
def add_callback(callback, control_instance):
    """ Method to add a callback to the control instance when a 'userModification'
        signal is emited.

        Parameters
        ----------
        callback: @function (mandatory)
            the function that will be called when a 'userModification' signal is
            emited.
        control_instance: QWidget (mandatory)
            the control widget we want to validate
        """
    control_instance.path.userModification.connect(callback)


def after_set(changed):
    """ Perform operations after a successful set.  ``changed`` is the
        value returned from the ``set`` method.

        The default propertysheet implementation sends an ObjectModified event
        if the ``changed`` value is not ``False.``
        """


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

    The natural logarithm is logarithm in base *e*, so that ``log(exp(x)) = x``

    The storage type of ``log`` output is always dense

    Defined in src/operator/tensor/elemwise_unary_op_logexp.cc:L76

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

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

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


def itoa(value, alphabet, padding=None):
    """
    Converts an int value to a str, using the given alphabet.
    Padding can be computed as: ceil(log of max_val base alphabet_len)
    """
    if value < 0:
        raise ValueError('Only positive numbers are allowed')
    elif value == 0:
        return alphabet[0]
    result = ''
    base = len(alphabet)
    while value:
        value, rem = divmod(value, base)
        result = alphabet[rem] + result
    if padding:
        fill = max(padding - len(result), 0)
        result = alphabet[0] * fill + result
    return result


def rename_projector_message_slides(apps, schema_editor):
    """
    Renames projector message slides in projector model.

    Old name 'core/projectormessage', new name 'core/projector-message'.
    """
    Projector = apps.get_model('core', 'Projector')
    for projector in Projector.objects.all():
        new_config = {}
        for key, value in projector.config.items():
            new_config[key] = value
            if value['name'] == 'core/projectormessage':
                new_config[key]['name'] = 'core/projector-message'
        projector.config = new_config
        projector.save(skip_autoupdate=True)


def describe_limits():
    """
    Returns the current provisioned-capacity limits for your AWS account in a region, both for the region as a whole and for any one DynamoDB table that you create there.
    When you establish an AWS account, the account has initial limits on the maximum read capacity units and write capacity units that you can provision across all of your DynamoDB tables in a given region. Also, there are per-table limits that apply when you create a table there. For more information, see Limits page in the Amazon DynamoDB Developer Guide .
    Although you can increase these limits by filing a case at AWS Support Center , obtaining the increase is not instantaneous. The DescribeLimits action lets you write code to compare the capacity you are currently using to those limits imposed by your account so that you have enough time to apply for an increase before you hit a limit.
    For example, you could use one of the AWS SDKs to do the following:
    This will let you see whether you are getting close to your account-level limits.
    The per-table limits apply only when you are creating a new table. They restrict the sum of the provisioned capacity of the new table itself and all its global secondary indexes.
    For existing tables and their GSIs, DynamoDB will not let you increase provisioned capacity extremely rapidly, but the only upper limit that applies is that the aggregate provisioned capacity over all your tables and GSIs cannot exceed either of the per-account limits.
    The DescribeLimits Request element has no content.
    See also: AWS API Documentation

    Examples
    The following example returns the maximum read and write capacity units per table, and for the AWS account, in the current AWS region.
    Expected Output:

    :example: response = client.describe_limits()

    :rtype: dict
    :return: {
        'AccountMaxReadCapacityUnits': 123,
        'AccountMaxWriteCapacityUnits': 123,
        'TableMaxReadCapacityUnits': 123,
        'TableMaxWriteCapacityUnits': 123
    }

    """
    pass


def dict_slice(dict_input, start, end) ->dict:
    """
    take slice for python dict
    :param dict_input: a dict for slicing
    :param start: start position for splicing
    :param end: end position for slicing
    :return: the sliced dict
    """
    keys = dict_input.keys()
    dict_slice = {}
    for k in keys[start:end]:
        dict_slice[k] = dict_input[k]
    return dict_slice


def npv(ico, nci, r, n):
    """ This capital budgeting function computes the net present
    value on a cash flow generating investment.
    ico = Initial Capital Outlay
    nci = net cash inflows per period
    r = discounted rate
    n = number of periods
    Example: npv(100000, 15000, .03, 10)
    """
    pv_nci = 0
    for x in range(n):
        pv_nci = pv_nci + nci / (1 + r) ** (x + 1)
    return pv_nci - ico


def incorrect(call_a, call_b):
    """
    Informs the user that the order is incorrect and provides the call numbers
    so the user can do a manual check.

    :param call_a:  first call number

    :param call_b:  second call number
    """
    print('_________________________________')
    print('|                                |')
    print('|             Incorrect          |')
    print('|                                |')
    print('|________________________________|')
    print(call_a)
    print(call_b)
    print()


def _client_id(request):
    """
    Gets the value of the Client-ID header from the request.

    We know the Client-ID must be decodable as ASCII because
    Cloud Queues requires it to be submitted as a UUID. Mimic
    is not so strict, but requiring ASCII is ok.
    """
    return request.requestHeaders.getRawHeaders(b'client-id')[0].decode('ascii'
        )


def add_keys(apps, schema_editor):
    """
    We can't import the Post model directly as it may be a newer
    version than this migration expects. We use the historical version.
    """
    Setting = apps.get_model('settings', 'Setting')
    key = ''
    try:
        key = 'BANK_MELLI_MERCHENT_CODE'
        Setting.objects.get(key=key)
    except Exception:
        Setting.objects.create(title='مرچنت کد بانک ملی', key=key, value='',
            value_type='s', is_show=False, is_variable_in_home=False)
    try:
        key = 'BANK_MELLI_TERMINAL_CODE'
        Setting.objects.get(key=key)
    except Exception:
        Setting.objects.create(title='ترمینال کد بانک ملی', key=key, value=
            '', value_type='s', is_show=False, is_variable_in_home=False)
    try:
        key = 'BANK_MELLI_SECRET_KEY'
        Setting.objects.get(key=key)
    except Exception:
        Setting.objects.create(title=' کلید خصوصی بانک ملی', key=key, value
            ='', value_type='s', is_show=False, is_variable_in_home=False)


def cancel():
    """
        Cancel the scheduled call.

        @raises twisted.internet.error.AlreadyCalled: if the call has already
            happened.
        @raises twisted.internet.error.AlreadyCancelled: if the call has already
            been cancelled.
        """


@classmethod
def fromExisting(cls, new_id, existing):
    """"Create a copy from an existing object, with a new ID

        :param new_id: New key to use
        :param existing: Existing object to copy values from
        :return: New mapper object
        """
    if not isinstance(existing, cls):
        raise ValueError("Can't copy from type {!r}".format(existing.__class__)
            )
    args, values = zip(*existing.to_dict().items())
    new = cls(existing._db, new_id)
    new._parse(args, values)
    return new


def convert_to_kw(value: float, precision: int=1) ->float:
    """Converts watt to kilowatt and rounds to precision"""
    if precision == -1:
        return value / 1000
    else:
        return round(value / 1000, precision)


@staticmethod
def get_ctr_name(filename):
    """Extracts the name of the constrains file name."""
    bracket_idx = filename.find('(')
    if bracket_idx == -1:
        print("+++ Error: no '(' in constraints [%s]", filename)
        assert False
    return filename[:bracket_idx]


def dict_from_cookiejar(cj):
    """Returns a key/value dictionary from a CookieJar.

    :param cj: CookieJar object to extract cookies from.
    """
    cookie_dict = {}
    for cookie in cj:
        cookie_dict[cookie.name] = cookie.value
    return cookie_dict


def blend(arr1, arr2, alpha=0.5):
    """Blend 2 arrays together, mixing with alpha.

	Parameters
	----------
	arr1:array
		Image 1.
	arr2:array
		Image 2.
	alpha:float
		Higher alpha makes image more like image 1.

	Returns
	-------
	array
		Resulting image.

	"""
    return alpha * arr1 + (1.0 - alpha) * arr2


def atmospheric_correction(h):
    """
    Calculate the atmospheric correction.

    Parameters
    ----------
    h : numpy array
        Heights relative to elipsoid (GPS heights).

    Returns
    -------
    gATM : numpy array.
        Atmospheric correction

    """
    gATM = 0.874 - 9.9 * 1e-05 * h + 3.56 * 1e-09 * h ** 2
    return gATM


def height_from_height_wrist(segment_length):
    """
    Calculates body height based on the height of the elbows from the ground

    args:
        segment_length (float): height of the wrists

    Returns:
        float: total body height
    """
    if segment_length <= 0:
        raise ValueError('segment_length must be > 0')
    return segment_length / 0.485


def make_trips_diary(valid_segments, missing_segments):
    """
    Zips together lists of valid segments and missing segments in timestamp order
    into continuous trip diary.
    """
    if not missing_segments:
        return valid_segments
    trips = []
    missing_iter = iter(missing_segments)
    missing_test_segment = next(missing_iter)
    trip_idx = 0
    missing_idxs = []
    for valid_segment in valid_segments:
        if not missing_test_segment:
            trips.append(valid_segment)
            trip_idx += 1
        elif missing_test_segment and valid_segment[0
            ].timestamp_UTC < missing_test_segment[0].timestamp_UTC:
            trips.append(valid_segment)
            trip_idx += 1
        else:
            trips.append(missing_test_segment)
            missing_idxs.append(trip_idx)
            trip_idx += 1
            trips.append(valid_segment)
            trip_idx += 1
            missing_test_segment = next(missing_iter, None)
    diary = {'trips': trips, 'missing': missing_idxs}
    return diary


def combine_words(first_word, following_words):
    """
        Combines the first word and following words into one regex
        Sample:
        first_word (word1|word2|...|wordx)
    """
    if len(following_words) == 1:
        idiom_regex = '{} {}'.format(first_word, ''.join(following_words))
    else:
        idiom_regex = '{} ({})'.format(first_word, '|'.join(following_words))
    if not idiom_regex.isspace():
        return idiom_regex


def is_followed(item_type, item_id, user_id=None):
    """Does <user_id> follow <item_type> <item_id>?"""


def bC_H_CO3_HMW84(T, P):
    """c-a: hydrogen carbonate [HMW84]."""
    b0 = 0.0
    b1 = 0.0
    b2 = 0.0
    C0 = 0
    C1 = 0
    alph1 = 2
    alph2 = -9
    omega = -9
    valid = T == 298.15
    return b0, b1, b2, C0, C1, alph1, alph2, omega, valid


def export_image_data(item):
    """Export image item data to file"""
    from plotpy.gui.widgets.qthelpers import exec_image_save_dialog
    exec_image_save_dialog(item.plot(), item.data)


@classmethod
def load(cls, config_file):
    """ Load experiment parameters from a JSON configuration file

        Parameters
        ----------
        config_file: string
            path to a JSON configuration file

        Returns
        -------
        dictionary (or list of dictionaries) of parameters to pass to a behavior
        """
    try:
        import simplejson as json
    except ImportError:
        import json
    with open(config_file, 'rb') as config:
        parameters = json.load(config)
    return parameters


@classmethod
def get_importers(cls):
    """Returns a dict that maps nicknames for importers to classmethods.

        :rtype: dict
        """
    return {'blackboard': cls.import_blackboard_zip, 'multiple': cls.
        import_multiple, 'single': cls.import_single, 'repo': cls.import_repo}


def lower(series):
    """Test that the data items are all lowercase."""
    return series.str.islower()


@classmethod
def identity(cls, dtype=None):
    """Creates an identity Matrix.
        """
    return cls(cls._module.create_identity(dtype), dtype)


def show_warning(message):
    """Show warning using Tkinter if available"""
    try:
        import Tkinter, tkMessageBox
        root = Tkinter.Tk()
        root.withdraw()
        tkMessageBox.showerror('Spyder', message)
    except ImportError:
        pass
    raise RuntimeError(message)


def check_attachment_permission(action, username, resource, perm):
    """Return the usual `True`/`False`/`None` security policy
           decision appropriate for the requested action on an
           attachment.

            :param action: one of ATTACHMENT_VIEW, ATTACHMENT_CREATE,
                                  ATTACHMENT_DELETE
            :param username: the user string
            :param resource: the `~trac.resource.Resource` for the
                             attachment. Note that when
                             ATTACHMENT_CREATE is checked, the
                             resource ``.id`` will be `None`.
            :param perm: the permission cache for that username and resource
            """


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

        :param UploadSessionFinishError val:
        :rtype: UploadSessionFinishBatchResultEntry
        """
    return cls('failure', val)


@classmethod
def hascreds(cls, config):
    """Determine if the given configuration has proper credentials
        Parameters
        ----------
        cls : class
            A Session class.
        config : dict
            GDAL configuration as a dict.
        Returns
        -------
        bool
        """
    return 'SWIFT_STORAGE_URL' in config and 'SWIFT_AUTH_TOKEN' in config


def myreplace(astr, thefind, thereplace):
    """in string astr replace all occurences of thefind with thereplace"""
    alist = astr.split(thefind)
    new_s = alist.split(thereplace)
    return new_s


def _connect_seg_to_poly(poly_verts, seg, tol):
    """Connect a LineSegment to a list of polyline vertices.

    If successful, a Point will be appended to the poly_verts list and True
    will be returned. If not successful, the poly_verts list will remain unchanged
    and False will be returned.

    Args:
        poly_verts: An ordered list of Points to which the segment should
            be connected.
        seg: A LineSegment to connect to the poly_verts.
        tol: The tolerance to be used for connecting the line.
    """
    p1, p2 = seg.p1, seg.p2
    if poly_verts[-1].is_equivalent(p1, tol):
        poly_verts.append(p2)
        return True
    elif poly_verts[0].is_equivalent(p2, tol):
        poly_verts.insert(0, p1)
        return True
    elif poly_verts[-1].is_equivalent(p2, tol):
        poly_verts.append(p1)
        return True
    elif poly_verts[0].is_equivalent(p1, tol):
        poly_verts.insert(0, p2)
        return True
    return False


def gear_for_speed_profiles(gs, curr_speed, current_gear, gear_cnt,
    clutch_duration=5):
    """
    Return the gear that must be used and the clutch condition.

    :param gs:
        Gear limits.
    :type gs: list

    :param curr_speed:
        Current speed.
    :type curr_speed: int

    :param current_gear:
        Current speed.
    :type current_gear: int

    :param gear_cnt:
        Gear count.
    :type gear_cnt: int

    :param clutch_duration:
        Clutch duration in sim step
    :type clutch_duration: int

    :return:
        Current gear & gear count
    :rtype: int, int
    """
    up_shift_offs = 0.0
    downshift_off = 0.1
    gear_limits = [0]
    gear_limits.extend(gs)
    gear_limits.append(200)
    if gear_limits[current_gear - 1] - gear_limits[current_gear - 1
        ] * downshift_off <= curr_speed < gear_limits[current_gear
        ] + gear_limits[current_gear] * up_shift_offs:
        if gear_cnt == 0:
            return current_gear, gear_cnt
        else:
            gear_cnt -= 1
            return current_gear, gear_cnt
    else:
        itr = 1
        gear_search = 1
        while itr == 1 and gear_search < len(gear_limits):
            if gear_limits[gear_search - 1] <= curr_speed < gear_limits[
                gear_search]:
                gear_cnt = clutch_duration
                current_gear = gear_search
                itr = 0
            else:
                gear_search += 1
        return current_gear, gear_cnt


def extendedColorFromQColor(col):
    """Make an extended color #RRGGBBAA or #RRGGBB string."""
    if col.alpha() == 255:
        return str(col.name())
    else:
        return '#%02x%02x%02x%02x' % (col.red(), col.green(), col.blue(),
            col.alpha())


def getItems():
    """Returns the items.
        """


def infer_layout(val):
    """
    Infer layout of the given memoryview *val*.
    """
    return 'C' if val.c_contiguous else 'F' if val.f_contiguous else 'A'


def str_split(strng, sep, pos):
    """https://stackoverflow.com/a/52008134/3521099"""
    strng = strng.split(sep)
    return sep.join(strng[:pos]), sep.join(strng[pos:])


def weekend_offset(date, flag=False):
    """internal helper function"""
    if date.weekday() == 5:
        return 2 if flag else 1
    return 1 if flag else 2


def to_selector(labels):
    """
  Transfer Labels to selector.
  """
    parts = []
    for key in labels.keys():
        parts.append('{0}={1}'.format(key, labels[key]))
    return ','.join(parts)


@classmethod
def header_size(cls, header_chunk):
    """Return the total header size in chunks, given the first chunk"""
    head_type = cls.header_type(header_chunk)
    return cls.header_size_by_desc[head_type]


def constraint_to_dict(constraint):
    """
    Tries to convert the object to a dictionary using its
    json() method if it exists.
    Otherwise, it assumes that already is a dictionary and return it as is.
    """
    try:
        return constraint.json()
    except AttributeError:
        return constraint


def parse_timestamp(timestamp):
    """Convert hexagon timestamp to integer (time in milliseconds)."""
    return int(timestamp, 16)


@staticmethod
def is_within_content_length_limit(payload, api_config):
    """
        Check that the message content is within the configured length limit.
        """
    length_limit = api_config.get('content_length_limit')
    if length_limit is not None and payload['content'] is not None:
        content_length = len(payload['content'])
        if content_length > length_limit:
            return 'Payload content too long: %s > %s' % (content_length,
                length_limit)
    return None


def add_speed(df):
    """average miles/hour"""
    df['speed'] = df['Trip_distance'] / (df['duration_min'] / 60)
    return df


@classmethod
def get_by_id(cls, context, allocation_id):
    """Find an allocation by its integer ID.

        :param cls: the :class:`Allocation`
        :param context: Security context
        :param allocation_id: The ID of an allocation.
        :returns: An :class:`Allocation` object.
        :raises: AllocationNotFound

        """
    db_allocation = cls.dbapi.get_allocation_by_id(allocation_id)
    allocation = cls._from_db_object(context, cls(), db_allocation)
    return allocation


def getInterfaceNames():
    """Return a list of RemoteInterface names to which this object knows
        how to respond."""


def update_copy(d, _new=None, **kw):
    """Copy the given dict and update with the given values."""
    d = d.copy()
    if _new:
        d.update(_new)
    d.update(**kw)
    return d


def remove_whitespaces(sentence):
    """
    Some error messages has multiple spaces, so we change it to one space.
    :param sentence:
    :return:
    """
    return ' '.join(sentence.split())


def slash_join(a, b):
    """
    Join a and b with a single slash, regardless of whether they already
    contain a trailing/leading slash or neither.
    """
    if not b:
        return a
    if a.endswith('/'):
        if b.startswith('/'):
            return a[:-1] + b
        return a + b
    if b.startswith('/'):
        return a + b
    return a + '/' + b


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 enough_samples(dates, meow_size):
    """Change detection requires a minimum number of samples (as specified
    by meow size).

    This function improves readability of logic that performs this check.

    Args:
        dates: list of ordinal day numbers relative to some epoch,
            the particular epoch does not matter.
        meow_size: minimum expected observation window needed to
            produce a fit.

    Returns:
        bool: True if times contains enough samples
        False otherwise.
    """
    return len(dates) >= meow_size


@staticmethod
def valued(val):
    """ Return True if the given string value is not empty """
    return val != ''