def register_api(bp, view_cls, endpoint, url, pk='item_id', pk_type='int'):
    """register restful api router

    :param bp: flask.BluePrint object
    :param view_cls: flask.views.View class
    :param endpoint: endpint
    :param url: url path, eg: /users/
    :param pk: entity id variable name
    :param pk_type: http://flask.pocoo.org/docs/0.12/quickstart/#variable-rules
    """
    view_func = view_cls.as_view(endpoint)
    bp.add_url_rule(url, defaults={pk: None}, view_func=view_func, methods=
        ['GET'])
    bp.add_url_rule(url, view_func=view_func, methods=['POST'])
    bp.add_url_rule('{0}<{1}:{2}>'.format(url, pk_type, pk), view_func=
        view_func, methods=['GET', 'PUT', 'DELETE', 'PATCH'])


def normalize_date_fields(document, created_at='created', updated_at='updated'
    ):
    """Attempt to normalize documents to make it easier for consumers,
    particularly around sorting.
    """
    if created_at and 'created_at' not in document:
        document[u'created_at'] = document[created_at]
    if updated_at and 'updated_at' not in document:
        document[u'updated_at'] = document[updated_at]


def _generate_dynamic_values(map, prefix, index_start, index_end, value_start):
    """ Generate values in a map (dict) dynamically. Each key starts with
        a (string) prefix, followed by an index in the inclusive range
        [index_start, index_end]. The values start at value_start.
    """
    for index in range(index_start, index_end + 1):
        name = '%s%s' % (prefix, index)
        value = value_start + index - index_start
        map[name] = value


def bc(col, width):
    """Mirror the column coordinate at the borders of the image; width must be a defined variable in the calling function containing the image width"""
    if col < 0:
        return -col
    elif col >= width:
        return width - col + width - 2
    return col


@staticmethod
def input_transform(data):
    """Provide an adapter between dataloader outputs and model inputs.
        It is an id() function by default.
        """
    return data


def run(_):
    """Function to execute when the pre-rebase hook is called. """
    pass


@classmethod
def replacer(cls, response_data, path):
    """Return the string that is replacing RESPONSE."""
    return path


def predict_model(model, scoring_inputs):
    """Uses a trained model to predict over the scoring data"""
    return model.predict(scoring_inputs)


def filebytes(fileobj, buffersize=1024):
    """
    Convenience for iterating over the bytes in a file. Given a
    file-like object (with a read(int) method), returns an iterator
    over the bytes of that file.
    """
    buff = fileobj.read(buffersize)
    while buff:
        for byte in buff:
            yield byte
        buff = fileobj.read(buffersize)


@staticmethod
def _flatten(supported_opts):
    """
        Supported options are stored as lists, within categories. This reads all the
        option objects from the categories, and returns them as a single list, to
        avoid needing to constantly traverse the categories to get to the options.

        :param supported_opts: the class field that contains a list of categories,
        each of which contains a list of options

        :return: a list of only options
        """
    to_return = []
    if supported_opts:
        for category in supported_opts:
            to_return.extend(category.options)
    return to_return


def take(seq, n):
    """
    Basically just itertools.islice(seq, 0, n)
    """
    last_index = n - 1
    for index, item in enumerate(seq):
        yield item
        if index == last_index:
            break


def cons(x, seq):
    """
    Return a generator where ``x`` is the first element and ``seq`` is the
    rest. Note, this differs from Clojure’s ``cons`` which returns a non-lazy
    list.
    """
    yield x
    for e in seq:
        yield e


def is_numba_installed(raise_error=False):
    """Test if numba is installed."""
    try:
        import numba
        is_installed = True
    except ImportError:
        is_installed = False
    if raise_error and not is_installed:
        raise IOError(
            'numba not installed. See http://numba.pydata.org/ for installation instructions.'
            )
    return is_installed


def process_default_input(dict_):
    """This functions processes the default input parameters"""
    try:
        dict_['ESTIMATION']['trim_support']
    except KeyError:
        trim = True
    else:
        trim = dict_['ESTIMATION']['trim_support']
    try:
        dict_['ESTIMATION']['reestimate_p']
    except KeyError:
        reestimate_p = False
    else:
        reestimate_p = dict_['ESTIMATION']['reestimate_p']
    try:
        dict_['ESTIMATION']['rbandwidth']
    except KeyError:
        rbandwidth = 0.05
    else:
        rbandwidth = dict_['ESTIMATION']['rbandwidth']
    return trim, rbandwidth, reestimate_p


def copy_undone(copied, tid):
    """
        After an undo operation, copy the matching blobs forward.

        The copied parameter is a list of ``(integer oid, integer tid)``.

        Does nothing if not a ``shared_blob_dir``.
        """


def get_variables(options):
    """
    Read all variables and values from ``-Dvariable=value`` options
    """
    split_eq = lambda x: x.split('=')
    data = dict(map(split_eq, options))
    return data


def draw_barre_arc(draw, instrument, finger_data_list, string_num, x_pos,
    y_pos, palette):
    """Add barre arcs to image if needed"""
    if '-' in finger_data_list[string_num]:
        finger_str = finger_data_list[string_num][0]
        arc_end = int(finger_data_list[string_num][3])
        x_pos_start = x_pos - 20
        y_pos_start = y_pos - 30
        x_pos_end = x_pos + instrument.string_spacing * (arc_end - 1 -
            string_num) + 20
        y_pos_end = y_pos + 60
        draw.arc((x_pos_start, y_pos_start, x_pos_end, y_pos_end), 225, 315,
            fill=palette.arc_colour)
    else:
        finger_str = str(finger_data_list[string_num])
    return finger_str


def fnutofwave(warr, farr):
    """Converts farr in ergs/s/cm2/Hz to ergs/s/cm2/A"""
    c = 2.99792458e+18
    return farr * c / warr ** 2


def layer_remove():
    """Remove mask layer

    """
    pass


def getDraft(userId, targetKey, draftName, default=None):
    """Get a particular named draft. If not found, the default is
        returned.
        """


def exit_spread_delta(data, value, _idx):
    """
    Exit and roll the trade if the spread total delta exceed the min or max value. For Example;

    spread delta = leg1ratio * leg1delta + leg2ratio * leg2delta
    """
    pass


def format_option(opt):
    """Return a formatted option in the form name=value."""
    return '{}={}\n'.format(opt.option, opt.value)


@staticmethod
def midi_unmap(plugin, param):
    """
        ``midi_unmap <instance_number> <param_symbol>``

        This command unmaps the MIDI controller from a parameter

        e.g.::

            unmap 0 gain

        .. note::

            Not implemented yet
        """
    pass


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

    The input should be in range `[-1, 1]`.
    The output is in the closed interval :math:`[0, \\pi]`

    .. math::
       arccos([-1, -.707, 0, .707, 1]) = [\\pi, 3\\pi/4, \\pi/2, \\pi/4, 0]

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

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

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

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

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


def read_selections_scalar(dsid, args):
    """ Returns a 2-tuple containing:

    1. Output dataset shape
    2. HDF5 dataspace containing source selection.

    Works for scalar datasets.
    """
    if dsid.shape != ():
        raise RuntimeError('Illegal selection function for non-scalar dataset')
    if args == ():
        out_shape = None
    elif args == (Ellipsis,):
        out_shape = ()
    else:
        raise ValueError('Illegal slicing argument for scalar dataspace')
    source_space = dsid.get_space()
    source_space.select_all()
    return out_shape, source_space


def brackets(s):
    """
	Return True if the parentheses match, False otherwise.

	>>> brackets("())")
	False

	>>> brackets("(()())")
	True

	>>> brackets("w(h)(a()t)")
	True
	"""
    x = 0
    for i in s:
        if i == '(':
            x += 1
        elif i == ')':
            x -= 1
        if x < 0:
            return False
    return not x


def datetime_is_naive(date_time):
    """ Returns True if dateTime is naive."""
    return date_time.tzinfo is None or date_time.tzinfo.utcoffset(date_time
        ) is None


def suspend_processes(AutoScalingGroupName=None, ScalingProcesses=None):
    """
    Suspends the specified Auto Scaling processes, or all processes, for the specified Auto Scaling group.
    Note that if you suspend either the Launch or Terminate process types, it can prevent other process types from functioning properly.
    To resume processes that have been suspended, use  ResumeProcesses .
    For more information, see Suspending and Resuming Auto Scaling Processes in the Auto Scaling User Guide .
    See also: AWS API Documentation

    Examples
    This example suspends the specified scaling process for the specified Auto Scaling group.
    Expected Output:

    :example: response = client.suspend_processes(
        AutoScalingGroupName='string',
        ScalingProcesses=[
            'string',
        ]
    )

    :type AutoScalingGroupName: string
    :param AutoScalingGroupName: [REQUIRED]
            The name or Amazon Resource Name (ARN) of the Auto Scaling group.

    :type ScalingProcesses: list
    :param ScalingProcesses: One or more of the following processes. If you omit this parameter, all processes are specified.
            Launch
            Terminate
            HealthCheck
            ReplaceUnhealthy
            AZRebalance
            AlarmNotification
            ScheduledActions
            AddToLoadBalancer
            (string) --

    :return: response = client.suspend_processes(
        AutoScalingGroupName='my-auto-scaling-group',
        ScalingProcesses=[
            'AlarmNotification',
        ],
    )

    print(response)

    """
    pass


def isimageobject(x):
    """Is an object a vipy.image class Image, ImageCategory, ImageDetection?"""
    return str(type(x)) in ["<class 'vipy.image.Image'>",
        "<class 'vipy.image.ImageCategory'>",
        "<class 'vipy.image.ImageDetection'>"]


def no_op(*args, **kwargs):
    """Function that does nothing."""


def decodeUnicode(s):
    """
    @summary: Decode Unicode string
    @param s: unicode string
    @return: str python
    """
    i = 0
    r = ''
    while i < len(s) - 2:
        if i % 2 == 0:
            r += s[i]
        i += 1
    return r


def tors_alpha(universe, seg, i):
    """alpha backbone dihedral

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

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

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

    .. versionadded:: 0.7.6
    """
    a = universe.select_atoms(" atom {0!s} {1!s} O3' ".format(seg, i - 1),
        ' atom {0!s} {1!s} P  '.format(seg, i), " atom {0!s} {1!s} O5' ".
        format(seg, i), " atom {0!s} {1!s} C5' ".format(seg, i))
    alpha = a.dihedral.value() % 360
    return alpha


def ISO():
    """Return the object in ISO standard format. Note: this is
        *not* ISO 8601-format! See the ISO8601 and HTML4 methods below
        for ISO 8601-compliant output

        Dates are output as: YYYY-MM-DD HH:MM:SS
        """


@classmethod
def iter_quadrature(cls, order=None, npoints=None):
    """iterates over a quadrature tuple wise
        """
    p = cls._determine_order(order, npoints)
    for i in range(len(cls.points[p])):
        yield cls.points[p][i], cls.weights[p][i]


def capitalize(string):
    """
    Capitalizes the first letter of a string.
    """
    return string[0].upper() + string[1:]


def merge_config(config, data):
    """
    Merge a new set of configuration requirements into a base configuration.

    :param config: the base configuration to update. This configuration
        is modified in-situ.
    :param data: The new configuration data to merge into the configuration.
    """
    for option in ['requires', 'sources']:
        value = data.pop(option, [])
        if value:
            config.setdefault(option, []).extend(value)
    config.update(data)


def merge(hub, flows):
    """
    Given the flows, find the areas where they converge and merge the related
    ingress data
    """
    ingress = {}
    r_flows = {}
    for full, data in flows.items():
        for pipe in data:
            if not data[pipe].get('enabled', True):
                continue
            for key in data[pipe]['ingress']:
                if key not in ingress:
                    ingress[key] = {}
                if pipe not in ingress[key]:
                    ingress[key][pipe] = []
                val = data[pipe]['ingress'][key]
                if not isinstance(val, list):
                    ingress[key][pipe].append(val)
                else:
                    ingress[key][pipe].extend(val)
                r_flows[pipe] = data[pipe]
    return ingress, r_flows


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


@classmethod
def encode_conjure_bean_type(cls, obj):
    """Encodes a conjure bean into json"""
    encoded = {}
    for attribute_name, field_definition in obj._fields().items():
        encoded[field_definition.identifier] = cls.do_encode(getattr(obj,
            attribute_name))
    return encoded


@staticmethod
def filter_by_rat(df, threshold=3):
    """
        Filter the DataFrame keeping in only ratings greater equal than threshold
        ------------
        :param df: pandas DataFrame
        :param threshold: minimum considered value in df
        :return: the pandas DataFrame with filtered ratings
        """
    rat_col = list(df)[2]
    df = df[df[rat_col] >= threshold]
    return df


def scale_size(scalar: float=1.0):
    """Change brush size by a scalar

    :param scalar: Scalar, Factor to scale brush size by
    :type scalar: float
    """
    pass


@classmethod
def progress(cls, options=None, return_raw_response=None):
    """Shows a task progress

        Usage::
            hammer task progress [OPTIONS]

        Options::
            --id ID                       UUID of the task
            --name NAME                   Name to search by
        """
    cls.command_sub = 'progress'
    return cls.execute(cls._construct_command(options), return_raw_response
        =return_raw_response)


@classmethod
def initialize_model(cls):
    """ This method is called to initialize a model during the creation of
        the registry
        """
    pass


def _pull(stack, arg):
    """move item from index to front"""
    idx = int(stack.pop())
    stack.append(stack.pop(idx))


def getFactor(currency):
    """returns the registered factor for a currency
           returns 1 if none was registered
        """


def pytest_instrument_tags(config, tags):
    """Called in pytest_runtest_setup(item) after collecting tags from @pytest.mark.instrument"""


def describe_func(obj, method=False):
    """ Describe the function object passed as argument.
	If this is a method object, the second argument will
	be passed as True """
    import inspect
    o = []
    try:
        arginfo = inspect.getargspec(obj)
    except TypeError:
        return
    args = arginfo[0]
    argsvar = arginfo[1]
    if args:
        if args[0] == 'self':
            args.pop(0)
        if arginfo[3]:
            dl = len(arginfo[3])
            al = len(args)
            defargs = args[al - dl:al]
            o = list(zip(defargs, arginfo[3]))
    return o


def groups(iterable, n):
    """
    They say Python is elegant, but then I have to do this.
    """
    return zip(*([iter(iterable)] * n))


def add_aacgm_coordinates(inst, glat_label='glat', glong_label='glong',
    alt_label='alt'):
    """
    Uses AACGMV2 package to add AACGM coordinates to instrument object.

    The Altitude Adjusted Corrected Geomagnetic Coordinates library is used
    to calculate the latitude, longitude, and local time
    of the spacecraft with respect to the geomagnetic field.

    Example
    -------
        # function added velow modifies the inst object upon every inst.load
        call inst.custom.add(add_quasi_dipole_coordinates, 'modify',
        glat_label='custom_label')

    Parameters
    ----------
    inst : pysat.Instrument
        Designed with pysat_sgp4 in mind
    glat_label : string
        label used in inst to identify WGS84 geodetic latitude (degrees N)
    glong_label : string
        label used in inst to identify WGS84 geodetic longitude (degrees E)
    alt_label : string
        label used in inst to identify WGS84 geodetic altitude (km, height
        above surface)

    Returns
    -------
    inst
        Input pysat.Instrument object modified to include quasi-dipole
        coordinates, 'aacgm_lat' for magnetic latitude, 'aacgm_long' for
        longitude, and 'aacgm_mlt' for magnetic local time.

    """
    import aacgmv2
    aalat = []
    aalon = []
    mlt = []
    for lat, lon, alt, time in zip(inst[glat_label], inst[glong_label],
        inst[alt_label], inst.data.index):
        tlat, tlon, tmlt = aacgmv2.get_aacgm_coord(lat, lon, alt, time)
        aalat.append(tlat)
        aalon.append(tlon)
        mlt.append(tmlt)
    inst['aacgm_lat'] = aalat
    inst['aacgm_long'] = aalon
    inst['aacgm_mlt'] = mlt
    inst.meta['aacgm_lat'] = {'units': 'degrees', 'long_name': 'AACGM latitude'
        }
    inst.meta['aacgm_long'] = {'units': 'degrees', 'long_name':
        'AACGM longitude'}
    inst.meta['aacgm_mlt'] = {'units': 'hrs', 'long_name':
        'AACGM Magnetic local time'}
    return


def substitute(line, charges, current_residuum):
    """
	Look up the charge for an atom, and write into a string.

	Args:
	line: String containing an atom name, residuum name, and original charge.
	charges: DataFrame containing atom name, residuum names, new charges.

	Returns:
	line: the original line, with the charge updated from the `charges` table.
	"""
    current_atom = line[0:7].strip()
    mask = (charges.atom == current_atom) & (charges.residue ==
        current_residuum)
    new_charge = charges[mask].q.values[0]
    charge_string = '{: 1.6f}'.format(new_charge) + '  '
    modified_line = line[:24] + charge_string + line[34:]
    return modified_line


def create_rar(archive, compression, cmd, verbosity, interactive, filenames):
    """Create a RAR archive."""
    cmdlist = [cmd, 'a']
    if not interactive:
        cmdlist.append('-y')
    cmdlist.extend(['-r', '-m5', '--', archive])
    cmdlist.extend(filenames)
    return cmdlist


def originstr(sequence):
    """formats dna sequence as broken, numbered lines ala genbank"""
    wordlen = 10
    cols = 6
    rowlen = wordlen * cols
    outstr = ''
    for linenum in range(int(len(sequence) / rowlen) + 1):
        pos = linenum * rowlen
        outstr += (' ' * 9 + str(pos + 1))[-9:] + ' ' + sequence[pos:pos + 10
            ] + ' ' + sequence[pos + 10:pos + 20] + ' ' + sequence[pos + 20
            :pos + 30] + ' ' + sequence[pos + 30:pos + 40] + ' ' + sequence[
            pos + 40:pos + 50] + ' ' + sequence[pos + 50:pos + 60] + '\n'
    return outstr


def full_sweep():
    """ Perform a full garbage collection sweep.

        o Reduce number of non-ghosts to 0, if possible.

        o Ghostify all non-sticky / non-changed objecs.
        """


def duplicate():
    """Duplicate selected control points and segments between them

    """
    pass


def get_trunk_vlan_spec(session, start=0, end=4094):
    """Gets portgroup trunk vlan spec.

    :param session: vCenter soap session
    :param start: the starting id
    :param end: then end id
    :returns: The configuration when a port uses trunk mode. This allows
              a guest to manage the vlan id.
    """
    client_factory = session.vim.client.factory
    spec_ns = 'ns0:VmwareDistributedVirtualSwitchTrunkVlanSpec'
    vlan_id = client_factory.create('ns0:NumericRange')
    vlan_id.start = start
    vlan_id.end = end
    vl_spec = client_factory.create(spec_ns)
    vl_spec.vlanId = vlan_id
    vl_spec.inherited = '0'
    return vl_spec


def db_convert_to_capped(db, coll_name, sizeBytes=2 ** 30):
    """converts a collection to capped"""
    if coll_name in db.collection_names():
        return db.command({'convertToCapped': coll_name, 'size': sizeBytes})


def _invoke_member(obj, memberName, *args, **kwargs):
    """Retrieves a member of an object, then calls it with the provided arguments.

    Args:
      obj: The object to operate on.
      membername: The name of the member to retrieve from ojb.
      args: Positional arguments to pass to the method.
      kwargs: Keyword arguments to pass to the method.
    Returns:
      The return value of the method invocation.
    """
    return getattr(obj, memberName)(*args, **kwargs)


def __queue(*inputs):
    """iterator that groups inputs by index (i.e. [(x[0], a[0]),(x[1], a[1])])"""
    return zip(*inputs)


@staticmethod
def checkhierarchy(description):
    """Function to check if the driver matches a particular hierarchy

        This function should be redefined in derived classes to return True
        if the description matches what is expected by the driver. The default
        implementation always returns False so that drivers that forget don't
        get loaded for hierarchies they don't expect.

        """
    return False


def not_equal(array_or_none1, array_or_none2):
    """
    Compare two arrays that can also be None or have diffent shapes
    and returns a boolean.

    >>> a1 = numpy.array([1])
    >>> a2 = numpy.array([2])
    >>> a3 = numpy.array([2, 3])
    >>> not_equal(a1, a2)
    True
    >>> not_equal(a1, a3)
    True
    >>> not_equal(a1, None)
    True
    """
    if array_or_none1 is None and array_or_none2 is None:
        return False
    elif array_or_none1 is None and array_or_none2 is not None:
        return True
    elif array_or_none1 is not None and array_or_none2 is None:
        return True
    if array_or_none1.shape != array_or_none2.shape:
        return True
    return (array_or_none1 != array_or_none2).any()


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

    The ".dev0" means dirty.

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


def read_fsas(ec_dir='/home/users/assafp/Database/EcoCyc/current/data'):
    """
    Read the fasta files of the chromosomes, return a dictionary from the
    chrname to the sequence
    Arguments:
    - `ec_dir`: main directory of EcoCyc
    """
    import glob
    from Bio import SeqIO
    fsa_seqs = {}
    for fsa_name in glob.glob('%s/*-*.fsa' % ec_dir):
        fsa_seqs[fsa_name.rsplit('.', 1)[0].split('-', 1)[1]] = SeqIO.read(open
            (fsa_name), 'fasta').seq
    return fsa_seqs


@staticmethod
def _add_key_meta(params):
    """Adds meta=_key to ensure a key is returned"""
    meta = params.get('meta', [])
    if '_key' not in meta:
        meta = list(meta)
        meta.append('_key')
        params['meta'] = meta
    return params


def __HashNull():
    """Null Function for HashFiles Function
    """
    pass


def move(name, other, newname=None):
    """
        Move a subobject named ``name`` from this folder to the folder
        represented by ``other``.  If ``newname`` is not none, it is used as
        the target object name; otherwise the existing subobject name is
        used.

        This operation is done in terms of a remove and an add.  The Removed
        and WillBeRemoved events sent will indicate that the object is
        moving.
        """


@staticmethod
def get_email():
    """Prompt for email.

        Returns:
            str: Google account email address.
        """
    print('Sign in with your Google account:')
    return input('Email: ')


def validate_format(*_arg):
    """
    This method can be overridden with format validation logic.
    """
    return True


def sigmaLabel(ax, xlabel, ylabel, sigma=None):
    """Label the axes on a figure with some uncertainty."""
    confStr = '$\\pm{} \\sigma$'.format(sigma) if sigma is not None else ''
    ax.set_xlabel(xlabel + confStr)
    ax.set_ylabel(ylabel + confStr)
    return ax


@classmethod
def condition(cls, previous_value, value, has_changed=False, first_save=
    False, graph_property=None):
    """ Only save this value if it is increasing

        :rtype: bool
        """
    if previous_value is not None:
        return value > previous_value
    else:
        return True


def set_to_str(s: set) ->str:
    """
    Convert a set to a string.

    :param s: a set.
    :return: a string. The result is similar to str(s), but if the elements of the set are comparable, they appear in
        ascending order.

    >>> set_to_str({2, 42, 12})
    '{2, 12, 42}'
    """
    try:
        return '{' + str(sorted(s))[1:-1] + '}'
    except TypeError:
        return str(s)


def combine_fields(global_vars, local_vars):
    """
    Combine the given manifest entries according to the semantics of specific fields.
    This is used to combine manifest level defaults with a per-test definition.
    """
    if not global_vars:
        return local_vars
    if not local_vars:
        return global_vars.copy()
    field_patterns = {'prefs': '%s %s', 'skip-if': '(%s) || (%s)',
        'support-files': '%s %s'}
    final_mapping = global_vars.copy()
    for field_name, value in local_vars.items():
        if field_name not in field_patterns or field_name not in global_vars:
            final_mapping[field_name] = value
            continue
        global_value = global_vars[field_name]
        pattern = field_patterns[field_name]
        final_mapping[field_name] = pattern % (global_value, value)
    return final_mapping


def process(proc_data):
    """
    Final processing to conform to the schema.

    Parameters:

        proc_data:   (dictionary) raw structured data to process

    Returns:

        List of dictionaries. Structured data with the following schema:

        [
          {
            "filename": string,
            "flags":    string,
            "links":    integer,
            "parent":   string,
            "owner":    string,
            "group":    string,
            "size":     integer,
            "date":     string
          }
        ]
    """
    for entry in proc_data:
        int_list = ['links', 'size']
        for key in int_list:
            if key in entry:
                try:
                    key_int = int(entry[key])
                    entry[key] = key_int
                except ValueError:
                    entry[key] = None
    return proc_data


def opt_to_kwargs(opt):
    """Get kwargs for seq2seq from opt."""
    kwargs = {}
    for k in ['mem_size', 'time_features', 'position_encoding', 'hops']:
        if k in opt:
            kwargs[k] = opt[k]
    return kwargs


def dateToInt(date, strfmt='%Y%m%d'):
    """ Converts a datetime date into int
	Parameters:
	-----------
		date : datetime
			date in datetime format
		strfmt : string
			format in which the int date will be generated
	Example:
		dateToInt(dt.date(2015,10,23),'%Y')
	"""
    return int(date.strftime(strfmt))


@staticmethod
def _build_volume(volume):
    """
        Given a generic volume definition, create the volumes element
        """
    return {'hostPath': volume.get('host'), 'containerPath': volume.get(
        'container'), 'mode': 'RO' if volume.get('readonly') else 'RW'}


def reload():
    """Gracefully reloads uWSGI.

    * http://uwsgi.readthedocs.io/en/latest/Management.html#reloading-the-server

    :rtype: bool
    """
    return False


@classmethod
def Character(cls):
    """Postgres Character Type"""
    return cls(str, 'CHARACTER')


def force_attribute_same_len_if_none(obj, same_len_attributes=[], value=None):
    """Make list of None with len the same as an existing attribute

    If attributes after the first are None then make those attributes a list
    of len(first_attribute) filled with value.  This is useful when you want
    to zip each member of two attributes. If the second attribute is None,
    then any zipping is impossible.  However, if the second attribute
    is set to a list of None then zipping is possible.

    Parameters
    ----------
    obj : object
        Object that has the attributes.
    same_len_attributes : list of list of string
        For each group of attribute names, if attributes after the first are
        None then those attributes will be made a list of len(first_attribute)
        filled with `value`.
    value : obj, optional
        Value to fill each list.  Default value=None.

    """
    for group in same_len_attributes:
        a1 = getattr(obj, group[0])
        if a1 != None:
            for v in group[1:]:
                if getattr(obj, v) is None:
                    setattr(obj, v, [value] * len(a1))


def oauth_url(client_id, permissions=None, guild=None, redirect_uri=None):
    """A helper function that returns the OAuth2 URL for inviting the bot
    into guilds.

    Parameters
    -----------
    client_id: :class:`str`
        The client ID for your bot.
    permissions: :class:`~discord.Permissions`
        The permissions you're requesting. If not given then you won't be requesting any
        permissions.
    guild: :class:`~discord.Guild`
        The guild to pre-select in the authorization screen, if available.
    redirect_uri: :class:`str`
        An optional valid redirect URI.
    """
    url = ('https://discordapp.com/oauth2/authorize?client_id={}&scope=bot'
        .format(client_id))
    if permissions is not None:
        url = url + '&permissions=' + str(permissions.value)
    if guild is not None:
        url = url + '&guild_id=' + str(guild.id)
    if redirect_uri is not None:
        from urllib.parse import urlencode
        url = url + '&response_type=code&' + urlencode({'redirect_uri':
            redirect_uri})
    return url


def _enumerate(obj):
    """enumerate lists (with indexes) and dicts (with keys)
    """
    if isinstance(obj, (set, tuple, list)):
        for i, v in enumerate(obj):
            yield i, v
    elif isinstance(obj, dict):
        for k, v in obj.items():
            yield k, v


def daySalary(monrhSalary):
    """根据月薪，计算员工日薪，计算公式：monthSalary/22.5"""
    return monrhSalary / 22.5


def phdos_label_from_units(units):
    """
    Return latex string for phonon DOS values in ``units``.
    """
    d = {'ev': '(states/eV)', 'mev': '(states/meV)', 'ha': '(states/Ha)',
        'cm-1': '(states/cm$^{-1}$)', 'cm^-1': '(states/cm$^{-1}$)', 'thz':
        '(states/Thz)'}
    try:
        return d[units.lower().strip()]
    except KeyError:
        raise KeyError(
            'Value for units `{}` unknown\nPossible values are:\n {}'.
            format(units, list(d.keys())))


def copyDropContents(source, target, bufsize=4096):
    """
    Manually copies data from one DROP into another, in bufsize steps
    """
    desc = source.open()
    read = source.read
    buf = read(desc, bufsize)
    while buf:
        target.write(buf)
        buf = read(desc, bufsize)
    source.close(desc)


def get_name(layer_name, counters):
    """ utlity for keeping track of layer names """
    if not layer_name in counters:
        counters[layer_name] = 0
    name = layer_name + '_' + str(counters[layer_name])
    counters[layer_name] += 1
    return name


def is_tool(name):
    """Check whether `name` is on PATH and marked as executable."""
    from shutil import which
    return which(name) is not None


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


@staticmethod
def _between_(x1s, y1s, x2s, y2s, x, y):
    """
        checks if (x,y) in rectangle of (x1s,y1s)-(x2s,y2s)
        """
    f1 = 1.0 - 1e-12
    f2 = 1.0 + 1e-12
    f3 = 1e-06
    xs_min = min(x1s, x2s)
    if xs_min > 0:
        xs_min *= f1
    else:
        xs_min *= f2
    xs_max = max(x1s, x2s)
    if xs_max > 0:
        xs_max *= f2
    else:
        xs_max *= f1
    ys_min = min(y1s, y2s)
    if ys_min > 0:
        ys_min *= f1
    else:
        ys_min *= f2
    ys_max = max(y1s, y2s)
    if ys_max > 0:
        ys_max *= f2
    else:
        ys_max *= f1
    if xs_min == 0:
        xs_min = -xs_max * f3
    if xs_max == 0:
        xs_max = -xs_min * f3
    if ys_min == 0:
        ys_min = -ys_max * f3
    if ys_max == 0:
        ys_max = -ys_min * f3
    if xs_min <= x <= xs_max and ys_min <= y <= ys_max:
        return True
    else:
        return False


def get_file_contents(path):
    """Open a file for reading

    :param path: path of file to read
    """
    with open(path) as p:
        return p.read()


def pretty_byte_count(num):
    """Converts integer into a human friendly count of bytes, eg: 12.243 MB"""
    if num == 1:
        return '1 byte'
    elif num < 1024:
        return '%s bytes' % num
    elif num < 1048576:
        return '%.2f KB' % (num / 1024.0)
    elif num < 1073741824:
        return '%.3f MB' % (num / 1048576.0)
    elif num < 1099511627776:
        return '%.3f GB' % (num / 1073741824.0)
    else:
        return '%.3f TB' % (num / 1099511627776.0)


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


def visit_Number(s, node):
    """Return a number in string without width specifier."""
    return str(node.value)


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

        :param ResellerLogInfo val:
        :rtype: ActorLogInfo
        """
    return cls('reseller', val)


def get_distances(clusters):
    """Extract distances as intermediate values between 2 clusters"""
    clusters_ext = list(clusters)
    clusters_ext.insert(0, str(0))
    distances = []
    for idx, _ in enumerate(clusters_ext[:-1]):
        clst_0 = float(clusters_ext[idx])
        clst_1 = float(clusters_ext[idx + 1])
        distances.append((clst_1 - clst_0) / 2 + clst_0)
    return tuple(distances)


@classmethod
def from_specification(cls, specification, model, classical_gap, ground_energy
    ):
    """Construct a PenaltyModel from a Specification.

        Args:
            specification (:class:`.Specification`): A specification that was used
                to generate the model.
            model (:class:`dimod.BinaryQuadraticModel`): A binary quadratic model
                that has ground states that match the feasible_configurations.
            classical_gap (numeric): The difference in classical energy between the ground
                state and the first excited state. Must be positive.
            ground_energy (numeric): The minimum energy of all possible configurations.

        Returns:
            :class:`.PenaltyModel`

        """
    return cls(specification.graph, specification.decision_variables,
        specification.feasible_configurations, specification.vartype, model,
        classical_gap, ground_energy, ising_linear_ranges=specification.
        ising_linear_ranges, ising_quadratic_ranges=specification.
        ising_quadratic_ranges)


@classmethod
def generate_and_write_files(cls, path=None, file_name=None, key_size=None,
    passphrase=None):
    """Generate and write public and private rsa keys to local files

        :param str path: Path to put the file(s)
        :param str file_name: Name of the private_key file, 'id_rsa' by default
        :param int key_size: RSA modulus length (must be a multiple of 256)
                             and >= 1024
        :param str pass_phrase: The pass phrase to derive the encryption key
                                from
        """
    keys = cls.generate_rsa_ssh_keys(key_size, passphrase)
    cls.write_secure_keys_local(private_key=keys.private_key, public_key=
        keys.public_key, path=path, file_name=file_name)


def decode_payload(payload: str) ->str:
    """ Decode payload with URL-safe base64url. """
    from base64 import urlsafe_b64decode
    result: bytes = urlsafe_b64decode(payload + '=' * (4 - len(payload) % 4))
    return result.decode()


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


@staticmethod
def __check_project_slug(project: str) ->None:
    """Check if project slug is invalid.

        Args:
            project (str): Slug of project which should be checked.

        Raises:
            TypeError: If slug is not of type str.
            ValueError: If slug string is empty or only consists of whitespace.
        """
    if not isinstance(project, str):
        raise TypeError('Project slug is not of type string.')
    if not project or project.isspace():
        raise ValueError('The specified project slug must not be empty.')


def radians(data=None, name=None, attr=None, out=None, **kwargs):
    """Converts each element of the input array from degrees to radians.

    .. math::
       radians([0, 90, 180, 270, 360]) = [0, \\pi/2, \\pi, 3\\pi/2, 2\\pi]

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

       - radians(default) = default
       - radians(row_sparse) = row_sparse
       - radians(csr) = csr

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

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

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

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


def _is_dunder(name):
    """Returns True if a __dunder__ name, False otherwise."""
    return name[:2] == name[-2:] == '__' and name[2:3] != '_' and name[-3:-2
        ] != '_' and len(name) > 4


@staticmethod
def _format_url(url):
    """"Formats URL strings"""
    if not (url.startswith('http://') or url.startswith('https://')):
        url = 'http://' + url
    return url


def convert_str_tags_to_list(i):
    """
    Input:  either a list, or a string of comma-separated tags.

    Output: If i is a list, it's returned.
            If i is a string, the list of tags it represents is returned
            (each tag is stripped of leading and trailing whitespace).

    """
    r = []
    if type(i) == list:
        r = i
    else:
        ii = i.split(',')
        for q in ii:
            q = q.strip()
            if q != '':
                r.append(q)
    return r


@classmethod
def get_cachevault(cls, session, server_key, controller):
    """Cachevault details
        Args:
            session:  database session
            server_key(int): key of the server cachevault belongs to
            controller(int): controller num
        Returns:
            dict: information about cachevault
        """
    query = []
    query.extend([
        'MATCH (:Asset {{ key: {} }})-[:HAS_CONTROLLER]->(ctrl:Controller {{ controllerNum: {} }})'
        .format(server_key, controller),
        'MATCH (ctr)-[:HAS_CACHEVAULT]->(cv:CacheVault)', 'RETURN cv'])
    results = session.run('\n'.join(query))
    record = results.single()
    return dict(record.get('cv')) if record else None


def unescape(text):
    """Inverse of escape."""
    if isinstance(text, str):
        if '&' in text:
            text = text.replace('&', '&')
        if '>' in text:
            text = text.replace('>', '>')
        if '<' in text:
            text = text.replace('<', '<')
        if '"' in text:
            text = text.replace('"', '"')
    return text


def set_global_updater_mngr(mngr):
    """Return the manager that creates and returns the ThreadUpdater."""
    global GLOBAL_UPDATER_MANGER
    GLOBAL_UPDATER_MANGER = mngr


def p_track_cd_text(t):
    """track_flag : CD_TEXT START_BLOCK language_blocks END_BLOCK"""
    from audiotools.toc import CDText
    t[0] = CDText(languages=t[3])


def save_class(cls):
    """
    Save given class as a string.

    :type cls: type
    :rtype: str
    """
    return '{0.__module__}.{0.__name__}'.format(cls)


def ltrimboth(l, proportiontocut):
    """
Slices off the passed proportion of items from BOTH ends of the passed
list (i.e., with proportiontocut=0.1, slices 'leftmost' 10% AND 'rightmost'
10% of scores.  Assumes list is sorted by magnitude.  Slices off LESS if
proportion results in a non-integer slice index (i.e., conservatively
slices off proportiontocut).

Usage:   ltrimboth (l,proportiontocut)
Returns: trimmed version of list l
"""
    lowercut = int(proportiontocut * len(l))
    uppercut = len(l) - lowercut
    return l[lowercut:uppercut]


def add_job_flow_steps(JobFlowId=None, Steps=None):
    """
    AddJobFlowSteps adds new steps to a running cluster. A maximum of 256 steps are allowed in each job flow.
    If your cluster is long-running (such as a Hive data warehouse) or complex, you may require more than 256 steps to process your data. You can bypass the 256-step limitation in various ways, including using SSH to connect to the master node and submitting queries directly to the software running on the master node, such as Hive and Hadoop. For more information on how to do this, see Add More than 256 Steps to a Cluster in the Amazon EMR Management Guide .
    A step specifies the location of a JAR file stored either on the master node of the cluster or in Amazon S3. Each step is performed by the main function of the main class of the JAR file. The main class can be specified either in the manifest of the JAR or by using the MainFunction parameter of the step.
    Amazon EMR executes each step in the order listed. For a step to be considered complete, the main function must exit with a zero exit code and all Hadoop jobs started while the step was running must have completed and run successfully.
    You can only add steps to a cluster that is in one of the following states: STARTING, BOOTSTRAPPING, RUNNING, or WAITING.
    See also: AWS API Documentation

    :example: response = client.add_job_flow_steps(
        JobFlowId='string',
        Steps=[
            {
                'Name': 'string',
                'ActionOnFailure': 'TERMINATE_JOB_FLOW'|'TERMINATE_CLUSTER'|'CANCEL_AND_WAIT'|'CONTINUE',
                'HadoopJarStep': {
                    'Properties': [
                        {
                            'Key': 'string',
                            'Value': 'string'
                        },
                    ],
                    'Jar': 'string',
                    'MainClass': 'string',
                    'Args': [
                        'string',
                    ]
                }
            },
        ]
    )

    :type JobFlowId: string
    :param JobFlowId: [REQUIRED]
            A string that uniquely identifies the job flow. This identifier is returned by RunJobFlow and can also be obtained from ListClusters .

    :type Steps: list
    :param Steps: [REQUIRED]
            A list of StepConfig to be executed by the job flow.
            (dict) --Specification of a cluster (job flow) step.
            Name (string) -- [REQUIRED]The name of the step.
            ActionOnFailure (string) --The action to take if the step fails.
            HadoopJarStep (dict) -- [REQUIRED]The JAR file used for the step.
            Properties (list) --A list of Java properties that are set when the step runs. You can use these properties to pass key value pairs to your main function.
            (dict) --A key value pair.
            Key (string) --The unique identifier of a key value pair.
            Value (string) --The value part of the identified key.

            Jar (string) -- [REQUIRED]A path to a JAR file run during the step.
            MainClass (string) --The name of the main class in the specified Java file. If not specified, the JAR file should specify a Main-Class in its manifest file.
            Args (list) --A list of command line arguments passed to the JAR file's main function when executed.
            (string) --

    :rtype: dict
    :return: {
        'StepIds': [
            'string',
        ]
    }

    :returns:
    (string) --

    """
    pass


def freestyle_stroke_material_create():
    """Create Freestyle stroke material for testing

    """
    pass


def skip_read_line(fd, no_eof=False):
    """
    Read the first non-empty line (if any) from the given file
    object. Return an empty string at EOF, if `no_eof` is False. If it
    is True, raise the EOFError instead.
    """
    ls = ''
    while 1:
        try:
            line = fd.readline()
        except EOFError:
            break
        if not line:
            if no_eof:
                raise EOFError
            else:
                break
        ls = line.strip()
        if ls and ls[0] != '#':
            break
    return ls


def get_maintenance_window(WindowId=None):
    """
    Retrieves a Maintenance Window.
    See also: AWS API Documentation

    :example: response = client.get_maintenance_window(
        WindowId='string'
    )

    :type WindowId: string
    :param WindowId: [REQUIRED]
            The ID of the desired Maintenance Window.

    :rtype: dict
    :return: {
        'WindowId': 'string',
        'Name': 'string',
        'Schedule': 'string',
        'Duration': 123,
        'Cutoff': 123,
        'AllowUnassociatedTargets': True|False,
        'Enabled': True|False,
        'CreatedDate': datetime(2015, 1, 1),
        'ModifiedDate': datetime(2015, 1, 1)
    }

    """
    pass


def decode_tx(txid):
    """
        return dict with important transaction information
        """
    return NotImplementedError


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

    Like 'git describe --tags --dirty --always -long'.
    The distance/hash is unconditional.

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


def setVerbosity(verbosity_level):
    """Copy verbosity to a variable that is global for this file.
       argument: verbosity_level -  an integer value indicating the level of verbosity
    """
    global verbosity
    verbosity = verbosity_level


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_sizeof(num, suffix='o'):
    """Readable file size
    :param num: Bytes value
    :type num: int
    :param suffix: Unit suffix (optionnal) default = o
    :type suffix: str
    :rtype: str
    """
    for unit in ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z']:
        if abs(num) < 1024.0:
            return '%3.1f %s%s' % (num, unit, suffix)
        num /= 1024.0
    return '%.1f%s%s' % (num, 'Yi', suffix)


def clear():
    """Clear the MetaData singleton."""
    global _METADATA
    _METADATA = None


def _get_table_name(featuregroup, version):
    """
    Gets the Hive table name of a featuregroup and version

    Args:
        :featuregroup: the featuregroup to get the table name of
        :version: the version of the featuregroup

    Returns:
        The Hive table name of the featuregroup with the specified version
    """
    return featuregroup + '_' + str(version)


def to_bool(value):
    """utility function for boolean casting
    >>> to_bool("True")
    True
    >>> to_bool("False")
    False
    >>> to_bool(True)
    True

    :type value any
    """
    valid = {'True': True, 'true': True, 'on': True, 't': True, '1': True,
        'False': False, 'false': False, 'off': False, 'f': False, '0': False}
    if isinstance(value, bool):
        return value
    lower_value = value.lower()
    if lower_value in valid:
        return valid[lower_value]
    else:
        raise ValueError(
            'invalid literal for boolean: {}. Possible values are {}'.
            format(value, list(valid)))


def strtime(span, colour=False):
    """
    Return a moderately long string, providing a human-interpretable
    representation of the provided timespan
    """
    if colour:
        cms = '\x1b[0m'
        cs = '\x1b[38;5;246m'
        cm = '\x1b[38;5;239m'
        ch = '\x1b[38;5;250m'
        cd = '\x1b[38;5;242m'
        cr = '\x1b[0m'
    else:
        cr = cd = ch = cm = cs = cms = ''
    if span < 1:
        return cms + '{:6.3f}ms'.format(span * 1000) + cr
    if span < 120:
        full = int(span)
        return cs + '{:3d}s '.format(full) + cms + '{:3d}ms'.format(int((
            span - full) * 1000)) + cr
    if span < 3600:
        full = int(span / 60)
        return cm + '{:2d}m '.format(full) + cs + '{:2d}s'.format(int(span -
            full * 60)) + cr
    if span < 86400:
        full = int(span / 3600)
        return ch + '{:2d}h '.format(full) + cm + '{:2d}m'.format(full, int
            (span / 60 - full * 60)) + cr
    else:
        full = int(span / 86400)
        return cd + '{:3d}d '.format(full) + ch + '{:2d}h'.format(int(span /
            3600 - full * 24)) + cr


@staticmethod
def nucmer_hit_containing_reference_position(nucmer_hits, ref_name,
    ref_position, qry_name=None):
    """Returns the first nucmer match found that contains the given
           reference location. nucmer_hits = hits made by self._parse_nucmer_coords_file.
           Returns None if no matching hit found"""
    for contig_name in nucmer_hits:
        for hit in nucmer_hits[contig_name]:
            if hit.ref_name == ref_name and (qry_name is None or qry_name ==
                hit.qry_name) and hit.ref_coords().distance_to_point(
                ref_position) == 0:
                return hit
    return None


def fibonaccigen(f0=0, f1=1):
    """ A000045 [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ...]
		arguments are the first two element of the Fibonacci series

		To get a specific Fibonacci number use `fibonacci(n)`.
	"""
    yield f0
    while True:
        yield f1
        f1, f0 = f1 + f0, f1


def validate(observation):
    """Make sure the observation table is valid, or raise an error."""
    if observation is not None and type(observation) == dict:
        return observation
    else:
        raise RuntimeError('Must return dictionary from act().')


def teste():
    """
    Método de Teste.
    """
    print('Esse é um método de testes.')


@staticmethod
def getPerformanceParameters(defaultParams):
    """
        _getPerformanceParameters_

        This generic JobFactory function allows all splitters to easily
        retrieve the parameters to specify the resource requirements for
        the created jobs.
        # TODO: Check couchDB for performance on the current task
                and if not available it falls back to the default params.
        It returns a tuple with the following values:
        timePerEvent, sizePerEvent, memoryRequirement
        """
    timePerEvent = defaultParams.get('timePerEvent', 0) or 0
    sizePerEvent = defaultParams.get('sizePerEvent', 0) or 0
    memory = defaultParams.get('memoryRequirement', 0) or 0
    return timePerEvent, sizePerEvent, memory


def __call__(cls, value, names=None, module=None, type=None):
    """Either returns an existing member, or creates a new enum class.

        This method is used both when an enum class is given a value to match
        to an enumeration member (i.e. Color(3)) and for the functional API
        (i.e. Color = Enum('Color', names='red green blue')).

        When used for the functional API: `module`, if set, will be stored in
        the new class' __module__ attribute; `type`, if set, will be mixed in
        as the first base class.

        Note: if `module` is not set this routine will attempt to discover the
        calling module by walking the frame stack; if this is unsuccessful
        the resulting class will not be pickleable.

        """
    if names is None:
        return cls.__new__(cls, value)
    return cls._create_(value, names, module=module, type=type)


def get_bundle_identifier_for_path(path):
    """
    Get bundle identifier for the given path.
    """
    return


@classmethod
def validate(cls, parameters_dict):
    """validate parameters"""
    return cls._schema(parameters_dict)


def update_failed():
    """return if the last update failed or not"""


@staticmethod
def build(d):
    """
        Build an object from a JSON dictionary.

        This differs from `from_dict` in that the values themselves may *also* be dictionaries
        corresponding to serialized DictSerializable objects.

        Parameters
        ----------
        d: dict
            The object as a serialized dictionary.

        Returns
        -------
        DictSerializable
            The deserialized object.

        """
    from gemd.json import GEMDJson
    encoder = GEMDJson()
    return encoder.raw_loads(encoder.raw_dumps(d))


def secondary_mass_fraction(mu):
    """
    Distribution function of the mass fraction of the secondary in binary systems / SNI
    mu = Mass_secondary / Mass_binary_system
    From: Matteucci, F. & Greggio, L. 1986, A&A, 154, 279
    with Gamma = 2 as Greggio, L., Renzini, A.: 1983a, Astron. Astrophys. 118, 217

    """
    gamma = 2.0
    return 2.0 ** (1.0 + gamma) * (1.0 + gamma) * mu ** gamma


def get_R2(Y, Y_hat):
    """
    Gets the coefficient of determination R^2.
    """
    diff_Y_Ybar = Y - Y.mean()
    SStotal = diff_Y_Ybar.dot(diff_Y_Ybar)
    diff_Y_Yhat = Y - Y_hat
    SSerr = diff_Y_Yhat.dot(diff_Y_Yhat)
    return 1 - SSerr / float(SStotal)


def bound(value, bound1, bound2):
    """
    returns value if value is between bound1 and bound2
    otherwise returns bound that is closer to value
    """
    if bound1 > bound2:
        return min(max(value, bound2), bound1)
    else:
        return min(max(value, bound1), bound2)


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 iterValueIndexInfo():
    """return iterable of dicts, each with data for added value indexes.

        See arguments to addValueIndex for keys in dicts."""


def get_parent(tree, child_clade):
    """
    Not used. removing in next commit.

    :param tree:
    :param child_clade:

    :return:
    """
    node_path = tree.get_path(child_clade)
    return node_path[-2]


def get_servers_for_psi(peer_selection_index):
    """
        @return: list of IServer instances
        """


@classmethod
def _create_all_bits(cls, figure, data_by_year, shifts, bits):
    """Totall used bits by shift and bits in rock."""
    all_bits = figure.add_subplot(222)
    all_bits.plot(data_by_year[shifts[0]].month, bits[0], marker='D',
        markersize=4)
    all_bits.plot(data_by_year[shifts[1]].month, bits[1], marker='D',
        markersize=4)
    all_bits.plot(data_by_year[shifts[0]].month, data_by_year[shifts[0]].
        bits_in_rock, marker='D', markersize=4)
    all_bits.plot(data_by_year[shifts[1]].month, data_by_year[shifts[1]].
        bits_in_rock, marker='D', markersize=4)
    all_bits.legend(['коронки, см.1', 'коронки, см.2',
        'коронки в скале, см.1', 'коронки в скале, см.2'])
    all_bits.set_ylabel('количество, шт')
    all_bits.grid(b=True, linestyle='--', linewidth=0.5)
    all_bits.set_title('Истрачено коронок.')


def controller_remove(controller: str='', object: str=''):
    """Remove a controller from the active object

    :param controller: Controller, Name of the controller to edit
    :type controller: str
    :param object: Object, Name of the object the controller belongs to
    :type object: str
    """
    pass


@staticmethod
def is_functional_var(var_name):
    """
        Assumes var_name is a legal variable name (doesn't check). Returns
        True iff var_name is a functional variable name

        Parameters
        ----------
        var_name : str

        Returns
        -------
        bool

        """
    assert isinstance(var_name, str) and len(var_name) >= 2
    if var_name[0] == '-':
        if not var_name[1].islower():
            return False
    elif not var_name[0].islower():
        return False
    return True


@classmethod
def _assert_safe_casting(cls, data, subarr):
    """
        Subclasses need to override this only if the process of casting data
        from some accepted dtype to the internal dtype(s) bears the risk of
        truncation (e.g. float to int).
        """
    pass


def create_reusable_delegation_set(CallerReference=None, HostedZoneId=None):
    """
    Creates a delegation set (a group of four name servers) that can be reused by multiple hosted zones. If a hosted zoned ID is specified, CreateReusableDelegationSet marks the delegation set associated with that zone as reusable
    For information on how to use a reusable delegation set to configure white label name servers, see Configuring White Label Name Servers .
    See also: AWS API Documentation

    :example: response = client.create_reusable_delegation_set(
        CallerReference='string',
        HostedZoneId='string'
    )

    :type CallerReference: string
    :param CallerReference: [REQUIRED]
            A unique string that identifies the request, and that allows you to retry failed CreateReusableDelegationSet requests without the risk of executing the operation twice. You must use a unique CallerReference string every time you submit a CreateReusableDelegationSet request. CallerReference can be any unique string, for example a date/time stamp.

    :type HostedZoneId: string
    :param HostedZoneId: If you want to mark the delegation set for an existing hosted zone as reusable, the ID for that hosted zone.

    :rtype: dict
    :return: {
        'DelegationSet': {
            'Id': 'string',
            'CallerReference': 'string',
            'NameServers': [
                'string',
            ]
        },
        'Location': 'string'
    }

    :returns:
    (string) --

    """
    pass


def _isInt(argstr):
    """ Returns True if and only if the given string represents an integer. """
    try:
        int(argstr, 0)
        return True
    except (ValueError, TypeError):
        return False


def readInputParameters(inputList):
    """Reads input parameters and creates a dictionary of inputs.

    Keyword arguments:
    inputList -- sys.argv list of parameters.

    Returns:
    Returns dictionary of parameters.
    """
    paramDict = dict()
    for e in inputList:
        eSplit = e.split('=')
        paramDict[eSplit[0]] = eSplit[1]
    return paramDict


def getColumnsClasses():
    """Returns all CSS classes based on columns presence.
        """


@classmethod
def ttl(klass, ttl):
    """
        Set check to be marked as critical after *ttl* (e.g. "10s") unless the
        check is periodically marked as passing.
        """
    return {'ttl': ttl}


def regularizeTrailingNewlines(s, kind):
    """Kind is 'asis', 'zero' or 'one'."""
    pass


def checksum_to_hash(checksum):
    """Converts hex to id_hash (signed 64-bit int)."""
    return int(checksum, 16) - 2 ** 63


def filter_parms(**items):
    """
    To get all segment for 'petrol truck'. Valid parameters:
        cat=category
        fuel=fuel
        segment=segment
        eurostd=eurostd
        pollutant=pollutant
        mode=mode

    >>> truck = session.query(emission.models.Category).all()[2]
    >>> fuel = list(truck.fuels())[0]
    >>> filtered_parameters = emission.models.filter(cat=truck, fuel=fuel)
    >>> set(x.segment for x in filtered_parameters)
    """
    parameters = []
    if 'cat' in items:
        parameters = items.get('cat').parameter
    if 'fuel' in items:
        parameters = list(filter(lambda x: x.fuel == items.get('fuel'),
            parameters))
    if 'segment' in items:
        parameters = list(filter(lambda x: x.segment == items.get('segment'
            ), parameters))
    if 'eurostd' in items:
        parameters = list(filter(lambda x: x.eurostd == items.get('eurostd'
            ), parameters))
    if 'pollutant' in items:
        parameters = list(filter(lambda x: x.pollutant == items.get(
            'pollutant'), parameters))
    if 'mode' in items:
        parameters = list(filter(lambda x: x.mode == items.get('mode'),
            parameters))
    return parameters


def downgrade():
    """Migrations for the downgrade."""


def save_history(filename, session_only=False, maxlines=5000, _larch=None):
    """save history of larch commands to a file"""
    _larch.input.history.save(filename, session_only=session_only, maxlines
        =maxlines)


def camel_to_underscore(name):
    """
    convert CamelCase style to under_score_case
    """
    as_list = []
    length = len(name)
    for index, i in enumerate(name):
        if index != 0 and index != length - 1 and i.isupper():
            as_list.append('_%s' % i.lower())
        else:
            as_list.append(i.lower())
    return ''.join(as_list)


def get_frosting(apk):
    """
    Return True if it has Google Play Store metadata
    """
    apk.parse_v2_v3_signature()
    return 558253134 in apk._v2_blocks


def matrixFromGeometry(shifts, angles, inverseTransform):
    """ Create the transformation matrix from a given
    2D shifts in X and Y...and the 3 euler angles.
    """
    from pwem.convert.transformations import euler_matrix
    from numpy import deg2rad
    radAngles = -deg2rad(angles)
    M = euler_matrix(radAngles[0], radAngles[1], radAngles[2], 'szyz')
    if inverseTransform:
        from numpy.linalg import inv
        M[:3, (3)] = -shifts[:3]
        M = inv(M)
    else:
        M[:3, (3)] = shifts[:3]
    return M


def _process_type(type_):
    """Process the SQLAlchemy Column Type ``type_``.

    Calls :meth:`sqlalchemy.sql.type_api.TypeEngine.compile` on
    ``type_`` to produce a string-compiled form of it.  "string-compiled"
    meaning as it would be used for a SQL clause.
    """
    return type_.compile()


def not_eq(value):
    """Partial evaluation of ``!=``, ``not_eq(a)(b)`` is ``a != b``."""
    return lambda el: value != el


@classmethod
def tree_to_dict(cls, tree):
    """
        Given an OptionTree, convert it into the equivalent dictionary format.
        """
    specs = {}
    for k in tree.keys():
        spec_key = '.'.join(k)
        specs[spec_key] = {}
        for grp in tree[k].groups:
            kwargs = tree[k].groups[grp].kwargs
            if kwargs:
                specs[spec_key][grp] = kwargs
    return specs


def check_categories(lines):
    """
  find out how many row and col categories are available
  """
    rcat_line = lines[0].split('\t')
    num_rc = 0
    found_end = False
    for inst_string in rcat_line[1:]:
        if inst_string == '':
            if found_end is False:
                num_rc = num_rc + 1
        else:
            found_end = True
    max_rcat = 15
    if max_rcat > len(lines):
        max_rcat = len(lines) - 1
    num_cc = 0
    for i in range(max_rcat):
        ccat_line = lines[i + 1].split('\t')
        if ccat_line[0] == '' and len(ccat_line) > 1:
            num_cc = num_cc + 1
    num_labels = {}
    num_labels['row'] = num_rc + 1
    num_labels['col'] = num_cc + 1
    return num_labels


def get_time_delta_from_args(args, prefix, required=True):
    """
    Create an astropy.time.TimeDelta value from argument crated via time_delta_parser.

    :param args: The argument parser result
    :param prefix: the argument used.
    :param required:  Was this argument required?
    :return: An astropy.time.TimeDelta value
    """
    from astropy.time import TimeDelta
    prefix = prefix.replace('-', '_', -1)
    val_name = prefix
    val2_name = prefix + '_val2'
    format_name = prefix + '_format'
    scale_name = prefix + '_scale'
    val = getattr(args, prefix)
    val2 = getattr(args, val2_name)
    format_ = getattr(args, format_name)
    scale = getattr(args, scale_name)
    if required and not val:
        raise SystemExit('missing argument %s' % val_name)
    if (val2 or format_) and not val:
        raise SystemExit('%s or %s cannot be used without %s' % (val2_name,
            format_name, val_name))
    if val:
        return TimeDelta(val, val2, format=format_, scale=scale)
    return None


def image_surface(nb_points):
    """ generate surface from data """
    from skimage import data
    from skimage.util import img_as_float
    from skimage.transform import rescale, resize
    from skimage.color import rgb2gray
    shape = nb_points, nb_points
    image = img_as_float(resize(rgb2gray(data.astronaut()), shape))
    print(image.shape)
    print(type(image))
    return image


def p_specification(t):
    """specification : definition_list"""


def python_3000_has_key(logical_line, noqa):
    """The {}.has_key() method is removed in Python 3: use the 'in' operator.

    Okay: if "alph" in d:\\n    print d["alph"]
    W601: assert d.has_key('alph')
    """
    pos = logical_line.find('.has_key(')
    if pos > -1 and not noqa:
        yield pos, "W601 .has_key() is deprecated, use 'in'"


def retrain(old_model_path, train_args):
    """Train a language model on top of the given language model."""
    from langdist.langmodel import CharLSTM
    char_lstm = CharLSTM.load(old_model_path)
    char_lstm.train(**train_args)


def black_invariant(text, chars=None):
    """Remove characters that may be changed when reformatting the text with black"""
    if chars is None:
        chars = [' ', '\t', '\n', ',', "'", '"', '(', ')', '\\']
    for char in chars:
        text = text.replace(char, '')
    return text


@classmethod
def delete_exception_handler(cls, handler):
    """Removes a L{ExceptionHandler} from the HTTP client
        @warning: SHOULD ONLY BE CALLED FROM A PROVIDER THROUGH A TEST
                  FIXTURE
        """
    if handler in cls._exception_handlers:
        cls._exception_handlers.remove(handler)


def p_CallbackRestOrInterface(p):
    """CallbackRestOrInterface : CallbackRest"""
    p[0] = p[1]


def toBCD(n):
    """Converts the number n into Binary Coded Decimal."""
    bcd = 0
    bits = 0
    while True:
        n, r = divmod(n, 10)
        bcd |= r << bits
        if n is 0:
            break
        bits += 4
    return bcd


@staticmethod
def human_size(size, precision=2):
    """
        Humanize accepted bytes
        :param int size: bytes
        :param int precision: delimiter
        :return:
        """
    suffixes = ['B', 'KB', 'MB', 'GB', 'TB']
    suffix_index = 0
    size = int(size)
    while size > 1024 and suffix_index < 4:
        suffix_index += 1
        size /= 1024
    return '%.*f%s' % (precision, size, suffixes[suffix_index])


def is_mock(obj):
    """Determine if the given argument is a mock type."""
    return hasattr(obj, 'hypothesis_internal_is_this_a_mock_check')


@classmethod
def use_trusted_connection(cls, use_trusted=False):
    """
        pass True to this class method to enable Windows
        Authentication (i.e. passwordless auth)
        """
    cls._use_trusted_connection = use_trusted


@classmethod
def from_file_map(klass, file_map, *, mmap=True, keep_file_open=None):
    """ Class method to create image from mapping in ``file_map``

        .. deprecated:: 2.4.1
            ``keep_file_open='auto'`` is redundant with `False` and has
            been deprecated. It raises an error as of nibabel 3.0.

        Parameters
        ----------
        file_map : dict
            Mapping with (kay, value) pairs of (``file_type``, FileHolder
            instance giving file-likes for each file needed for this image
            type.
        mmap : {True, False, 'c', 'r'}, optional, keyword only
            `mmap` controls the use of numpy memory mapping for reading image
            array data.  If False, do not try numpy ``memmap`` for data array.
            If one of {'c', 'r'}, try numpy memmap with ``mode=mmap``.  A
            `mmap` value of True gives the same behavior as ``mmap='c'``.  If
            image data file cannot be memory-mapped, ignore `mmap` value and
            read array from file.
        keep_file_open : { None, True, False }, optional, keyword only
            `keep_file_open` controls whether a new file handle is created
            every time the image is accessed, or a single file handle is
            created and used for the lifetime of this ``ArrayProxy``. If
            ``True``, a single file handle is created and used. If ``False``,
            a new file handle is created every time the image is accessed.
            If ``file_map`` refers to an open file handle, this setting has no
            effect. The default value (``None``) will result in the value of
            ``nibabel.arrayproxy.KEEP_FILE_OPEN_DEFAULT`` being used.

        Returns
        -------
        img : MGHImage instance
        """
    if mmap not in (True, False, 'c', 'r'):
        raise ValueError("mmap should be one of {True, False, 'c', 'r'}")
    img_fh = file_map['image']
    mghf = img_fh.get_prepare_fileobj('rb')
    header = klass.header_class.from_fileobj(mghf)
    affine = header.get_affine()
    hdr_copy = header.copy()
    data = klass.ImageArrayProxy(img_fh.file_like, hdr_copy, mmap=mmap,
        keep_file_open=keep_file_open)
    img = klass(data, affine, header, file_map=file_map)
    return img


@staticmethod
def get_or_new_from_json_dict(data, cls):
    """Get `cls` object w/ deserialization from json if needed.

        If data is instance of cls, return data.
        Else if data is instance of dict, create instance from dict.
        Else, return None.

        :param data:
        :param cls:
        :rtype: object
        :return:
        """
    if isinstance(data, cls):
        return data
    elif isinstance(data, dict):
        return cls.new_from_json_dict(data)
    return None


def zerocopy_to_numpy(input):
    """Create a numpy ndarray that shares the input memory.

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

    Returns
    -------
    numpy.ndarray
        A numpy ndarray.
    """
    pass


def no_separators_or_newlines(string, separator='\t'):
    """Replace new lines and separators with spaces, semicolons or tabs.

    Parameters
    ----------
    string : str
        A string containing new lines and separators such as tabs,
        and commas.
    separator : str, optional
        A string that defines the type of separator. By default this is
        set to tabs.

    Returns
    -------
    str
        The passed 'string' with replacements depending on the value of 'separator'.
        If 'separator' was set to tab:
            New lines replaced with spaces, tabs replaced with spaces.
        If 'separator' was set to comma:
            New lines replaced with tabs, commas replaced with semicolons.
        If 'separator' was set to anything else:
            New lines replaced with tabs, 'separator' replaced with tabs.

    Examples
    --------
    >>> no_separators_or_newlines('This\\tis\\nSparta!')
    'This is Sparta!'

    >>> no_separators_or_newlines('This,is\\nSparta!', separator=',')
    'This;is    Sparta!'

    >>> no_separators_or_newlines('This;is\\nSparta!', separator=';')
    'This   is  Sparta!'
    """
    if separator == '\t':
        string = string.replace('\n', ' ')
        return string.replace('\t', ' ')
    elif separator == ',':
        string = string.replace('\n', '\t')
        return string.replace(',', ';')
    else:
        string = string.replace('\n', '\t')
        return string.replace(separator, '\t')


def find_tree(gi, found_lib, folders):
    """
    Look for a directory structure in the given library.
    Returns the id of the last folder of the tree if it was completely found
    """
    dist_folders = gi.libraries.get_folders(found_lib)
    dist_f = {}
    for f in dist_folders:
        dist_f[f['name']] = f
    path = ''
    last_f_id = None
    for f in folders:
        path += '/' + f
        if path in dist_f:
            print('Found folder ' + f)
            last_f_id = dist_f[path]['id']
        else:
            raise Exception("Did not find folder '" + f + "'")
    return last_f_id


def isoformat(dt):
    """Return iso-formatted timestamp

    Like .isoformat(), but uses Z for UTC instead of +00:00
    """
    return dt.isoformat().replace('+00:00', 'Z')


@classmethod
def from_origin(cls, value):
    """
        Convert original Python`s bytes instance into Bytes
        :param value:  bytes instance to convert
        :return: Bytes instance
        """
    return cls(value)


def MakeTimecodeString(seconds, fmt='hh:MM:SS.FFF'):
    """
	Convert a number of seconds into a colon-delimited timecode
	string, according to the formatting specified by `fmt`.

	NB: `fmt` is not interpreted character-by-character, merely
	checked for *whether or not it contains* certain characters:
	D/d for days, H/h for hours, M/m for minutes, S/s for
	seconds, and F/f for fractions-of-a-second.  Upper-case
	characters indicate mandatory inclusion, whereas lower-case
	letters indicate discretionary inclusion---for example, if
	`fmt` contains H, hours will always get formatted even if
	the number of hours is zero; if `fmt` contains h instead of
	H, hours will get formatted if and only if necessary (i.e.
	if `seconds` >= 3600). If there's no H or h character, you
	will simply see a numbers of minutes larger than 60, when
	appropriate.

	The number of occurrences of each character dictates the
	width of the corresponding field, unless otherwise
	constrained.

	Higher-order fields override the settings for lower-order
	ones. For example, if hours are getting formatted, minutes
	will always also get formatted, and always with width 2,
	regardless of the presence, absence or count of M and m
	characters.
	"""
    s = '-' if seconds < 0 else ''
    seconds = abs(seconds)
    fmtLower = fmt.lower()
    includeDays = 'D' in fmt or 'd' in fmt and seconds >= 86400
    includeHours = 'H' in fmt or 'h' in fmt and seconds >= 3600 or includeDays
    includeMinutes = 'M' in fmt or 'm' in fmt and seconds >= 60 or includeHours
    dayWidth = fmtLower.count('d')
    hourWidth = 2 if includeDays else fmtLower.count('h')
    minuteWidth = 2 if includeHours else fmtLower.count('m')
    secondWidth = 2 if includeMinutes else fmtLower.count('s')
    decimalPlaces = fmtLower.count('f') if 'F' in fmt or seconds != round(
        seconds) else 0
    if decimalPlaces:
        secondWidth += 1 + decimalPlaces
    seconds = round(seconds * 10 ** (decimalPlaces + 1)
        ) // 10 * 10 ** -decimalPlaces
    if includeDays:
        days = seconds // 86400
        seconds -= days * 86400
        s += '%0{}d:'.format(dayWidth) % days
    if includeHours:
        hours = seconds // 3600
        seconds -= hours * 3600
        s += '%0{}d:'.format(hourWidth) % hours
    if includeMinutes:
        minutes = seconds // 60
        seconds -= minutes * 60
        s += '%0{}d:'.format(minuteWidth) % minutes
    s += '%0{}.{}f'.format(secondWidth, decimalPlaces) % seconds
    return s


@staticmethod
def is_match(item, expressions):
    """Check if item matches expressions.

        :param item: Item
        :type item: byte.model.Model

        :param expressions: Expressions
        :type expressions: list of byte.base.BaseExpression
        """
    for expression in expressions:
        if not expression.execute(item):
            return False
    return True


def dataframe(url, downloader='default', *args, **kwargs):
    """Parse an App url and return a Pandas dataframe"""
    from . import parse_app_url
    import pandas as pd
    from itertools import islice
    u = parse_app_url(url, downloader=downloader, **kwargs)
    r = u.get_resource()
    t = r.get_target()
    g = t.generator
    try:
        return g.dataframe(*args, **kwargs)
    except AttributeError:
        pass
    headers = next(islice(g, 0, 1))
    data = islice(g, 1, None)
    df = pd.DataFrame(list(data), *args, columns=headers, **kwargs)
    df.metatab_errors = g.errors if hasattr(g, 'errors') and g.errors else {}
    return df


def plural(items, word):
    """Return number of items followed by the right form  of ``word``.

    ``items`` can either be an int or an object whose cardinality can be
    discovered via `len(items)`.

    The plural of ``word`` is assumed to be made by adding an ``s``.

    """
    item_count = items if isinstance(items, int) else len(items)
    word = word if item_count == 1 else word + 's'
    return '{0} {1}'.format(item_count, word)


def list_param(current_scene_db, query_start, query_end):
    """returns a list of set parameters in the scene"""
    from src.praxxis.sqlite import connection
    conn = connection.create_connection(current_scene_db)
    cur = conn.cursor()
    list_param = 'SELECT * FROM "Parameters" ORDER BY Parameter DESC LIMIT ?,?'
    cur.execute(list_param, (query_start, query_end))
    conn.commit()
    rows = cur.fetchall()
    conn.close()
    return rows


@staticmethod
def _fqrn(resource_type, project, resource):
    """Return a fully qualified resource name for Cloud Pub/Sub.

        :param resource_type:
        :param project:
        :param resource:
        :rtype: str
        """
    return 'projects/{0}/{1}/{2}'.format(project, resource_type, resource)


@staticmethod
def get_alexa_slot_value(data, slot=None):
    """Gets values for slots from the interaction model.

        Args:
            data: The request data received from Alexa.
            slot: Name of the slot. If a name is not specified, all slots will be returned as
                a dictionary. If a name is specified but is not found, None will be returned.

        Returns:
            A ``string`` representing the value of the slot from the interaction model, or a ``hash`` of slots.

        Examples:
            >>> beer_type = ADAPI.get_alexa_intent(data, "beer_type")
            >>> all_slots = ADAPI.get_alexa_intent(data)

        """
    if 'request' in data and 'intent' in data['request'] and 'slots' in data[
        'request']['intent']:
        if slot is None:
            return data['request']['intent']['slots']
        elif slot in data['request']['intent']['slots'] and 'value' in data[
            'request']['intent']['slots'][slot]:
            return data['request']['intent']['slots'][slot]['value']
        else:
            return None
    else:
        return None


def timedelta_fits_into(short_td, long_td):
    """Return true if multiple short timedeltas fit exactly into long timedelta"""
    return long_td.total_seconds() % short_td.total_seconds() == 0


def isAdmin():
    """
    If the user is admin, return True.
    """
    import sys, os, traceback, types
    if os.name == 'nt':
        import ctypes
        try:
            return ctypes.windll.shell32.IsUserAnAdmin()
        except:
            traceback.print_exc()
            return False
    elif os.name == 'posix':
        return os.getuid() == 0
    else:
        pass


def connectionLost(reason):
    """
        Called when the connection is shut down.

        Clear any circular references here, and any external references
        to this Protocol.  The connection has been closed. The C{reason}
        Failure wraps a L{twisted.internet.error.ConnectionDone} or
        L{twisted.internet.error.ConnectionLost} instance (or a subclass
        of one of those).

        @type reason: L{twisted.python.failure.Failure}
        """


def next_color():
    """
    Return the next color in the plot color cycle.

    Example::

        from matplotlib import pyplot as plt
        from bumps.plotutil import next_color, dhsv
        color = next_color()
        plt.errorbar(x, y, yerr=dy, fmt='.', color=color)
        # Draw the theory line with the same color as the data, but darker
        plt.plot(x, y, '-', color=dhsv(color, dv=-0.2))
    """
    import pylab
    lines = pylab.gca()._get_lines
    try:
        base = next(lines.prop_cycler)['color']
    except Exception:
        try:
            base = next(lines.color_cycle)
        except Exception:
            base = lines._get_next_cycle_color()
    return base


def warn(warning: str):
    """
	Logs a warning to stderr.
	"""
    from sys import stderr
    from time import ctime
    if stderr.isatty():
        print('\x1b[38;2;238;216;78mWW:', warning, '-\t', ctime(), '\x1b[m',
            file=stderr)
    else:
        print('WW:', warning, '-\t', ctime(), file=stderr)


@classmethod
def instance(cls):
    """Returns the single instance of this class.
        """
    assert cls._instance, 'Create an instance of this class first'
    return cls._instance


def find(predicate, seq):
    """A helper to return the first element found in the sequence
    that meets the predicate. For example: ::

        member = find(lambda m: m.name == 'Mighty', channel.server.members)

    would find the first :class:`Member` whose name is 'Mighty' and return it.
    If an entry is not found, then ``None`` is returned.

    This is different from `filter`_ due to the fact it stops the moment it finds
    a valid entry.

    .. _filter: https://docs.python.org/3.6/library/functions.html#filter

    Parameters
    -----------
    predicate
        A function that returns a boolean-like result.
    seq : iterable
        The iterable to search through.
    """
    for element in seq:
        if predicate(element):
            return element
    return None


def get_name(friendly=False):
    """Get name of this resource

    :return: name of this resource
    :rtype: str
    """
    if friendly:
        return 'Alignak command'
    return 'command'


def strip_prefix_from_dict_values(input_dict, prefix):
    """Remove a given prefix from every item in a dict"""
    for key in list(input_dict.keys()):
        if key in ['output_dir', 'input_bam']:
            continue
        if isinstance(input_dict[key], str) and input_dict[key].startswith(
            prefix):
            input_dict[key] = input_dict[key][len(prefix):].strip('/')
    return input_dict


def cmdline_generator(param_iter, PathToBin=None, PathToCmd=None,
    PathsToInputs=None, PathToOutput=None, PathToStderr='/dev/null',
    PathToStdout='/dev/null', UniqueOutputs=False, InputParam=None,
    OutputParam=None):
    """Generates command lines that can be used in a cluster environment

    param_iter : ParameterIterBase subclass instance
    PathToBin : Absolute location primary command (i.e. Python)
    PathToCmd : Absolute location of the command
    PathsToInputs : Absolute location(s) of input file(s)
    PathToOutput : Absolute location of output file
    PathToStderr : Path to stderr
    PathToStdout : Path to stdout
    UniqueOutputs : Generate unique tags for output files
    InputParam : Application input parameter (if not specified, assumes
        stdin is to be used)
    OutputParam : Application output parameter (if not specified, assumes
        stdout is to be used)
    """
    if not PathsToInputs:
        raise ValueError('No input file(s) specified.')
    if not PathToOutput:
        raise ValueError('No output file specified.')
    if not isinstance(PathsToInputs, list):
        PathsToInputs = [PathsToInputs]
    if PathToBin is None:
        PathToBin = ''
    if PathToCmd is None:
        PathToCmd = ''
    if PathToStdout is None:
        stdout_ = ''
    else:
        stdout_ = '> "%s"' % PathToStdout
    if PathToStderr is None:
        stderr_ = ''
    else:
        stderr_ = '2> "%s"' % PathToStderr
    if OutputParam is None:
        output = '> "%s"' % PathToOutput
        stdout_ = ''
    else:
        output_param = param_iter.AppParams[OutputParam]
        output_param.on('"%s"' % PathToOutput)
        output = str(output_param)
        output_param.off()
    output_count = 0
    base_command = ' '.join([PathToBin, PathToCmd])
    for params in param_iter:
        for inputfile in PathsToInputs:
            cmdline = [base_command]
            cmdline.extend(sorted(filter(None, map(str, params.values()))))
            if InputParam is None:
                input = '< "%s"' % inputfile
            else:
                input_param = params[InputParam]
                input_param.on('"%s"' % inputfile)
                input = str(input_param)
                input_param.off()
            cmdline.append(input)
            if UniqueOutputs:
                cmdline.append(''.join([output, str(output_count)]))
                output_count += 1
            else:
                cmdline.append(output)
            cmdline.append(stdout_)
            cmdline.append(stderr_)
            yield ' '.join(cmdline)


def split(a):
    """
    Split float64 in two aligned parts.

    Uses the procedure of Shewchuk, 1997,
    Discrete & Computational Geometry 18(3):305-363
    http://www.cs.berkeley.edu/~jrs/papers/robustr.pdf

    """
    c = 134217729.0 * a
    abig = c - a
    ah = c - abig
    al = a - ah
    return ah, al


def _is_neighbour(path0, path1):
    """
        Boolean function. A neighbour has exactly the same path excepted for the last node
    """
    return path0[:-1] == path1[:-1] and path0 != path1


def index_summary(idx, name=None):
    """Summarized representation of an Index.
    """
    n = len(idx)
    if name is None:
        name = idx.__class__.__name__
    if n:
        head = idx[0]
        tail = idx[-1]
        summary = ', {} to {}'.format(head, tail)
    else:
        summary = ''
    return '{}: {} entries{}'.format(name, n, summary)


def broadcast_logical_xor(lhs=None, rhs=None, out=None, name=None, **kwargs):
    """Returns the result of element-wise **logical xor** with broadcasting.

    Example::

       x = [[ 1.,  1.,  0.],
            [ 1.,  1.,  0.]]

       y = [[ 1.],
            [ 0.]]

       broadcast_logical_xor(x, y) = [[ 0.,  0.,  1.],
                                      [ 1.,  1.,  0.]]

    Defined in src/operator/tensor/elemwise_binary_broadcast_op_logic.cc:L190

    Parameters
    ----------
    lhs : NDArray
        First input to the function
    rhs : NDArray
        Second input to the function

    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 string_contains_continuous_characters(value):
    """
    Returns True if the the value passed consists entirely of continuous characters, either forward or reverse.
    This is based on the ASCII decimal value of each character.
    For example, all the following qill return True: '1234567', 'defghij', '98765'
    http://www.asciitable.com/
    """
    previous_forward = None
    previous_backward = None
    for c in value:
        if not previous_forward and not previous_backward:
            previous_forward = previous_backward = ord(c)
            continue
        if ord(c) != previous_forward + 1 and ord(c) != previous_backward - 1:
            return False
        previous_forward = previous_backward = ord(c)
    return True


def p_import_from_plus_2(p):
    """import_from_plus : import_from_plus DOT"""
    p[0] = p[1] + 1


def my_abs(val):
    """
    it seems you can't use a builtin as a filter_func:
    File "C:\\oTreeenv\\lib\\site-packages\\django	emplatease.py", line 1179, in filter
    filter_func._filter_name = name
    AttributeError: 'builtin_function_or_method' object has no attribute '_filter_name'
    """
    return abs(val)


@classmethod
def from_files(cls, *args, **kwargs):
    """
        Construct Corpus object by loading files. See method :meth:`~tmtoolkit.corpus.Corpus.add_files()` for
        available arguments.

        :return: Corpus instance
        """
    return cls().add_files(*args, **kwargs)


def parse_line(line):
    """
    Parses lines of the following form

        Line #|      Hits|         Time| Time per hit|      %|Source code
        ------+----------+-------------+-------------+-------+-----------
             1|         2|   4.1008e-05|   2.0504e-05|  0.00%|import os

    Extracts a dict of (line_number, hits, time, time_per_hit, percentage, code)

    :param line: string
    :return: tuple
    """
    columns = line.split('|')
    return {'line_number': int(columns[0]), 'hits': int(columns[1]), 'time':
        float(columns[2]), 'time_per_hit': float(columns[3]), 'percentage':
        float(columns[4][:-1]), 'code': '|'.join(columns[5:]), 'calls':
        list(), 'calls_from': dict()}


@classmethod
def withToken(cls, token, environment, compression_enabled=True,
    backoff_config=None):
    """ Initialization of the smartobjects client

        The client exposes the Events, Objects, Owners and Search services.
        Initialization will fetch an API token with the id and secret provided.

        :param client_id (string): client_id part of the OAuth 2.0 credentials (available in your dashboard)
        :param client_secret (string): client_secret part of the OAuth 2.0 credentials (available in your dashboard)
        :param environment: a URL to the targeted environment (Environments.Sandbox or Environments.Production can be used)
            (note: client_id and client_secret are unique per environment)
        :param compression_enabled: gzip compress the request body (default: True)
        :param backoff_config: retry with exponential backoff (default: None)

        :note: Do not expose publicly code containing your client_id and client_secret
        .. seealso:: examples/simple_workflow.py
        """
    return cls(client_id=None, client_secret=None, environment=environment,
        compression_enabled=compression_enabled, backoff_config=
        backoff_config, token_override=token)


def delta_seconds(before, after):
    """Return the difference between two timing objects.

    Compute the difference in seconds between two date, time, or
    datetime objects (as a float, to microsecond resolution).
    """
    delta = after - before
    try:
        return delta.total_seconds()
    except AttributeError:
        return delta.days * 24 * 3600 + delta.seconds + float(delta.
            microseconds) / 10 ** 6


def closed_pairwise(iterable):
    """ Return a generator which generate a closed pair wise list from an iterable.
    s -> (s[0],s[1]), (s[1],s[2]), ... (s[N], s[0])
    """
    closed_iterable = list(iterable) + [iterable[0]]
    prev = closed_iterable[0]
    for x in closed_iterable[1:]:
        yield prev, x
        prev = x


def _getcallargs(args, varargname, kwname, varargs, keywords):
    """Gets the dictionary of the parameter name-value of the call."""
    dct_args = {}
    varargs = tuple(varargs)
    keywords = dict(keywords)
    argcount = len(args)
    varcount = len(varargs)
    callvarargs = None
    if argcount <= varcount:
        for n, argname in enumerate(args):
            dct_args[argname] = varargs[n]
        callvarargs = varargs[-(varcount - argcount):]
    else:
        for n, var in enumerate(varargs):
            dct_args[args[n]] = var
        for argname in args[-(argcount - varcount):]:
            if argname in keywords:
                dct_args[argname] = keywords.pop(argname)
        callvarargs = ()
    if varargname is not None:
        dct_args[varargname] = callvarargs
    if kwname is not None:
        dct_args[kwname] = keywords
    dct_args.update(keywords)
    return dct_args


def NoxEq(NO, NO2, D):
    """ Returns the NO and NO2 concentrations in photoequilibrium according to
    a given state, concerving N quantity.
    """
    alpha = D * NO2 / NO
    NO2eq = alpha * (NO2 + NO) / (1 + alpha)
    NOeq = NO2 + NO - NO2eq
    return NOeq, NO2eq


def _read(ifp):
    """
	Read the data in the correct format.
	"""
    return ifp.read()


@classmethod
def get_all(cls, context):
    """Retrieve all applications for the active context.

        Context may be global or tenant scoped.
        """


@classmethod
def normalize(cls, obj):
    """Normalize an object, if possible, to conform to this type.

        Args:
            obj (object): Object to normalize.

        Returns:
            object: Normalized object.

        """
    try:
        obj = float(obj)
    except BaseException:
        pass
    return obj


def __call__(cls, *args, **kwargs):
    """Hook __init__ call to push resource instance into Swimlane client ResourceCache after instantiation"""
    resource_instance = type.__call__(cls, *args, **kwargs)
    resource_instance._swimlane.resources_cache.cache(resource_instance)
    return resource_instance


def create_cache_subnet_group(CacheSubnetGroupName=None,
    CacheSubnetGroupDescription=None, SubnetIds=None):
    """
    Creates a new cache subnet group.
    Use this parameter only when you are creating a cluster in an Amazon Virtual Private Cloud (Amazon VPC).
    See also: AWS API Documentation

    :example: response = client.create_cache_subnet_group(
        CacheSubnetGroupName='string',
        CacheSubnetGroupDescription='string',
        SubnetIds=[
            'string',
        ]
    )

    :type CacheSubnetGroupName: string
    :param CacheSubnetGroupName: [REQUIRED]
            A name for the cache subnet group. This value is stored as a lowercase string.
            Constraints: Must contain no more than 255 alphanumeric characters or hyphens.
            Example: mysubnetgroup

    :type CacheSubnetGroupDescription: string
    :param CacheSubnetGroupDescription: [REQUIRED]
            A description for the cache subnet group.

    :type SubnetIds: list
    :param SubnetIds: [REQUIRED]
            A list of VPC subnet IDs for the cache subnet group.
            (string) --

    :rtype: dict
    :return: {
        'CacheSubnetGroup': {
            'CacheSubnetGroupName': 'string',
            'CacheSubnetGroupDescription': 'string',
            'VpcId': 'string',
            'Subnets': [
                {
                    'SubnetIdentifier': 'string',
                    'SubnetAvailabilityZone': {
                        'Name': 'string'
                    }
                },
            ]
        }
    }

    :returns:
    CreateCacheSubnetGroup
    ModifyCacheSubnetGroup

    """
    pass


def accessed():
    """Determine if the session has been accessed (and so needs to be
        saved).
        """


def repeat_getattr(thing, query):
    """
    Perform a repeated `getattr` operation.

    i.e., when given `repeat_getattr(x, '.y.z')`, will return `x.y.z`.
    """
    if not query:
        return thing
    assert isinstance(query, str)
    if not query.startswith('.'):
        raise Exception("`query` must start with '.', e.g. '.foo.bar.baz'.")
    attribute_names = filter(None, query.split('.'))
    current = thing
    for attribute_name in attribute_names:
        current = getattr(current, attribute_name)
    return current


def select_less():
    """Deselect keyframes on ends of selection islands

    """
    pass


def Broadcast():
    """
    This message type is for delivering some piece of data to all peers in th network.
    It is used to broadcast "crypto-coins" between peers.
    """
    return 'Broadcast'


@staticmethod
def convert_str_unicode_hex_values_to_str(s):
    """Convert string containing hex values to ASCII.

        For example, '680065006c006c006f00' converts to 'hello'
        """
    s = s.replace('00', '')
    result = ''
    try:
        for i in range(0, len(s), 2):
            result += bytearray.fromhex(s[i:i + 2]).decode()
    except (UnicodeDecodeError, ValueError):
        pass
    if result == '':
        return
    return result


def _parse_boolean(xml_boolean):
    """Converts strings "true" and "false" from XML files to Python bool"""
    if xml_boolean is not None:
        assert xml_boolean in ['true', 'false'
            ], 'The boolean string must be "true" or "false"'
        return {'true': True, 'false': False}[xml_boolean]