def Open_landsat(src_FileName, proyDEM_fileName):
    """
    This function opens a landsat image and returns the data array of a specific landsat band.
    """
    import SEBAL.pySEBAL.pySEBAL_code as SEBAL
    ls, ulx, uly, lrx, lry, epsg_to = SEBAL.reproject_dataset_example(
        src_FileName, proyDEM_fileName)
    ls_data = ls.GetRasterBand(1).ReadAsArray()
    return ls_data


def validate_intervals(intervals):
    """Checks that an (n, 2) interval ndarray is well-formed, and raises errors
    if not.

    Parameters
    ----------
    intervals : np.ndarray, shape=(n, 2)
        Array of interval start/end locations.

    """
    if intervals.ndim != 2 or intervals.shape[1] != 2:
        raise ValueError(
            'Intervals should be n-by-2 numpy ndarray, but shape={}'.format
            (intervals.shape))
    if (intervals < 0).any():
        raise ValueError('Negative interval times found')
    if (intervals[:, (1)] <= intervals[:, (0)]).any():
        raise ValueError('All interval durations must be strictly positive')


@classmethod
def _get_fields(cls):
    """
        Aggregates all available fields and their types from the class itself and its superclass
        (assuming it is a configuration as well).

        Returns
        -------
        dict
            Mapping from field names to types.
        """
    annotations = {}
    if hasattr(super(), '_get_fields'):
        annotations = {**annotations, **super()._get_fields()}
    if hasattr(cls, '__annotations__'):
        annotations = {**annotations, **cls.__annotations__}
    return annotations


def lowercase_range(code1, code2):
    """
    If the range of characters from code1 to code2-1 includes any
    upper case letters, return the corresponding lower case range.
    """
    code3 = max(code1, ord('A'))
    code4 = min(code2, ord('Z') + 1)
    if code3 < code4:
        d = ord('a') - ord('A')
        return code3 + d, code4 + d
    else:
        return None


def _orbits_transversals_from_bsgs(base, strong_gens_distr,
    transversals_only=False, slp=False):
    """
    Compute basic orbits and transversals from a base and strong generating set.

    The generators are provided as distributed across the basic stabilizers.
    If the optional argument ``transversals_only`` is set to True, only the
    transversals are returned.

    Parameters
    ==========

    ``base`` - the base
    ``strong_gens_distr`` - strong generators distributed by membership in basic
    stabilizers
    ``transversals_only`` - a flag switching between returning only the
    transversals/ both orbits and transversals
    ``slp`` - if ``True``, return a list of dictionaries containing the
              generator presentations of the elements of the transversals,
              i.e. the list of indices of generators from `strong_gens_distr[i]`
              such that their product is the relevant transversal element

    Examples
    ========

    >>> from sympy.combinatorics import Permutation
    >>> Permutation.print_cyclic = True
    >>> from sympy.combinatorics.named_groups import SymmetricGroup
    >>> from sympy.combinatorics.util import _orbits_transversals_from_bsgs
    >>> from sympy.combinatorics.util import (_orbits_transversals_from_bsgs,
    ... _distribute_gens_by_base)
    >>> S = SymmetricGroup(3)
    >>> S.schreier_sims()
    >>> strong_gens_distr = _distribute_gens_by_base(S.base, S.strong_gens)
    >>> _orbits_transversals_from_bsgs(S.base, strong_gens_distr)
    ([[0, 1, 2], [1, 2]], [{0: (2), 1: (0 1 2), 2: (0 2 1)}, {1: (2), 2: (1 2)}])

    See Also
    ========

    _distribute_gens_by_base, _handle_precomputed_bsgs

    """
    from sympy.combinatorics.perm_groups import _orbit_transversal
    base_len = len(base)
    degree = strong_gens_distr[0][0].size
    transversals = [None] * base_len
    slps = [None] * base_len
    if transversals_only is False:
        basic_orbits = [None] * base_len
    for i in range(base_len):
        transversals[i], slps[i] = _orbit_transversal(degree,
            strong_gens_distr[i], base[i], pairs=True, slp=True)
        transversals[i] = dict(transversals[i])
        if transversals_only is False:
            basic_orbits[i] = list(transversals[i].keys())
    if transversals_only:
        return transversals
    else:
        if not slp:
            return basic_orbits, transversals
        return basic_orbits, transversals, slps


def perform_metadata_inspection(container):
    """
    Prints the metadata of the container to the terminal.

    :param container: the container
    :type container: :class:`surround.data.container.DataContainer`
    """
    metadata = container.metadata
    print('Metadata format version: %s' % metadata['version'])
    print('Summary Metadata:')
    print('  Title:          %s' % metadata['summary']['title'])
    print('  Description:    %s' % metadata['summary']['description'])
    print('  Creator:        %s' % metadata['summary']['creator'])
    print('  Date:           %s' % metadata['summary']['date'])
    print('  Publisher:      %s' % metadata['summary']['publisher'])
    print('  Contributor:    %s' % metadata['summary']['contributor'])
    print('  Subject:        %s' % metadata['summary']['subject'])
    print('  Formats:        %s' % metadata['summary']['formats'])
    print('  Types:          %s' % metadata['summary']['types'])
    print('  Identifier:     %s' % metadata['summary']['identifier'])
    print('  Rights:         %s' % metadata['summary']['rights'])
    print('  Under Ethics:   %s' % metadata['summary']['under-ethics'])
    print('  Language:       %s\n' % metadata['summary']['language'])
    if metadata.get_property('manifests'):
        for manifest in metadata['manifests']:
            print("'%s' Group Metadata:" % manifest['path'])
            print('  Description:   %s' % manifest['description'])
            print('  Language:      %s' % manifest['language'])
            print('  Formats:       %s' % manifest['formats'])
            print('  Types:         %s\n' % manifest['types'])


def maximum_temperature(t_max_bare, t_max_full, vc):
    """
    Computes the maximum temperature at dry conditions

    .. math ::

        T_{0,max} = c_{veg}(T_{c,max}-T_{s,max})+T_{s,max}

    Parameters
    ----------
    t_max_bare : float
        maximum temperature at bare soil
        :math:`T_{s,max}`
        [K]
    t_max_full : float
        maximum temperature at full dry vegetation
        :math:`T_{c,max}`
        [K]
    vc : float
        vegetation cover
        :math:`c_{veg}`
        [-]

    Returns
    -------
    lst_max : float
        maximum temperature at dry conditions
        :math:`T_{0,max}`
        [K]

    """
    return vc * (t_max_full - t_max_bare) + t_max_bare


def add_class_to_node(node, classname):
    """ Adds the given classname to the given lxml node's class list. """
    if 'class' in node.attrib:
        node.attrib['class'] += ' ' + classname
    else:
        node.attrib['class'] = classname


def polyak_average(source, target, alpha):
    """
    [[Source]](https://github.com/seba-1511/cherry/blob/master/cherry/models/utils.py)

    **Description**

    Shifts the parameters of source towards those of target.

    Note: the parameter `alpha` indicates the convex combination weight of the source.
    (i.e. the old parameters are kept at a rate of `alpha`.)

    **References**

    1. Polyak, B., and A. Juditsky. 1992. “Acceleration of Stochastic Approximation by Averaging.”

    **Arguments**

    * **source** (nn.Module) - The module to be shifted.
    * **target** (nn.Module) - The module indicating the shift direction.
    * **alpha** (float) - Strength of the shift.

    **Example**
    ~~~python
    target_qf = nn.Linear(23, 34)
    qf = nn.Linear(23, 34)
    ch.models.polyak_average(target_qf, qf, alpha=0.9)
    ~~~
    """
    for s, t in zip(source.parameters(), target.parameters()):
        s.data.mul_(alpha).add_(t.data, alpha=1.0 - alpha)


def frame(I=None, second=5, saveable=True, name='frame', cmap=None, fig_idx
    =12836):
    """Display a frame. Make sure OpenAI Gym render() is disable before using it.

    Parameters
    ----------
    I : numpy.array
        The image.
    second : int
        The display second(s) for the image(s), if saveable is False.
    saveable : boolean
        Save or plot the figure.
    name : str
        A name to save the image, if saveable is True.
    cmap : None or str
        'gray' for greyscale, None for default, etc.
    fig_idx : int
        matplotlib figure index.

    Examples
    --------
    >>> env = gym.make("Pong-v0")
    >>> observation = env.reset()
    >>> tl.visualize.frame(observation)

    """
    import matplotlib.pyplot as plt
    if saveable is False:
        plt.ion()
    plt.figure(fig_idx)
    if len(I.shape) and I.shape[-1] == 1:
        I = I[:, :, (0)]
    plt.imshow(I, cmap)
    plt.title(name)
    if saveable:
        plt.savefig(name + '.pdf', format='pdf')
    else:
        plt.draw()
        plt.pause(second)


def search_result_generator(page_generator):
    """
    Simple wrapper function to return a generator to iterate through item
    results on the search page
    """
    for page in page_generator:
        for res in page:
            yield res


def dist_rgb_weighted(rgb1, rgb2):
    """
    Determine the weighted distance between two rgb colors.

    :arg tuple rgb1: RGB color definition
    :arg tuple rgb2: RGB color definition
    :returns: Square of the distance between provided colors
    :rtype: float

    Similar to a standard distance formula, the values are weighted
    to approximate human perception of color differences

    For efficiency, the square of the distance is returned
    which is sufficient for comparisons
    """
    red_mean = (rgb1[0] + rgb2[0]) / 2.0
    return (2 + red_mean / 256) * pow(rgb1[0] - rgb2[0], 2) + 4 * pow(rgb1[
        1] - rgb2[1], 2) + (2 + (255 - red_mean) / 256) * pow(rgb1[2] -
        rgb2[2], 2)


def suggestThreadPoolSize(size):
    """
        Suggest the size of the internal threadpool used to dispatch functions
        passed to L{IReactorInThreads.callInThread}.
        """


def resolveMessageIds(message_id_list):
    """Returns a list of message proxies for a given set of message ids"""


def first_defined(*args):
    """
    Finds the first argument that is not None
    :param args: arguments to check for "defineness"
    :return:
    """
    for arg in args:
        if arg is not None:
            return arg
    return None


def pvt(bars):
    """ Price Volume Trend """
    trend = (bars['close'] - bars['close'].shift(1)) / bars['close'].shift(1
        ) * bars['volume']
    return trend.cumsum()


@staticmethod
def volume():
    """ Volume of a composite shape is current undefined, so a negative number is returned (may change) """
    return -1.0


def escape(s, quote=None):
    """Replace special characters "&", "<", ">" and (") to HTML-safe sequences.

    There is a special handling for `None` which escapes to an empty string.

    .. versionchanged:: 0.9
       `quote` is now implicitly on.

    :param s: the string to escape.
    :param quote: ignored.
    """
    if s is None:
        return ''
    elif hasattr(s, '__html__'):
        return str(s.__html__())
    elif not isinstance(s, str):
        s = str(s)
    if quote is not None:
        from warnings import warn
        warn(DeprecationWarning('quote parameter is implicit now'),
            stacklevel=2)
    s = s.replace('&', '&').replace('<', '<').replace('>', '>'
        ).replace('"', '"')
    return s


def isproperty(obj):
    """
    Is this a property?

    >>> class Foo:
    ...     def got(self):
    ...         return 2
    ...     def get(self):
    ...         return 1
    ...     get = property(get)

    >>> isproperty(Foo.got)
    False
    >>> isproperty(Foo.get)
    True
    """
    return type(obj) == property


def has_elements(*args):
    """
    Check if args has elements.

    :param args: a tuple
    :return: returns true if args has elements
    """
    if not args:
        raise ValueError('No elements found!')
    return True


def format_cpus(n):
    """Formats n as a number of CPUs"""
    return '{:.1f}'.format(n)


def initialize_from_paramMat(paramMat):
    """
    Initializes a parameter list. If there is a "START" row, then everything below it will be saved as a list.

    """
    startFlag = 0
    paramDict = dict()
    paramList = list()
    for i in paramMat:
        if startFlag == 0:
            if i[0] == 'START':
                startFlag += 1
            else:
                paramDict[i[0]] = i[1]
        else:
            paramList.append(i)
    paramDict['paramList'] = paramList
    return paramDict


@staticmethod
def p_var_criterion_optional_list(p):
    """var_criterion_optional_list : var_criterion_optional
                                       | var_criterion_optional var_criterion_optional_list"""
    try:
        p[0] = [p[1]] + p[2]
    except IndexError:
        p[0] = [p[1]]


def getid(obj):
    """Abstracts the common pattern of allowing both an object or

    an object's ID (UUID) as a parameter when dealing with relationships.
    """
    try:
        return obj.id
    except AttributeError:
        return obj


def from73(theWord):
    """Returns a integer from a Rep code 0x49, 32bit signed integer."""
    return theWord


def _parse_exon(o):
    """Parse exon information from an Ensembl `overlap` query.

    :param o: A Python dict representing an entry from the response.
    :type o: dict

    :returns: A tuple of (start, end) positions representing the exon.
    :rtype: tuple

    """
    assert o['feature_type'] == 'exon'
    return o['start'], o['end']


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


@staticmethod
def default_done_msg():
    """
        Returns default message.
        """
    return 'Address validation is complete.'


def announce(zelf, *args, **kwargs):
    """
            Announce a text on all channels of all bots.

            args[0] = "text to announce"

            >>> import core.bots
            >>> bot = core.bots.Bot()
            >>> bot.announce("hello")
            hello

        """
    from core.kernel import fleet
    thrs = []
    for bot in fleet:
        thrs.append(zelf.put(bot.announce, *args, **kwargs))
    if thrs:
        zelf.collect(thrs)
    return thrs


@staticmethod
def _generate_fname_md(text):
    """generates markdown for a lookup table file path."""
    return '  {}\n'.format(text)


def gain_com(exp, num, value):
    """Change the pmt gain in a job.

    Return a list with parts for the cam command.
    """
    return [('cmd', 'adjust'), ('tar', 'pmt'), ('num', str(num)), ('exp',
        str(exp)), ('prop', 'gain'), ('value', str(value))]


def get_scale(x):
    """Finds the lowest scale where x <= scale."""
    scales = [20, 50, 100, 200, 400, 600, 800, 1000]
    for scale in scales:
        if x <= scale:
            return scale
    return x


def upload_signing_certificate(UserName=None, CertificateBody=None):
    """
    Uploads an X.509 signing certificate and associates it with the specified IAM user. Some AWS services use X.509 signing certificates to validate requests that are signed with a corresponding private key. When you upload the certificate, its default status is Active .
    If the UserName field is not specified, the IAM user name is determined implicitly based on the AWS access key ID used to sign the request. Because this action works for access keys under the AWS account, you can use this action to manage root credentials even if the AWS account has no associated users.
    See also: AWS API Documentation

    Examples
    The following command uploads a signing certificate for the IAM user named Bob.
    Expected Output:

    :example: response = client.upload_signing_certificate(
        UserName='string',
        CertificateBody='string'
    )

    :type UserName: string
    :param UserName: The name of the user the signing certificate is for.
            This parameter allows (per its regex pattern ) a string of characters consisting of upper and lowercase alphanumeric characters with no spaces. You can also include any of the following characters: =,.@-

    :type CertificateBody: string
    :param CertificateBody: [REQUIRED]
            The contents of the signing certificate.
            The regex pattern used to validate this parameter is a string of characters consisting of any printable ASCII character ranging from the space character (u0020) through end of the ASCII character range as well as the printable characters in the Basic Latin and Latin-1 Supplement character set (through u00FF). It also includes the special characters tab (u0009), line feed (u000A), and carriage return (u000D).

    :rtype: dict
    :return: {
        'Certificate': {
            'UserName': 'string',
            'CertificateId': 'string',
            'CertificateBody': 'string',
            'Status': 'Active'|'Inactive',
            'UploadDate': datetime(2015, 1, 1)
        }
    }

    """
    pass


def write_simple_ner_dataset(sentences: list, entitites: list, file_path: str):
    """
    Writes a dataset in the simple NER format similar to
    the CoNLL 2003 NER format.

    :param sentences:
    :param entitites:
    :param file_path:
    """
    with open(file_path, 'w', encoding='utf8') as f:
        for ss, es in zip(sentences, entitites):
            for s, e in zip(ss, es):
                f.write('{} {}\n'.format(s, e))
            f.write('\n')


def subparser(subparsers):
    """Define the `kevlar novel` command-line interface."""
    desc = """    Construct a graph to group reads by shared interesting k-mers. Nodes in the
    graph represent reads, and edges between a pair of nodes indicate that the
    two corresponding reads have one or more interesting k-mers in common.
    Connected components in the undirected graph correspond to distinct
    variants (or variant-related breakpoints).
    """
    subparser = subparsers.add_parser('partition', description=desc)
    subparser.add_argument('-s', '--strict', action='store_true', help=
        'require perfect identity between overlapping reads for inclusion in the same partition; by default, only a shared interesting k-mer is required'
        )
    subparser.add_argument('--min-abund', metavar='X', type=int, default=2,
        help='ignore k-mers with abundance lower than X; default is 2')
    subparser.add_argument('--max-abund', metavar='Y', type=int, default=
        200, help='ignore k-mers with abundance higher than Y; default is 200')
    subparser.add_argument('--no-dedup', dest='dedup', action='store_false',
        default=True, help='skip step to remove duplicates')
    subparser.add_argument('--gml', metavar='FILE', help=
        'write read graph to .gml file')
    subparser.add_argument('--split', type=str, metavar='OUTPREFIX', help=
        'write each partition to a separate output file, each with a filename like "OUTPREFIX.cc#.augfastq.gz"'
        )
    subparser.add_argument('-o', '--out', metavar='FILE', help=
        'output file; default is terminal (stdout)')
    subparser.add_argument('infile', help=
        'input reads in augmented Fast[q|a] format')


@staticmethod
def check_understood_rrule(rrule):
    """test if we can reproduce `rrule`."""
    keys = set(rrule.keys())
    freq = rrule.get('FREQ', [None])[0]
    unsupported_rrule_parts = {'BYSECOND', 'BYMINUTE', 'BYHOUR',
        'BYYEARDAY', 'BYWEEKNO', 'BYMONTH'}
    if keys.intersection(unsupported_rrule_parts):
        return False
    if len(rrule.get('BYMONTHDAY', [1])) > 1:
        return False
    if rrule.get('BYMONTHDAY', [1])[0] < 1:
        return False
    if rrule.get('BYDAY', ['1'])[0][0] == '-':
        return False
    if rrule.get('BYSETPOS', [1])[0] != 1:
        return False
    if freq not in ['DAILY', 'WEEKLY', 'MONTHLY', 'YEARLY']:
        return False
    if 'BYDAY' in keys and freq == 'YEARLY':
        return False
    return True


def create_mp_description(description_format, lines):
    """Create a merge proposal description.

    Args:
      lines: List of one-line descriptions of fixes
    Returns:
      A string with a merge proposal description
    """
    if len(lines) > 1:
        mp_description = ['Fix some issues reported by lintian\n']
        for line in lines:
            line = '* %s\n' % line
            if line not in mp_description:
                mp_description.append(line)
    else:
        mp_description = lines[0]
    return ''.join(mp_description)


def pack_bits(bits):
    """convert a bit (bool or int) tuple into a int"""
    packed = 0
    level = 0
    for bit in bits:
        if bit:
            packed += 2 ** level
        level += 1
    return packed


@classmethod
def convert_ranges(cls, ranges, length):
    """Converts to valid byte ranges"""
    result = []
    for start, end in ranges:
        if end is None:
            result.append((start, length - 1))
        elif start is None:
            s = length - end
            result.append((0 if s < 0 else s, length - 1))
        else:
            result.append((start, end if end < length else length - 1))
    return result


def get_return_data_type(func_name):
    """Return a somewhat-helpful data type given a function name"""
    if func_name.startswith('get_'):
        if func_name.endswith('_list'):
            return 'List'
        elif func_name.endswith('_count'):
            return 'Integer'
    return ''


def insert_explicit_nulls(unischema, row_dict):
    """If input dictionary has missing fields that are nullable, this function will add the missing keys with
    None value.

    If the fields that are missing are not nullable, a ``ValueError`` is raised.

    :param unischema: An instance of a unischema
    :param row_dict: dictionary that would be checked for missing nullable fields. The dictionary is modified inplace.
    :return: None
    """
    for field_name, value in unischema.fields.items():
        if field_name not in row_dict:
            if value.nullable:
                row_dict[field_name] = None
            else:
                raise ValueError(
                    'Field {} is not found in the row_dict, but is not nullable.'
                    .format(field_name))


def expired():
    """True indicates the cached item is expired"""


def is_valid_default_handler(handler):
    """Returns `True` if the `handler` is a valid default handler, as
    described in the `IRequestHandler` interface documentation.
    """
    return handler and getattr(handler, 'is_valid_default_handler', True)


@classmethod
def from_data(cls, data):
    """Construct a frame from its data representation.

        Parameters
        ----------
        data : :obj:`dict`
            The data dictionary.

        Returns
        -------
        :class:`compas.geometry.Frame`
            The constructed frame.

        Examples
        --------
        >>> data = {'point': [0.0, 0.0, 0.0], 'xaxis': [1.0, 0.0, 0.0], 'yaxis': [0.0, 1.0, 0.0]}
        >>> frame = Frame.from_data(data)
        >>> frame.point
        Point(0.000, 0.000, 0.000)
        >>> frame.xaxis
        Vector(1.000, 0.000, 0.000)
        >>> frame.yaxis
        Vector(0.000, 1.000, 0.000)
        """
    frame = cls.worldXY()
    frame.data = data
    return frame


def get_routing_list(app):
    """Make a sumple list of routing rules.

    :param app: Flask application
    :returns: list of routes
    """
    routes = []
    for route in app.url_map.iter_rules():
        routes.append({'uri': route.rule, 'methods': sorted(list(route.
            methods)), 'endpoint': route.endpoint})
    routes.sort(key=lambda d: d['uri'])
    return routes


def token_generator():
    """
    Generate Token number up to 2**8.
    This token is used for client server communication.
    :return: int
    """
    token, max_token = 1, pow(2, 8)
    while True:
        yield token
        token += 1
        if token >= max_token:
            token = 1


def resolve_order_item_class_name(labels):
    """
    Returns an OrderItem class name for provided class.
    """
    return '%sOrderItem' % labels['model']


def version():
    """
    Return server version

    :return: server version
    :retype: str
    """
    return '1.0'


def _cln(s):
    """
    Clean a string of comments, newlines
    """
    return s.split('!')[0].strip()


@classmethod
def validate_faces(cls, faces):
    """Raises an exception if not all faces in ``faces`` are defining either all triangles, lines
        or points.

        Parameters
        ----------
        faces : list

        Returns
        -------

        """
    if not faces:
        return
    if len(faces[0]) > 3:
        raise Exception(
            'Invalid mesh. Expected mesh composed of points, lines xor triangles.'
            )
    for face in faces:
        if len(face) != len(faces[0]):
            raise NotImplementedError(
                'Invalid mesh. Expected mesh composed of points, lines xor triangles.'
                )


def is_numeric(s):
    """
    Determine if a ``pandas.Series`` or ``numpy.ndarray`` is numeric
    from its dtype.
    """
    return s.dtype.kind in 'iufc'


def string_list_to_float_list(x):
    """
    Convert a list of strings to a list of floats, where a string value of '-' is mapped to a
    floating point value of -1.0, and an empty input list produces a length-10 list of -1.0's.

    Parameters
    ----------
    x : list
        The list of strings to convert

    Returns
    -------
    res : list of floats
        The converted results.
    """
    npts = len(x)
    if npts == 0 or npts == 1 and x[0].strip() == '-':
        return [-1.0] * 10
    res = []
    for a in x:
        if a.strip() == '-':
            res.append(-1.0)
        else:
            res.append(float(a))
    return res


@staticmethod
def process_source_covariates(covariates):
    """Process source covariates before saving them.

        This method is applied to the source covariates before they are saved.
        The method can be used to compute derived covariates

        Parameters
        ----------
        covariates : float[]
            Covariates describing the repulsiveness of sources

        """
    return covariates


def PercentileRow(array, p):
    """Selects the row from a sorted array that maps to percentile p.

    p: float 0--100

    returns: NumPy array (one row)
    """
    rows, cols = array.shape
    index = int(rows * p / 100)
    return array[index,]


def _security_filters(requirements):
    """Produce set of filters associated with the security requirements."""
    result = set()
    for requirement in (requirements or []):
        scheme = getattr(requirement, 'scheme', None)
        if scheme:
            filter = getattr(scheme, 'filter', None)
            if filter:
                result.add(filter)
    return result


def mrtrix_dti(name='MRTrix_DTI'):
    """
    A workflow for DTI reconstruction using the tensor fitting included with
    MRTrix.
    :inputs:
        * in_dwi: the input dMRI volume to be reconstructed
        * in_bvec: b-vectors file in FSL format
        * in_bval: b-values file in FSL format
        * in_mask: input whole-brain mask (dwi space)
    """
    from nipype.pipeline import engine as pe
    from nipype.interfaces import utility as niu
    from nipype.interfaces import mrtrix as mrt
    from nipype.interfaces import freesurfer as fs
    inputnode = pe.Node(niu.IdentityInterface(fields=['in_bvec', 'in_bval',
        'in_dwi', 'in_mask']), name='inputnode')
    outputnode = pe.Node(niu.IdentityInterface(fields=['fa', 'md']), name=
        'outputnode')
    fsl2mrtrix = pe.Node(mrt.FSL2MRTrix(), name='fsl2mrtrix')
    dwi2tsr = pe.Node(mrt.DWI2Tensor(), name='DWI2Tensor')
    tsr2fa = pe.Node(mrt.Tensor2FractionalAnisotropy(), name='ComputeFA')
    fa2nii = pe.Node(mrt.MRConvert(extension='nii'), 'FA2Nifti')
    msk_fa = pe.Node(fs.ApplyMask(), name='MaskFA')
    tsr2adc = pe.Node(mrt.Tensor2ApparentDiffusion(), name='ComputeADC')
    adc2nii = pe.Node(mrt.MRConvert(extension='nii'), 'ADC2Nifti')
    msk_adc = pe.Node(fs.ApplyMask(), name='MaskADC')
    wf = pe.Workflow(name=name)
    wf.connect([(inputnode, fsl2mrtrix, [('in_bvec', 'bvec_file'), (
        'in_bval', 'bval_file')]), (inputnode, dwi2tsr, [('in_dwi',
        'in_file')]), (inputnode, msk_fa, [('in_mask', 'mask_file')]), (
        inputnode, msk_adc, [('in_mask', 'mask_file')]), (fsl2mrtrix,
        dwi2tsr, [('encoding_file', 'encoding_file')]), (dwi2tsr, tsr2fa, [
        ('tensor', 'in_file')]), (tsr2fa, fa2nii, [('FA', 'in_file')]), (
        fa2nii, msk_fa, [('converted', 'in_file')]), (dwi2tsr, tsr2adc, [(
        'tensor', 'in_file')]), (tsr2adc, adc2nii, [('ADC', 'in_file')]), (
        adc2nii, msk_adc, [('converted', 'in_file')]), (msk_fa, outputnode,
        [('out_file', 'fa')]), (msk_adc, outputnode, [('out_file', 'md')])])
    return wf


def ceil_div(num, div):
    """
    Returns the ceiling function of a division between `num` and `div`.

    Usage::

        >>> ceil_div(100, 7)
        15
        >>> ceil_div(100, 10)
        10
        >>> ceil_div(1, 4)
        1

    :param num: Division's numerator, a number
    :param div: Division's divisor, a number

    :return: Rounded up result of the division between the parameters.
    """
    quanta, mod = divmod(num, div)
    if mod:
        quanta += 1
    return quanta


def is_similarity(estimator):
    """Returns True if the given estimator encode a distance."""
    return getattr(estimator, '_estimator_type', None) == 'similarity'


def _property_name(name):
    """
    Returns the property name string.

    Parameters
    ----------
    name : str
        The name of the property to be created.
    """
    if not isinstance(name, str):
        raise ValueError('Property name {!r} must be a string.'.format(name))
    return '_{}'.format(name)


def package_root(varmap):
    """Return correct directory for the root package.

    The "root" package is the one where modules which do not
    belong to a package are located (see the distutils docs).
    This function should not need to be called directly in
    your actual setup script, but it can be useful for testing.
    Note that it looks for a ``package_root`` setup var, which
    can be used as a shortcut if your "root" package is not in
    the standard place (which is your setup script directory),
    rather than having to declare a ``package_dir`` dictionary
    with a ``''`` key.
    """
    try:
        return varmap['package_dir']['']
    except KeyError:
        try:
            result = varmap['package_root']
        except KeyError:
            return '.'
        else:
            dirmap = varmap.setdefault('package_dir', {})
            if '' not in dirmap:
                dirmap[''] = result
            return result


def slide(align: bool=False, select: bool=True):
    """Select and slide paint curve point

    :param align: Align Handles, Aligns opposite point handle during transform
    :type align: bool
    :param select: Select, Attempt to select a point handle before transform
    :type select: bool
    """
    pass


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

    :return: name of this resource
    :rtype: str
    """
    if friendly:
        return 'Alignak time period'
    return 'timeperiod'


def frame2ms(frame, fps):
    """
    Converts frames to milliseconds.

    Parameters
    ----------
    - frame : int

        The index of the frame to be converted to milliseconds.
    - fps : int

        Frames per second.

    Returns
    -------
    - int

        The rounded millisecond value of the input frame index.
    """
    return round(frame / fps * 1000)


def adjust_val_to_360(val):
    """
    Take in a single numeric (or null) argument.
    Return argument adjusted to be between
    0 and 360 degrees.
    """
    if not val and val != 0:
        return None
    else:
        try:
            return float(val) % 360
        except ValueError:
            return val


def description(filename):
    """Provide a short description."""
    with open(filename) as fp:
        for lineno, line in enumerate(fp):
            if lineno < 3:
                continue
            line = line.strip()
            if len(line) > 0:
                return line


def surface_slot_remove():
    """Remove the selected surface slot

    """
    pass


def setAlignmentMethod(method):
    """Set pairwise alignment method (global or local)."""
    if method in ('local', 'global'):
        global ALIGNMENT_METHOD
        ALIGNMENT_METHOD = method
    else:
        raise ValueError('method must be "local" or "global"')


@staticmethod
def resolve_problem_id(id_in):
    """Codeforces problems are encoded with uppercase latin letters. This
        function handles conversion from:

            - lowercase latin letters,
            - numbers.

        >>> SiteCodeforces.resolve_problem_id('A')
        'A'

        >>> SiteCodeforces.resolve_problem_id('z')
        'Z'

        >>> SiteCodeforces.resolve_problem_id('3')
        'C'

        >>> SiteCodeforces.resolve_problem_id('.') is None
        True
        """
    if isinstance(id_in, str):
        if id_in.isalpha() and len(id_in) == 1:
            return id_in.upper()
        if id_in.isdigit():
            id_out = chr(ord('A') + int(id_in) - 1)
            if id_out.isalpha():
                return id_out
    return None


def _call_it(params):
    """indirect caller for instance methods and multiprocessing"""
    instance, name, args = params
    kwargs = {}
    return getattr(instance, name)(*args, **kwargs)


def reverse_enumerate(iterable):
    """
    The same as `enumerate` except in reverse order

    reverse_enumerate(iterable) -> iterator for index, value of iterable

    Return an enumerate object.  iterable must be another object that supports
    iteration.  The enumerate object yields pairs containing a count and a value yielded by the iterable argument.
    reverse_enumerate is useful for obtaining an indexed list in reverse order:
        (len(seq) - 1, seq[-1]), (len(seq) - 2, seq[-2]), (len(seq) - 3, seq[-3]), ...
    """
    return zip(range(len(iterable) - 1, -1, -1), reversed(iterable))


def p_range_stmt(p):
    """ range_stmt : RANGE range_addr_stmt SEMICOLON
                   | RANGE DYNAMIC_BOOTP range_addr_stmt SEMICOLON
    """
    if len(p) > 4:
        p[0] = {p[1]: p[3]}
    else:
        p[0] = {p[1]: p[2]}


def to_bool(obj):
    """Convert a boolean-like object.

    >>> to_bool(1)
    True

    >>> to_bool(0)
    False

    >>> to_bool(' True ')
    True

    >>> to_bool('F')
    False

    """
    if isinstance(obj, str):
        return obj.lower().strip() in ('yes', 'true', 'enabled', '1')
    else:
        return bool(obj)


def get_parser_from_config(base_config, attributes, default_parser):
    """
    Checks the various places that the parser option could be set and returns
    the value with the highest precedence, or `default_parser` if no parser was found
    @param base_config: a set of log config options for a logfile
    @param attributes: a set of attributes to apply to a logfile
    @param default_parser: the default parser if no parser setting is found in base_config or attributes
    """
    if 'attributes' in base_config and 'parser' in base_config['attributes']:
        return base_config['attributes']['parser']
    if 'parser' in base_config:
        return base_config['parser']
    if 'parser' in attributes:
        return attributes['parser']
    return default_parser


def _check_method(estimator, method):
    """Check that an estimator has the method attribute.

    If method == 'transform'  and estimator does not have 'transform', use
    'predict' instead.
    """
    if method == 'transform' and not hasattr(estimator, 'transform'):
        method = 'predict'
    if not hasattr(estimator, method):
        ValueError('base_estimator does not have `%s` method.' % method)
    return method


def distance_index(i, j, length):
    """Helper function to calculate the distance between two indices in a
    circular HMM.

    Args:
        i (int): first index
        j (int): second index
        length (int): length of the HMM

    Returns:
        int: The distance between the indices ``i`` and ``j``: As the HMM
        is circular ``j`` may have a smaller value than ``i``, even though
        ``j`` is ahead of ``i``.

    .. todo:: May be replaced by a simple mod, as distance_index is used only
        once in the code at current.

    """
    if j > i:
        return j - i
    else:
        return length + j - i


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

        :param FilePreviewType val:
        :rtype: EventType
        """
    return cls('file_preview', val)


@classmethod
def _guess_mimetype(cls, filename):
    """Guesses the MIME type from the filename.

        :return: the MIME type
        :rtype: str
        """
    import mimetypes
    mimetype, _ = mimetypes.guess_type(filename, strict=False)
    return mimetype


@classmethod
def __width(cls, header):
    """ provides width of tine property

        :param header: tine frameHeader
        :type header: :obj:`dict` <:obj:`str`, `any`>
        :returns: numpy dtype
        :rtype: :obj:`str`
        """
    width = 0
    if 'aoiWidth' in header and header['aoiWidth'] > 0:
        width = header['aoiWidth']
    elif 'sourceWidth' in header:
        width = header['sourceWidth']
    if not 0 < width <= 65535:
        raise ValueError('Invalid width: %s' % width)
    return width


def takeTime(elem):
    """
    function: 提取time字段
    :param elem:
    :return:
    """
    return elem['time']


def get_location(http_info):
    """Extract the redirect URL from a pysaml2 http_info object"""
    try:
        headers = dict(http_info['headers'])
        return headers['Location']
    except KeyError:
        return http_info['url']


def instance_signals_and_handlers(cls, instance):
    """Calculate per-instance signals and handlers."""
    isignals = cls._signals.copy()
    ihandlers = cls._build_instance_handler_mapping(instance, cls.
        _signal_handlers)
    return isignals, ihandlers


def extractResponse(cls, request, data):
    """Take a C{L{SRegRequest}} and a dictionary of simple
        registration values and create a C{L{SRegResponse}}
        object containing that data.

        @param request: The simple registration request object
        @type request: SRegRequest

        @param data: The simple registration data for this
            response, as a dictionary from unqualified simple
            registration field name to string (unicode) value. For
            instance, the nickname should be stored under the key
            'nickname'.
        @type data: {str:str}

        @returns: a simple registration response object
        @rtype: SRegResponse
        """
    self = cls()
    self.ns_uri = request.ns_uri
    for field in request.allRequestedFields():
        value = data.get(field)
        if value is not None:
            self.data[field] = value
    return self


def parse_slideshare(xmltree):
    """Convert blog parts of slideshare to hyperlink

    Argument:

        xmltree: XML tree object

    """
    uri = xmltree.find('strong').find('a').get('href')
    title = xmltree.find('strong').find('a').get('title')
    repl_slideshare = '\n`' + title + ' <' + uri + '>`_\n'
    return repl_slideshare


def _GetLeastIndex(face, points):
    """Return index of coordinate that is leftmost, lowest in face."""
    bestindex = 0
    bestpos = points.pos[face[0]]
    for i in range(1, len(face)):
        pos = points.pos[face[i]]
        if pos[0] < bestpos[0] or pos[0] == bestpos[0] and pos[1] < bestpos[1]:
            bestindex = i
            bestpos = pos
    return bestindex


@staticmethod
def _transaction_commit(transaction_id, **kwargs):
    """Commit a transaction.
        :param transaction_id: ID of transaction to be committed.
        :param **kwargs: Further parameters for the transport layer.
        """
    raise NotImplementedError('Transport interface not implemented')


@staticmethod
def compose_help_block_message():
    """Assemble a block of relevant help text to be returned with an invalid request."""
    message = 'You must supply a numeric transaction id '
    message += '(like "/transactioninfo/<transaction_id>")'
    return message


def delete_last_bracket(unreadable_json_str) ->str:
    """最後に余計な閉じかっこが存在する場合に削除する"""
    reversed_list = list(reversed(unreadable_json_str))
    for index, char in enumerate(reversed_list):
        if char == '}':
            del reversed_list[index]
            break
    valid_order_list = reversed(reversed_list)
    output = ''.join(valid_order_list)
    return output


def get_elb_listeners(listeners=None):
    """
    @type listeners: list
    """
    output = ''
    for listener in listeners:
        listener_config = listener.get('Listener')
        output += (
            'LB Port: {0} \nLB Protocol: {1} \nInstance Port: {2} \nInstance Protocol: {3}\n'
            .format(listener_config.get('LoadBalancerPort', '-'),
            listener_config.get('Protocol', '-'), listener_config.get(
            'InstancePort', '-'), listener_config.get('InstanceProtocol', '-'))
            )
    if output:
        return output.rstrip()


def p_varargslist_19(p):
    """varargslist : fpdef EQUAL test varargslist_star"""
    p[4].args.insert(0, p[1])
    p[4].defaults.insert(0, p[3])
    p[0] = p[4]


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

        :param SharedContentChangeMemberRoleDetails val:
        :rtype: EventDetails
        """
    return cls('shared_content_change_member_role_details', val)


def namedtuple_asdict(namedtuple):
    """
    The same as ``namedtuple._adict()``.

    Parameters
    ----------
    namedtuple : collections.namedtuple
    The named tuple to get the dict of
    """
    return namedtuple._asdict()


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

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

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


def parse_flag_str(flag_str):
    """ Parse a dq flag query string

    Parameters
    ----------
    flag_str: str
        String to be parsed

    Returns
    -------
    flags: list of strings
        List of reduced name strings which can be passed to lower level
        query commands
    signs: dict
        Dict of bools indicating if the flag should add positively to the
        segmentlist
    ifos: dict
        Ifo specified for the given flag
    bounds: dict
        The boundary of a given flag
    padding: dict
        Any padding that should be applied to the segments for a given flag
    """
    flags = flag_str.replace(' ', '').strip().split(',')
    signs = {}
    ifos = {}
    bounds = {}
    padding = {}
    bflags = []
    for flag in flags:
        if not (flag[0] == '+' or flag[0] == '-'):
            err_msg = "DQ flags must begin with a '+' or a '-' character. "
            err_msg += 'You provided {}.'.format(flag)
            err_msg += (
                'See http://pycbc.org/pycbc/latest/html/workflow/segments.html'
                )
            err_msg += ' for more information.'
            raise ValueError(err_msg)
        sign = flag[0] == '+'
        flag = flag[1:]
        ifo = pad = bound = None
        if len(flag.split(':')[0]) == 2:
            ifo = flag.split(':')[0]
            flag = flag[3:]
        if '<' in flag:
            popt = flag.split('<')[1].split('>')[0]
            spad, epad = popt.split(':')
            pad = float(spad), float(epad)
            flag = flag.replace(popt, '').replace('<>', '')
        if '[' in flag:
            bopt = flag.split('[')[1].split(']')[0]
            start, end = bopt.split(':')
            bound = int(start), int(end)
            flag = flag.replace(bopt, '').replace('[]', '')
        if ifo:
            ifos[flag] = ifo
        if pad:
            padding[flag] = pad
        if bound:
            bounds[flag] = bound
        bflags.append(flag)
        signs[flag] = sign
    return bflags, signs, ifos, bounds, padding


@classmethod
def delete_subscript(class_, script, subscript):
    """
        Returns a script with the given subscript removed. The subscript
        must appear in the main script aligned to opcode boundaries for it
        to be removed.
        """
    new_script = bytearray()
    pc = 0
    for opcode, data, pc, new_pc in class_.ScriptTools.get_opcodes(script):
        section = script[pc:new_pc]
        if section != subscript:
            new_script.extend(section)
    return bytes(new_script)


def delete_tags(DryRun=None, Resources=None, Tags=None):
    """
    Deletes the specified set of tags from the specified set of resources. This call is designed to follow a DescribeTags request.
    For more information about tags, see Tagging Your Resources in the Amazon Elastic Compute Cloud User Guide .
    See also: AWS API Documentation

    Examples
    This example deletes the tag Stack=test from the specified image.
    Expected Output:

    :example: response = client.delete_tags(
        DryRun=True|False,
        Resources=[
            'string',
        ],
        Tags=[
            {
                'Key': 'string',
                'Value': 'string'
            },
        ]
    )

    :type DryRun: boolean
    :param DryRun: Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation .

    :type Resources: list
    :param Resources: [REQUIRED]
            The ID of the resource. For example, ami-1a2b3c4d. You can specify more than one resource ID.
            (string) --

    :type Tags: list
    :param Tags: One or more tags to delete. If you omit the value parameter, we delete the tag regardless of its value. If you specify this parameter with an empty string as the value, we delete the key only if its value is an empty string.
            (dict) --Describes a tag.
            Key (string) --The key of the tag.
            Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws:
            Value (string) --The value of the tag.
            Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters.

    :return: response = client.delete_tags(
        Resources=[
            'ami-78a54011',
        ],
        Tags=[
            {
                'Key': 'Stack',
                'Value': 'test',
            },
        ],
    )

    print(response)

    """
    pass


def B23p_T(T):
    """function B23p_T = B23p_T(T)

    Section 4.1 Boundary between region 2 and 3.

    Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam 1997 Section 4 Auxiliary Equation for the Boundary between Regions 2 and 3

    Eq 5, Page 5
    """
    return 348.05185628969 - 1.1671859879975 * T + 0.0010192970039326 * T ** 2


def __call__(field, value):
    """validates field and value.

        raises zope.schema.ValidationError
        returns None
        """


def check_mouse_press_for_buttons(x, y, button_list):
    """ Given an x, y, see if we need to register any button clicks. """
    for button in button_list:
        if x > button.center_x + button.width / 2:
            continue
        if x < button.center_x - button.width / 2:
            continue
        if y > button.center_y + button.height / 2:
            continue
        if y < button.center_y - button.height / 2:
            continue
        button.on_press()


def create_project(project_name='DataProject', config={}):
    """
    Creates the project and creates a skelton directory
    structure

    Params:
      project_name: A string that represents the name of the project

      config: A dictionary that represents configuration options.  The structure
      is {"option": value}
        current options:
          git: A boolean that represents if you want a git repo to be init'd

          full_structure: A boolean that represents if you'd like the full
          folder structure or a barebones structure

          libraries: An array of strings that represents the libraries you'd
          like loaded on `load_project`
    """
    from os import mkdir, chdir, system
    from json import dump
    mkdir(project_name)
    chdir(project_name)
    if config == {}:
        config = {'git': False, 'full_structure': False, 'packages': [],
            'logging': False}
    if config['full_structure']:
        folders = ['data', 'diagnostics', 'doc', 'graphs', 'lib', 'reports',
            'profiling', 'tests', 'munge']
    else:
        folders = ['data', 'lib', 'munge']
    map(mkdir, folders)
    system('touch README.txt')
    if config['git']:
        system('git init')
    with open('.config.json', mode='w') as f:
        dump(config, f)


def put_gps_long(row):
    """
    Format longitude as a float.

    :param row: a data frame row
    :type row: pandas.Series
    :returns: processed value.

    """
    if row['lat'] == 0 and row['long'] == 0:
        row['long'] = 0
    else:
        row['long'] = row['long'] / 100000.0
    return row['long']


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


@classmethod
def get_language_filename(cls, mask, code):
    """Return full filename of a language file.

        Calculated forfor given path, filemask and language code.
        """
    return mask.replace('*', cls.get_language_code(code))


def callback(future):
    """Callback function to ensure the future has completed."""
    message_id = future.result()
    print('message_id: {} received.'.format(message_id))
    return 'OK, 200'


def psi_Na_HCO3_OH_HMW84(T, P):
    """c-a-a': sodium bicarbonate hydroxide [HMW84]."""
    psi = 0.0
    valid = T == 298.15
    return psi, valid


def p_schema(p):
    """schema : IDENTIFIER"""
    p[0] = p[1]


@classmethod
def solve(cls, *base_args, **base_kwargs):
    """Solve a linear system of equations using the Kaczmarz algorithm.

        Note
        ----
        This method takes the same parameters as :class:`kaczmarz.Base`
        or the subclass from which it is called.
        For example, :meth:`kaczmarz.Cyclic.solve`
        takes the same arguments as :class:`kaczmarz.Cyclic`.

        Parameters
        ----------
        base_args : tuple
            Positional arguments for :class:`kaczmarz.Base` constructor
            or the subclass in use.
        base_kwargs : dict
            Keyword arguments for :class:`kaczmarz.Base` constructor
            or the subclass in use.

        Returns
        -------
        x : (n,) or (n, 1) array
            The solution to the system ``A @ x = b``.
            The shape will match that of ``x0`` if provided,
            or ``b`` otherwise.
        """
    iterates = cls.iterates(*base_args, **base_kwargs)
    for x in iterates:
        pass
    return x


def allowed_file(filename):
    """Returns `True` if file extension is `.tar`"""
    return '.' in filename and filename.rsplit('.', 1)[1] in ['tar']


@classmethod
def extract_api_viewset(mcs, attrs):
    """
        Extracts APIFiltering specification from the attributes.

        :param attrs: Model class attributes
        :return: APIFiltering class.
        """
    spec = attrs.pop('APIViewset')
    for attr, default in mcs.API_VIEWSET_ATTRS:
        if not hasattr(spec, attr):
            setattr(spec, attr, default())
    return spec


def sort(obj, *args, **kwargs):
    """ a sort that actually returns the object being sorted """
    obj.sort(*args, **kwargs)
    return obj


def _gpibServers(cxn):
    """Get a list of available GPIB servers."""
    gpibs = []
    for name in cxn.servers:
        srv = cxn.servers[name]
        if 'gpib_bus' in name and 'list_devices' in srv.settings:
            gpibs.append(srv)
    return gpibs


def __delitem__(username):
    """Delete an inbox."""


def p_character_letter(p):
    """character : K_LETTER
                 | K_LETTER K_FROM CHARACTER K_TO CHARACTER
    """
    p[0] = []
    if len(p) == 6:
        char_from = p[3]
        char_to = p[5]
    else:
        char_from = 'a'
        char_to = 'z'
    p[0].append(('letter', (char_from, char_to)))


@classmethod
def current(cls):
    """Get the current AppConfig"""
    assert getattr(cls, '_current', None), 'no current AppConfig'
    return cls._current


def decode_input(input_proto):
    """Obtain an instance of Input from a protobuf.

    Args:
        input_proto: The protobuf instance representing the input

    Returns:
        The input decoded from the protobuf
    """
    for inp in input_proto:
        yield getattr(inp, inp.WhichOneof('value'))


def set_watched(db, aid, ep_type, number):
    """Set episode as watched."""
    db.cursor().execute(
        """UPDATE episode SET user_watched=:watched
        WHERE aid=:aid AND type=:type AND number=:number"""
        , {'aid': aid, 'type': ep_type, 'number': number, 'watched': 1})


@classmethod
def find_by_or_fail(cls, name, value, columns=None):
    """
        Find a model by specificd column or raise exception

        :param id: column name
        :type id: str

        :param columns: The columns to retrieve
        :type columns: list

        :return: Either a Model instance or a Collection
        :rtype: Model
        """
    instance = cls()
    return instance.new_query().find_by_or_fail(name, value, columns)


def _process_mbar_lambdas(secp):
    """
    Extract the lambda points used to compute MBAR energies from an AMBER MDOUT file.
    Parameters
    ----------
    secp: .out file from amber simulation.

    Returns
    -------
    mbar_lambdas: lambda values used for MBAR energy collection in simulation.

    """
    in_mbar = False
    mbar_lambdas = []
    for line in secp:
        if line.startswith('    MBAR - lambda values considered:'):
            in_mbar = True
            continue
        if in_mbar:
            if line.startswith('    Extra'):
                break
            if 'total' in line:
                data = line.split()
                mbar_lambdas.extend(data[2:])
            else:
                mbar_lambdas.extend(line.split())
    return mbar_lambdas


def inReplyTo(REQUEST=None):
    """ Return the IDiscussable object to which this item is a reply.

        o Permission: None assigned
        """


def cut_suffix(value, suffix):
    """Removes the tailing `suffix` if exists, else return `value`
    unchanged.

    """
    from xotl.tools.future.codecs import safe_decode, safe_encode
    if isinstance(value, str) and isinstance(suffix, bytes):
        suffix = safe_decode(suffix)
    elif isinstance(value, bytes) and isinstance(suffix, str):
        suffix = safe_encode(suffix)
    if len(suffix) > 0 and value.endswith(suffix):
        return value[:-len(suffix)]
    else:
        return value


@classmethod
def by_id(cls, node=None, id=None):
    """Retrieve a subnets record by id and create a Subnet instance from it.

        Args:
            node (BaseNode): the node from which the subnet belongs
            id (str): id of the subnet to retrieve

        Returns:
            Subnet: a Subnet instance corresponding to the record
        """
    response = node.user.client.subnets.get(node.user.id, node.id, id)
    return cls.from_response(node, response)


def get_utterances_view(botName=None, botVersions=None, statusType=None):
    """
    Use the GetUtterancesView operation to get information about the utterances that your users have made to your bot. You can use this list to tune the utterances that your bot responds to.
    For example, say that you have created a bot to order flowers. After your users have used your bot for a while, use the GetUtterancesView operation to see the requests that they have made and whether they have been successful. You might find that the utterance "I want flowers" is not being recognized. You could add this utterance to the OrderFlowers intent so that your bot recognizes that utterance.
    After you publish a new version of a bot, you can get information about the old version and the new so that you can compare the performance across the two versions.
    Data is available for the last 15 days. You can request information for up to 5 versions in each request. The response contains information about a maximum of 100 utterances for each version.
    If the bot's childDirected field is set to true , utterances for the bot are not stored and cannot be retrieved with the GetUtterancesView operation. For more information, see .
    This operation requires permissions for the lex:GetUtterancesView action.
    See also: AWS API Documentation

    :example: response = client.get_utterances_view(
        botName='string',
        botVersions=[
            'string',
        ],
        statusType='Detected'|'Missed'
    )

    :type botName: string
    :param botName: [REQUIRED]
            The name of the bot for which utterance information should be returned.

    :type botVersions: list
    :param botVersions: [REQUIRED]
            An array of bot versions for which utterance information should be returned. The limit is 5 versions per request.
            (string) --

    :type statusType: string
    :param statusType: [REQUIRED]
            To return utterances that were recognized and handled, use``Detected`` . To return utterances that were not recognized, use Missed .

    :rtype: dict
    :return: {
        'botName': 'string',
        'utterances': [
            {
                'botVersion': 'string',
                'utterances': [
                    {
                        'utteranceString': 'string',
                        'count': 123,
                        'distinctUsers': 123,
                        'firstUtteredDate': datetime(2015, 1, 1),
                        'lastUtteredDate': datetime(2015, 1, 1)
                    },
                ]
            },
        ]
    }

    """
    pass


def version_minor():
    """
    Returns the package minor version
    as defined in configure.ac
    as integer
    """
    return 6


@classmethod
def parse(cls, name, data_size, reader, parsers):
    """given a 4 byte name, data_size int, BitstreamReader
        and dict of {"atom":handler} sub-parsers,
        returns an atom of this class"""
    (version, track_in_poster, track_in_preview, track_in_movie, track_enabled
        ) = reader.parse('8u 20p 1u 1u 1u 1u')
    if version == 0:
        atom_format = '32u 32u 32u 4P 32u 8P 16u 16u 16u 2P'
    else:
        atom_format = '64U 64U 32u 4P 64U 8P 16u 16u 16u 2P'
    (created_utc_date, modified_utc_date, track_id, duration, video_layer,
        qt_alternate, volume) = reader.parse(atom_format)
    geometry_matrices = reader.parse('9* 32u')
    video_width, video_height = reader.parse('32u 32u')
    return cls(version=version, track_in_poster=track_in_poster,
        track_in_preview=track_in_preview, track_in_movie=track_in_movie,
        track_enabled=track_enabled, created_utc_date=created_utc_date,
        modified_utc_date=modified_utc_date, track_id=track_id, duration=
        duration, video_layer=video_layer, qt_alternate=qt_alternate,
        volume=volume, geometry_matrices=geometry_matrices, video_width=
        video_width, video_height=video_height)


def doWrite():
    """
        Some data can be written to your descriptor.

        @return: If an error is encountered which causes the descriptor to
            no longer be valid, a L{Failure} should be returned.  Otherwise,
            C{None}.
        """


@staticmethod
def access_sort(key):
    """
        Sorts (prefixmode, UID) keys based on the prefix modes given.
        """
    prefixes, user = key
    accesses = {'o': 100, 'h': 10, 'v': 1}
    num = 0
    for prefix in prefixes:
        num += accesses.get(prefix, 0)
    return num


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 __get__(form, form_class=None):
    """Bind an action to a form

        Note that the other methods defined in this interface are
        valid only after the action has been bound to a form.
        """


def julian_day(year, month=1, day=1):
    """Given a proleptic Gregorian calendar date, return a Julian day int."""
    janfeb = month < 3
    return day + 1461 * (year + 4800 - janfeb) // 4 + 367 * (month - 2 +
        janfeb * 12) // 12 - 3 * ((year + 4900 - janfeb) // 100) // 4 - 32075


@classmethod
def has_parameter(cls, name):
    """ Determine if the model has a parameter with the given name

        :param name: The name of the parameter to check for
        :type name: str
        :rtype: bool
        """
    return name in cls.default_parameters


@classmethod
def initialize(cls, **kwargs):
    """Initialize class attributes

        Since drivers may need to cache thing short-term. The emulator
        instantiates the driver every time it serves a client query.

        Driver objects can cache whenever it makes sense for the duration
        of a single session. It is guaranteed that the driver object will
        never be reused for any other session.

        The `initialize` method is provided to set up the driver in a way
        that would affect all the subsequent sessions.

        :params **kwargs: driver-specific parameters
        :returns: initialized driver class
        """
    return cls


def rendaku_merge_pairs(lpair, rpair):
    """Merge lpair < rpair while applying semi-irregular rendaku rules"""
    ltext, lnum = lpair
    rtext, rnum = rpair
    if lnum > rnum:
        raise ValueError
    if rpair == ('ひゃく', 100):
        if lpair == ('さん', 3):
            rtext = 'びゃく'
        elif lpair == ('ろく', 6):
            ltext = 'ろっ'
            rtext = 'ぴゃく'
        elif lpair == ('はち', 8):
            ltext = 'はっ'
            rtext = 'ぴゃく'
    elif rpair == ('せん', 1000):
        if lpair == ('さん', 3):
            rtext = 'ぜん'
        elif lpair == ('はち', 8):
            ltext = 'はっ'
    elif rpair == ('ちょう', 10 ** 12):
        if lpair == ('いち', 1):
            ltext = 'いっ'
        elif lpair == ('はち', 8):
            ltext = 'はっ'
        elif lpair == ('じゅう', 10):
            ltext = 'じゅっ'
    elif rpair == ('けい', 10 ** 16):
        if lpair == ('いち', 1):
            ltext = 'いっ'
        elif lpair == ('ろく', 6):
            ltext = 'ろっ'
        elif lpair == ('はち', 8):
            ltext = 'はっ'
        elif lpair == ('じゅう', 10):
            ltext = 'じゅっ'
        elif lpair == ('ひゃく', 100):
            ltext = 'ひゃっ'
    return '%s%s' % (ltext, rtext), lnum * rnum


@classmethod
def get_mains_powered_outlets(cls, session):
    """Wall-powered outlets

        Args:
            session: database session
        Returns:
            list: of outlet keys powered by the mains
        """
    results = session.run(
        """
            MATCH (outlet:Outlet) WHERE NOT (outlet)-[:POWERED_BY]->(:Asset) RETURN outlet.key as key
            """
        )
    return list(map(lambda x: x.get('key'), results))


def lxml_installed():
    """
    checks if lxml is installed
    used for fallbacks to other builtin modules
    """
    import imp
    try:
        imp.find_module('lxml')
        return True
    except ImportError:
        return False


def _toggle(mapping, key, value):
    """If *key* is set in *mapping*, delete its value.  Otherwise, set
    *key* to *value*."""
    if key in mapping:
        del mapping[key]
    else:
        mapping[key] = value


def SetPacketReportCallbackFunc(func):
    """
    You can pass a callback to catch a moment when some packet is
    added/removed.
    """
    global _PacketReportCallbackFunc
    _PacketReportCallbackFunc = func


def replace(input_string: str, old: str, new: str, count: int=None) ->str:
    """
    Replace elements in the input string.

        :param input_string: The input string in which the text is to be replaced.
        :param old: The old string element.
        :param new: The replacement text.
        :param count: How many times the text should be replaced. If None all occurrences will be replaced.
    """
    if count is None:
        return input_string.replace(old, new)
    else:
        return input_string.replace(old, new, count)


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

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

    """
    pass


def volume_tetrahedron(v1: 'mathutils.Vector', v2: 'mathutils.Vector', v3:
    'mathutils.Vector', v4: 'mathutils.Vector') ->float:
    """Return the volume formed by a tetrahedron (points can be in any order).

    :param v1: Point1
    :type v1: 'mathutils.Vector'
    :param v2: Point2
    :type v2: 'mathutils.Vector'
    :param v3: Point3
    :type v3: 'mathutils.Vector'
    :param v4: Point4
    :type v4: 'mathutils.Vector'
    """
    pass


def connected_components(edges):
    """
    Computes the connected components.

    @param      edges       edges
    @return                 dictionary { vertex : id of connected components }
    """
    res = {}
    for k in edges:
        for _ in k[:2]:
            if _ not in res:
                res[_] = _
    modif = 1
    while modif > 0:
        modif = 0
        for k in edges:
            a, b = k[:2]
            r, s = res[a], res[b]
            if r != s:
                m = min(res[a], res[b])
                res[a] = res[b] = m
                modif += 1
    return res


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


def frange(start, stop, step):
    """Generator that creates an arbitrary-stepsize range."""
    r = start
    while r < stop:
        yield r
        r += step


def cc_flags():
    """Get the compiler flags necessary for including the interface
    library in a C or C++ program.

    Returns:
        list: The necessary compiler flags and preprocessor definitions.

    """
    from yggdrasil.drivers import CModelDriver
    print(' '.join(CModelDriver.CModelDriver.get_compiler_flags(for_model=
        True)))


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

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

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


def named(values, names):
    """Creates a dict with `names` as fields, and `values` as values."""
    return dict(zip(names.split(), values))


def _prepare_versions(listen_versions, supported_versions):
    """Return listen versions."""
    assert supported_versions
    if not listen_versions:
        return supported_versions
    unsupported = set(listen_versions) - set(supported_versions)
    if unsupported:
        raise ValueError('Unsupported OpenFlow versions: %r' % unsupported)
    return listen_versions


def bit_reverse_byte(byte):
    """Bit-bashing reversal of a byte"""
    result = 0
    for i in range(8):
        if byte & 1 << i:
            result |= 1 << 7 - i
    return result & 255


@staticmethod
def interfaces_roles_dont_change_and_best_upstream_neighbor_reelected(interface
    : 'TreeInterfaceUpstream') ->None:
    """
        Interfaces roles dont change (this interface remains Root) AND
        BestUpstreamNeighbor changes AND
        BestUpstreamNeighbor is not null
        (other router was elected as the responsible for forwarding multicast data packets)

        OR

        Interfaces roles dont change (this interface remains Root) AND
        BestUpstreamNeighbor transmitted a new IamUpstream message AND
        that neighbor is still responsible for forwarding multicast data packet
        (a new IamUpstream message was received from the BestUpstreamNeighbor but that router is still responsible for
        forwarding multicast data packets)
        """
    interface.logger.debug(
        'interfaces_roles_dont_change_and_best_upstream_neighbor_reelected')
    interface.send_my_interest()


@classmethod
def _check_special_char_position(cls, last_special: str, special: str) ->str:
    """
        Returns an action to execute if the character is well placed. It should
        only be applied over special characters.

        If it's not well placed, the character will be included in the text
        """
    if special == cls.open_flag_char:
        if last_special not in [cls.end_format_char, None]:
            return cls.ESCAPE_CHAR
        else:
            return cls.START_FLAGS
    elif special == cls.close_flag_char:
        if last_special != cls.open_flag_char:
            return cls.ESCAPE_CHAR
        else:
            return cls.START_FORMAT
    elif special == cls.end_format_char:
        if last_special in [cls.open_flag_char, cls.end_format_char, None]:
            return cls.ESCAPE_CHAR
        else:
            return cls.END_FORMAT


def _insert_eval(rule):
    """
   inserts eval(expr=RULE) for rules that are expresssions and not functions

   # todo: make both single and double quotation marks work (use single now?)
   Example:
       rb.add("df.groupby('pid')['gender'].nunique()<2")
   becomes
       rb.add("evaluate(expr="df.groupby('pid')['gender'].nunique()<2")")
   why?
       standardize all rules: always start with a function
       easier to code with it
   """
    if rule.startswith('df.'):
        rule = f'evaluate(expr="{rule}")'
    elif rule.split('(')[0] in globals():
        pass
    else:
        rule = f'evaluate(expr="{rule}")'
    return rule


def _fix_missing_period(line):
    """
    Adds a period to a line that is missing a period.
    """
    dm_single_close_quote = u'’'
    dm_double_close_quote = u'”'
    END_TOKENS = ['.', '!', '?', '...', "'", '`', '"',
        dm_single_close_quote, dm_double_close_quote, ')']
    if '@highlight' in line or line == '' or line[-1] in END_TOKENS:
        return line
    return line + '.'


@staticmethod
def max_val() ->float:
    """
        Get maximum value of metric. This used for correct histogram visualisation in some monitors

        :return: maximum value
        """
    return 1


@staticmethod
def stop(container, timeout=1):
    """
		Stops a container returned by `ContainerUtils.start_for_exec()`
		"""
    container.stop(timeout=timeout)


def incrgc():
    """ Perform an incremental garbage collection sweep.

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

        o Ghostify in LRU order.

        o Skip dirty or sticky objects.

        o Quit once we get down to 'cache_size'.
        """


def scatter_row_inplace(data, row_index, value):
    """Write the value into the data tensor using the row index inplace.

    This is an inplace write so it will break the autograd.

    Parameters
    ----------
    data : Tensor
        The data tensor to be updated.
    row_index : Tensor
        A 1-D integer tensor containing which rows to be updated.
    value : Tensor
        The new value.
    """
    pass


def createAndAdd(data):
    """Call create and add.

        This method can be used for keep all attributes internal during create
        and add calls. On sucess we return the new created and added object.
        If something fails, we return None. The default handleAdd method will
        only set the _finishedAdd marker on sucess.
        """


@staticmethod
def gray(text):
    """ turns text gray """
    return f'\x1b[90m{text}\x1b[0m'


def psi_H_K_SO4_HMW84(T, P):
    """c-c'-a: hydrogen potassium sulfate [HMW84]."""
    psi = 0.197
    valid = T == 298.15
    return psi, valid


def get_op_symbol(obj, fmt='%s', symbol_data=symbol_data, type=type):
    """Given an AST node object, returns a string containing the symbol.
    """
    return fmt % symbol_data[type(obj)]


def equal(attrs, inputs, proto_obj):
    """Logical Equal operator with broadcasting."""
    return 'broadcast_equal', attrs, inputs


@classmethod
def process(cls, request):
    """
        Добавляет в контекст элементы Рабочего Стола
        :param request: request
        :type request: Request
        """
    desktop = cls._get_desktop(request)
    return {'desktop': desktop}


def is_select(status):
    """Returns true if the first word in status is 'select'."""
    if not status:
        return False
    return status.split(None, 1)[0].lower() == 'select'


def str_without_suffix(data: str, suffix='/'):
    """Removes suffix (if present) from string.

    Args:
        data (str):
        suffix: suffix to be remove, defaults to '/'

    Returns:
        str: the string without the suffix if it was present
    """
    if data is None:
        return None
    return data if not data.endswith(suffix) else data[:-len(suffix)]


def is_private(node_name: str) ->bool:
    """Check if node is private to class definition."""
    return node_name.startswith('__') and not node_name.endswith('__')


def make_unique(dirs):
    """Take a sequence of hashable items and return a tuple including each
    only once.

    Preserves original ordering.

    """
    udirs = []
    found = set()
    for d in dirs:
        if d not in found:
            udirs.append(d)
            found.add(d)
    return tuple(udirs)


def check_palette(palette):
    """
    Check a palette argument (to the :class:`Writer` class) for validity.

    Returns the palette as a list if okay; raises an exception otherwise.
    """
    if palette is None:
        return None
    p = list(palette)
    if not 0 < len(p) <= 256:
        raise ValueError('a palette must have between 1 and 256 entries')
    seen_triple = False
    for i, t in enumerate(p):
        if len(t) not in (3, 4):
            raise ValueError(
                'palette entry %d: entries must be 3- or 4-tuples.' % i)
        if len(t) == 3:
            seen_triple = True
        if seen_triple and len(t) == 4:
            raise ValueError(
                'palette entry %d: all 4-tuples must precede all 3-tuples' % i)
        for x in t:
            if int(x) != x or not 0 <= x <= 255:
                raise ValueError(
                    'palette entry %d: values must be integer: 0 <= x <= 255' %
                    i)
    return p


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

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


def stop_gradient(data=None, name=None, attr=None, out=None, **kwargs):
    """Stops gradient computation.

    Stops the accumulated gradient of the inputs from flowing through this operator
    in the backward direction. In other words, this operator prevents the contribution
    of its inputs to be taken into account for computing gradients.

    Example::

      v1 = [1, 2]
      v2 = [0, 1]
      a = Variable('a')
      b = Variable('b')
      b_stop_grad = stop_gradient(3 * b)
      loss = MakeLoss(b_stop_grad + a)

      executor = loss.simple_bind(ctx=cpu(), a=(1,2), b=(1,2))
      executor.forward(is_train=True, a=v1, b=v2)
      executor.outputs
      [ 1.  5.]

      executor.backward()
      executor.grad_arrays
      [ 0.  0.]
      [ 1.  1.]

    Defined in src/operator/tensor/elemwise_unary_op_basic.cc:L327

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

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

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


def get_data(get_data_func, class_num, data_dir, save_dir, passbands,
    known_redshift=True, nprocesses=1, redo=False, calculate_t0=True):
    """
    Get data using some function.

    Parameters
    ----------
    get_data_func : func
        Function that returns light_curves and takes at least the arguments class_num, data_dir, save_dir, passbands.
        E.g. get_data_func = get_data_custom(class_num, data_dir, save_dir, passbands, known_redshift)
    class_num : int
        Class number. E.g. SNIa is 1. See helpers.py for lookup table.
        E.g. class_num = 1
    data_dir : str
        Directory where data is stored
        E.g. data_dir='data/ZTF_20190512/'
    save_dir : str
        Directory to save processed data
        E.g. save_dir='data/saved_light_curves/'
    passbands : tuple
        Passbands to use.
        E.g. passbands=('g', 'r')
    known_redshift : bool
        Whether to correct the light curves for cosmological time dilation or not.
    nprocesses : int or None
        Number of processes to use
    redo : bool
        Whether to redo reading the data and saving the processed data.
    calculate_t0 : bool
        Whether to calculate t0 during preprocessing.

    Returns
    -------
        light_curves : dict of astropy.table.Table objects
            e.g light_curves['objid1'] =
                passband   time       flux     fluxErr   photflag
                  str1   float32    float32    float32    int32
                -------- -------- ----------- ---------- --------
                       g -46.8942  -48.926975  42.277767        0
                       g -43.9352  -105.35379   72.97575        0
                       g -35.9161  -46.264206    99.9172        0
                       g -28.9377  -28.978344  42.417065        0
                       g -25.9787  109.886566   46.03949        0
                       g -15.0399    -80.2485   80.38155        0
                       g -12.0218    93.51743  113.21529        0
                       g  -6.9585   248.88364 108.606865        0
                       g  -4.0411   341.41498  47.765404        0
                       g      0.0    501.7441   45.37485     6144
                     ...      ...         ...        ...      ...
                       r  40.9147   194.32494  57.836903     4096
                       r  59.9162    67.59185   45.66463     4096
                       r  62.8976    80.85155  44.356197     4096
                       r  65.8974   28.174305   44.75049     4096
                       r  71.8966  -18.790287 108.049774     4096
                       r  74.9297  -3.1707647  125.15057     4096
                       r  77.9341 -11.0205965 125.784676     4096
                       r  80.8576   129.65466   69.99305     4096
                       r  88.8922  -14.259436  52.917866     4096
                       r 103.8734   27.178356 115.537704     4096
    """
    return get_data_func(class_num, data_dir, save_dir, passbands,
        known_redshift, nprocesses, redo, calculate_t0)


def clean_catalog(wfau_catalog, clean_band='K_1', badclass=-9999,
    maxerrbits=41, minerrbits=0, maxpperrbits=60):
    """
    Attempt to remove 'bad' entries in a catalog.

    Parameters
    ----------
    wfau_catalog : `~astropy.io.fits.BinTableHDU`
        A FITS binary table instance from the WFAU survey.
    clean_band : ``'K_1'``, ``'K_2'``, ``'J'``, ``'H'``
        The band to use for bad photometry flagging.
    badclass : int
        Class to exclude.
    minerrbits : int
    maxerrbits : int
        Inside this range is the accepted number of error bits.
    maxpperrbits : int
        Exclude this type of error bit.

    Examples
    --------
    """
    band = clean_band
    mask = (wfau_catalog[band + 'ERRBITS'] <= maxerrbits) * (wfau_catalog[
        band + 'ERRBITS'] >= minerrbits) * ((wfau_catalog['PRIORSEC'] ==
        wfau_catalog['FRAMESETID']) + (wfau_catalog['PRIORSEC'] == 0)) * (
        wfau_catalog[band + 'PPERRBITS'] < maxpperrbits)
    if band + 'CLASS' in wfau_catalog.colnames:
        mask *= wfau_catalog[band + 'CLASS'] != badclass
    elif 'mergedClass' in wfau_catalog.colnames:
        mask *= wfau_catalog['mergedClass'] != badclass
    return wfau_catalog.data[mask]


def start(st_reg_number):
    """Checks the number valiaty for the Santa Catarina state"""
    divisor = 11
    if len(st_reg_number) > 9:
        return False
    if len(st_reg_number) < 9:
        return False
    sum_total = 0
    peso = 9
    for i in range(len(st_reg_number) - 1):
        sum_total = sum_total + int(st_reg_number[i]) * peso
        peso = peso - 1
    rest_division = sum_total % divisor
    digit = divisor - rest_division
    if rest_division < 2:
        digit = 0
    return digit == int(st_reg_number[len(st_reg_number) - 1])


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

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

    """
    pass


def psi_Mg_Na_HSO4_HMW84(T, P):
    """c-c'-a: magnesium sodium bisulfate [HMW84]."""
    psi = 0.0
    valid = T == 298.15
    return psi, valid


def user_label(user):
    """Given a user ORM FAB object, returns a label"""
    if user:
        if user.first_name and user.last_name:
            return user.first_name + ' ' + user.last_name
        else:
            return user.username


def p_and_test_1(p):
    """and_test : not_test"""
    p[0] = p[1]


def write_contents(path, data):
    """
    Overwrite the contents of the file at `path` with the given data.
    If the file does not exist, it is created.

    Example::

      >>> import tempfile
      >>> (fd, tmpfile) = tempfile.mkstemp()
      >>> write_contents(tmpfile, 'big data here') and None # discard return value on Py3
      >>> read_contents(tmpfile)
      'big data here'

    (If you run this test, remember to clean up afterwards)
    ::

      >>> os.remove(tmpfile)

    """
    mode = 'wb' if isinstance(data, bytes) else 'w'
    with open(path, mode) as stream:
        return stream.write(data)


def write(cls, path: str, data, encode: bool=True, **kwargs):
    """
        Write the contents to a file's destination
        """
    raise NotImplementedError('override in subclass')


def __iter__():
    """Return iterable of active tokens managed by utility.
        """


def ptr_byref(args, offset=-1):
    """Return the pointer argument passed in by-reference."""
    return args[offset]._obj


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 get_keywords():
    """Get the keywords needed to look up the version information."""
    git_refnames = '$Format:%d$'
    git_full = '$Format:%H$'
    git_date = '$Format:%ci$'
    keywords = {'refnames': git_refnames, 'full': git_full, 'date': git_date}
    return keywords


def to_list(obj):
    """
    Transforms a non iterable object into a singleton list, or an iterable
    into a list.
    """
    if isinstance(obj, list) or isinstance(obj, tuple):
        return list(obj)
    return [obj]


def shape_key_mirror(use_topology: bool=False):
    """Mirror the current shape key along the local X axis

    :param use_topology: Topology Mirror, Use topology based mirroring (for when both sides of mesh have matching, unique topology)
    :type use_topology: bool
    """
    pass


def reloadtranslation():
    """Force a full reload of UI translation

    """
    pass


def build_place_string(filename, lineno, module):
    """Return place string for log event.

    Example::

        >>> build_place_string('/foo/bar.py', 71, 'foo_bar')
        'File "/foo/bar.py", line 71, in foo_bar'

    :param filename: name of the file
    :param lineno: line number
    :param module: name of module or function

    """
    place = 'File "%s", line %d, in %s' % (filename, lineno, module)
    return place


def filer_actions(context):
    """
    Track the number of times the action field has been rendered on the page,
    so we know which value to use.
    """
    context['action_index'] = context.get('action_index', -1) + 1
    return context


def format_deprecated_warn(msg, version, repl='', help=False):
    """
    Calling the method will return in a warning message about the node
    in question being scheduled for removal.

    If repl (replacement message) is provided that message be included.
    """
    help_msg = ''.join(['\nPlease use {} instead.'.format(repl) if repl else
        '',
        """

To disable deprecation warnings, uncheck:
Preferences -> Advanced -> Display warnings for deprecated nodes."""
         if help else ''])
    return '{} is deprecated and will be removed in version {}.{}'.format(msg,
        version, help_msg)


def paths_calculate(start_frame: int=1, end_frame: int=250):
    """Calculate motion paths for the selected objects

    :param start_frame: Start, First frame to calculate object paths on
    :type start_frame: int
    :param end_frame: End, Last frame to calculate object paths on
    :type end_frame: int
    """
    pass


def lambdasVisuShrink(wavCoeff):
    """
    Computes the threshold value (lambda) by VisuShrink [1] method.

    Parameters
    ---------
    wavCoeff: list of lists or array-like
        Wavelet coefficients

    Returns
    -------
    list of float:
        The threshold values for each wavelet coefficients
        vector.

    See also
    --------
    filtration: Function that use this function for filter via wavelet
        coefficients
    pywt.wavedec: Function that decomposes the signal in wavelet and
        scale coefficients
    pywt.waverec: Function that recomposes the signal from wavelet and
        scale coefficients

    References
    ----------
    .. [1] DONOHO, D. L.; JOHNSTONE, I. M. Ideal spatial adaptation via
           wavelet shrinkage. Biometrika, v. 81, p. 425–455, 1994.
    """
    import numpy as np
    d_m1 = list(wavCoeff[-1])
    d_m1 = np.array(d_m1)
    estDeviation = np.median(np.abs(d_m1)) / 0.6745
    lambdaValues = [estDeviation * np.sqrt(2 * np.log10(d_m1.size))] * len(
        wavCoeff)
    return lambdaValues


@classmethod
def from_item(cls, item):
    """
        Constructs Google Document from the item, in which Google describe it
        """
    return cls(id=item['id'], name=item.get('name'), mime_type=item.get(
        'mimeType'))


def duplicates_removed(it, already_seen=()):
    """
    Returns a list with duplicates removed from the iterable `it`.

    Order is preserved.
    """
    lst = []
    seen = set()
    for i in it:
        if i in seen or i in already_seen:
            continue
        lst.append(i)
        seen.add(i)
    return lst


@classmethod
def supported(cls, _conn):
    """Return that null authentication is never a supported auth mode"""
    return False


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


def int_to_8byte(i):
    """Given an integer, return a bytearray of its unsigned integer
    representation, big-endian.
    """
    return bytearray([i >> 56 & 255, i >> 48 & 255, i >> 40 & 255, i >> 32 &
        255, i >> 24 & 255, i >> 16 & 255, i >> 8 & 255, i & 255])


def getColumnNamesNum(infile):
    """
    input infile, get a dict (key is cloumnName , value is the cloumn number )
    """
    linelist = []
    dict1 = {}
    with open(infile) as ff:
        for line in ff:
            line = line.rstrip()
            linelist = line.split('\t')
            break
    for x, columnName in enumerate(linelist):
        dict1[columnName] = x
    return dict1


def generate_user_input_table(ui):
    """Generate user input table in a format that allows for copy-paste from
    LaTeX pdf to python editor"""
    calculation_input = []
    for key, value in ui.items():
        if key != 'parameter_id':
            calculation_input.append(key)
    calculation_input = sorted(calculation_input)
    table_user_input = []
    for i in calculation_input:
        if isinstance(ui[i], str):
            table_user_input.append((i, "'" + str(ui[i]) + "'"))
        else:
            table_user_input.append((i, str(ui[i])))
    return table_user_input


def grant_permission(username, action):
    """Grant a user permission to perform an action."""


def get_data_address(x):
    """Returns memory address where a numpy or cupy array's data is stored."""
    if hasattr(x, '__array_interface__'):
        ptr_x = x.__array_interface__['data'][0]
    elif hasattr(x, '__cuda_array_interface__'):
        ptr_x = x.__cuda_array_interface__['data'][0]
    else:
        raise ValueError(
            'Input must have an __array_interface__ or __cuda_array_interface__ attribute.'
            )
    return ptr_x


def view_zoom_in(location: float=(0.0, 0.0)):
    """Zoom in the image (centered around 2D cursor)

    :param location: Location, Cursor location in screen coordinates
    :type location: float
    """
    pass


def vertex_warp(warp_angle: float=6.28319, offset_angle: float=0.0, min:
    float=-1, max: float=1.0, viewmat: float=(0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
    0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), center: float=(0.0,
    0.0, 0.0)):
    """Warp vertices around the cursor

    :param warp_angle: Warp Angle, Amount to warp about the cursor
    :type warp_angle: float
    :param offset_angle: Offset Angle, Angle to use as the basis for warping
    :type offset_angle: float
    :param min: Min
    :type min: float
    :param max: Max
    :type max: float
    :param viewmat: Matrix
    :type viewmat: float
    :param center: Center
    :type center: float
    """
    pass


@classmethod
def cascade(cls, id, parent_id=None):
    """Delete the current object and the relative define in cascade.

    id: int
    parent_id: int for parent child relations

    """
    if cls.relations:
        for relation in cls.relations:
            if relation.get('model') and relation.get('relation_key'):
                model_elastic = relation.get('model')
                mod_elastic = __import__('model', fromlist=model_elastic)
                type_es = getattr(mod_elastic, model_elastic)
                type_es.delete({'query': {'term': {relation.get(
                    'relation_key'): id}}})
    if parent_id:
        cls.delete(id, parent_id)
    else:
        cls.delete(id)


def filename(hierarchy, organism):
    """ Obtain a filename for given hierarchy and organism.

    :param hierarchy: GeneSet hierarchy, example: ('GO', 'biological_process')
    :param organism: Taxonomy ID

    :return: Filename for given hierarchy and organism

    Example
    --------
        >>> filename(('CustomSet', 'subsets'), '6500')
        'CustomSet-subsets-6500.gmt'
    """
    return '-'.join(hierarchy + (organism if organism is not None else '',)
        ) + '.gmt'


def get_application_settings(ApplicationId=None):
    """
    Used to request the settings for an app.

    :example: response = client.get_application_settings(
        ApplicationId='string'
    )

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

    :rtype: dict
    :return: {
        'ApplicationSettingsResource': {
            'ApplicationId': 'string',
            'LastModifiedDate': 'string',
            'Limits': {
                'Daily': 123,
                'Total': 123
            },
            'QuietTime': {
                'End': 'string',
                'Start': 'string'
            }
        }
    }

    """
    pass


def check_migration_rate(parser, rate):
    """
    Checks that the specified migration rate makes sense.
    """
    if rate < 0:
        parser.error('Migration rates must be non-negative.')


def ordered_node_greedy_best_first(node, h, node_tiebreaker):
    """
    Creates an ordered search node (basically, a tuple containing the node
    itself and an ordering) for greedy best first search (the value with lowest
    heuristic value is used).

    @param node The node itself.
    @param h The heuristic value.
    @param node_tiebreaker An increasing value to prefer the value first
                           inserted if the ordering is the same.
    @returns A tuple to be inserted into priority queues.
    """
    f = h
    return f, h, node_tiebreaker, node


def PlanetStatistics(*args, **kwargs):
    """
  Computes and plots the CDPP statistics comparison between `model` and
  `compare_to` for all known planets.

  """
    raise NotImplementedError('This mission is not yet supported.')


def is_response_to_head(response):
    """
    Checks whether the request of a response has been a HEAD-request.
    Handles the quirks of AppEngine.

    :param conn:
    :type conn: :class:`httplib.HTTPResponse`
    """
    method = response._method
    if isinstance(method, int):
        return method == 3
    return method.upper() == 'HEAD'


@classmethod
def store(cls, server_url, association):
    """Create an Association instance"""
    raise NotImplementedError('Implement in subclass')


def get_run_url(run):
    """Returns the FTP URL for a given SRA run accession ID."""
    return (
        'ftp://ftp-trace.ncbi.nlm.nih.gov/sra/sra-instant/reads/ByRun/sra/SRR/%s/%s/%s.sra'
         % (run[:6], run, run))


@staticmethod
def log_response(response):
    """
        renders response as json or as a string
        """
    try:
        log_body = response.json()
    except ValueError:
        log_body = response.content[:30]
    return log_body


@staticmethod
def linear_model(x, y):
    """
        Returns a linear model transformation function fitted on the two supplied points.
        y = m*x + b
        Note: Assumes that slope > 0, otherwise division through zero might occur.
        """
    x1, x2 = x
    y1, y2 = y
    m = (y2 - y1) / (x2 - x1)
    b = y1 - m * x1
    return lambda x: m * x + b


def _Native(*data, **kwargs):
    """Stub for implementing an operator implemented in native frontend language.

    Parameters
    ----------
    data : Symbol[]
        Input data for the custom operator.
    info : ptr, required
    need_top_grad : boolean, optional, default=1
        Whether this layer needs out grad for backward. Should be false for loss layers.

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

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


def _winsorize(col, top_pct, bot_pct, top=True, bot=True):
    """
    Winsorizes a pandas Series
    """
    if top:
        top_val = col.quantile(top_pct)
        col.loc[col > top_val] = top_val
    if bot:
        bot_val = col.quantile(bot_pct)
        col.loc[col < bot_val] = bot_val
    return col


def extrude_edges_indiv(use_normal_flip: bool=False, mirror: bool=False):
    """Extrude individual edges only

    :param use_normal_flip: Flip Normals
    :type use_normal_flip: bool
    :param mirror: Mirror Editing
    :type mirror: bool
    """
    pass


@classmethod
def abulk(cls, x):
    """
        calculate the bulk (relaxed) lattice parameter of the alloy
        """
    return cls.aSi + (0.2 * x + 0.027 * x ** 2)


def exit():
    """Dummy implementation of _thread.exit()."""
    raise SystemExit