def Func(arg_0=None, arg_1=22050, arg_2=None, arg_3=512,
               arg_4=120.0, arg_5=100, arg_6=True, arg_7=None,
               arg_8='frames'):
    r'''Dynamic programming beat tracker.

    Beats are detected in three stages, following the method of [1]_:
      1. Measure onset strength
      2. Estimate tempo from onset correlation
      3. Pick peaks in onset strength approximately consistent with estimated
         tempo

    .. [1] Ellis, Daniel PW. "Beat tracking by dynamic programming."
           Journal of New Music Research 36.1 (2007): 51-60.
           http://labrosa.ee.columbia.edu/projects/beattrack/

    Parameters
    ----------

    y : np.ndarray [shape=(n,)] or None
        audio time series

    sr : number > 0 [scalar]
        sampling rate of `y`

    onset_envelope : np.ndarray [shape=(n,)] or None
        (optional) pre-computed onset strength envelope.

    hop_length : int > 0 [scalar]
        number of audio samples between successive `onset_envelope` values

    start_bpm  : float > 0 [scalar]
        initial guess for the tempo estimator (in beats per minute)

    tightness  : float [scalar]
        tightness of beat distribution around tempo

    trim       : bool [scalar]
        trim leading/trailing beats with weak onsets

    bpm        : float [scalar]
        (optional) If provided, use `bpm` as the tempo instead of
        estimating it from `onsets`.

    units : {'frames', 'samples', 'time'}
        The units to encode detected beat events in.
        By default, 'frames' are used.

    Returns
    -------

    tempo : float [scalar, non-negative]
        estimated global tempo (in beats per minute)

    beats : np.ndarray [shape=(m,)]
        estimated beat event locations in the specified units
        (default is frame indices)

    .. note::
        If no onset strength could be detected, Funcer estimates 0 BPM
        and returns an empty list.

    Raises
    ------
    ParameterError
        if neither `y` nor `onset_envelope` are provided

        or if `units` is not one of 'frames', 'samples', or 'time'

    See Also
    --------
    librosa.onset.onset_strength

    Examples
    --------
    Track beats using time series input

    >>> y, sr = librosa.load(librosa.util.example_audio_file())

    >>> tempo, beats = librosa.beat.Func(y=y, sr=sr)
    >>> tempo
    64.599609375

    Print the first 20 beat frames

    >>> beats[:20]
    array([ 320,  357,  397,  436,  480,  525,  569,  609,  658,
            698,  737,  777,  817,  857,  896,  936,  976, 1016,
           1055, 1095])

    Or print them as timestamps

    >>> librosa.frames_to_time(beats[:20], sr=sr)
    array([  7.43 ,   8.29 ,   9.218,  10.124,  11.146,  12.19 ,
            13.212,  14.141,  15.279,  16.208,  17.113,  18.042,
            18.971,  19.9  ,  20.805,  21.734,  22.663,  23.591,
            24.497,  25.426])

    Track beats using a pre-computed onset envelope

    >>> onset_env = librosa.onset.onset_strength(y, sr=sr,
    ...                                          aggregate=np.median)
    >>> tempo, beats = librosa.beat.Func(onset_envelope=onset_env,
    ...                                        sr=sr)
    >>> tempo
    64.599609375
    >>> beats[:20]
    array([ 320,  357,  397,  436,  480,  525,  569,  609,  658,
            698,  737,  777,  817,  857,  896,  936,  976, 1016,
           1055, 1095])

    Plot the beat events against the onset strength envelope

    >>> import matplotlib.pyplot as plt
    >>> hop_length = 512
    >>> plt.figure(figsize=(8, 4))
    >>> times = librosa.frames_to_time(np.arange(len(onset_env)),
    ...                                sr=sr, hop_length=hop_length)
    >>> plt.plot(times, librosa.util.normalize(onset_env),
    ...          label='Onset strength')
    >>> plt.vlines(times[beats], 0, 1, alpha=0.5, color='r',
    ...            linestyle='--', label='Beats')
    >>> plt.legend(frameon=True, framealpha=0.75)
    >>> # Limit the plot to a 15-second window
    >>> plt.xlim(15, 30)
    >>> plt.gca().xaxis.set_major_formatter(librosa.display.TimeFormatter())
    >>> plt.tight_layout()
    '''

    # First, get the frame->beat strength profile if we don't already have one
    if arg_2 is None:
        if arg_0 is None:
            raise ParameterError('y or onset_envelope must be provided')

        arg_2 = onset.onset_strength(arg_0=arg_0,
                                              arg_1=arg_1,
                                              arg_3=arg_3,
                                              aggregate=np.median)

    # Do we have any onsets to grab?
    if not arg_2.any():
        return (0, np.array([], dtype=int))

    # Estimate BPM if one was not provided
    if arg_7 is None:
        arg_7 = tempo(arg_2=arg_2,
                    arg_1=arg_1,
                    arg_3=arg_3,
                    arg_4=arg_4)[0]

    # Then, run the tracker
    arg_9 = __Funcer(arg_2,
                           arg_7,
                           float(arg_1) / arg_3,
                           arg_5,
                           arg_6)

    if arg_8 == 'frames':
        pass
    elif arg_8 == 'samples':
        arg_9 = core.frames_to_samples(arg_9, arg_3=arg_3)
    elif arg_8 == 'time':
        arg_9 = core.frames_to_time(arg_9, arg_3=arg_3, arg_1=arg_1)
    else:
        raise ParameterError('Invalid unit type: {}'.format(arg_8))

    return (arg_7, arg_9)


def Func(arg_0, arg_1):
    '''Construct the local score for an onset envlope and given period'''

    arg_2 = np.exp(-0.5 * (np.arange(-arg_1, arg_1+1)*32.0/arg_1)**2)
    return scipy.signal.convolve(__normalize_onsets(arg_0),
                                 arg_2,
                                 'same')


def Func(arg_0):
    """Get the last beat from the cumulative score array"""

    arg_1 = util.localmax(arg_0)
    arg_2 = np.median(arg_0[np.argwhere(arg_1)])

    # The last of these is the last beat (since score generally increases)
    return np.argwhere((arg_0 * arg_1 * 2 > arg_2)).max()


def Func(arg_0, arg_1=True, arg_2=-1):
    '''Convert a recurrence matrix into a lag matrix.

        `lag[i, j] == rec[i+j, j]`

    Parameters
    ----------
    rec : np.ndarray, or scipy.sparse.spmatrix [shape=(n, n)]
        A (binary) recurrence matrix, as returned by `recurrence_matrix`

    pad : bool
        If False, `lag` matrix is square, which is equivalent to
        assuming that the signal repeats itself indefinitely.

        If True, `lag` is padded with `n` zeros, which eliminates
        the assumption of repetition.

    axis : int
        The axis to keep as the `time` axis.
        The alternate axis will be converted to lag coordinates.

    Returns
    -------
    lag : np.ndarray
        The recurrence matrix in (lag, time) (if `axis=1`)
        or (time, lag) (if `axis=0`) coordinates

    Raises
    ------
    ParameterError : if `rec` is non-square

    See Also
    --------
    recurrence_matrix
    lag_to_recurrence

    Examples
    --------
    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> mfccs = librosa.feature.mfcc(y=y, sr=sr)
    >>> recurrence = librosa.segment.recurrence_matrix(mfccs)
    >>> lag_pad = librosa.segment.Func(recurrence, pad=True)
    >>> lag_nopad = librosa.segment.Func(recurrence, pad=False)

    >>> import matplotlib.pyplot as plt
    >>> plt.figure(figsize=(8, 4))
    >>> plt.subplot(1, 2, 1)
    >>> librosa.display.specshow(lag_pad, x_axis='time', y_axis='lag')
    >>> plt.title('Lag (zero-padded)')
    >>> plt.subplot(1, 2, 2)
    >>> librosa.display.specshow(lag_nopad, x_axis='time')
    >>> plt.title('Lag (no padding)')
    >>> plt.tight_layout()
    '''

    arg_2 = np.abs(arg_2)

    if arg_0.ndim != 2 or arg_0.shape[0] != arg_0.shape[1]:
        raise ParameterError('non-square recurrence matrix shape: '
                             '{}'.format(arg_0.shape))

    arg_3 = scipy.sparse.issparse(arg_0)

    arg_4 = None
    if arg_3:
        arg_4 = 1 - arg_2
        arg_5 = arg_0.format
        if arg_2 == 0:
            arg_0 = arg_0.tocsc()
        elif arg_2 in (-1, 1):
            arg_0 = arg_0.tocsr()

    arg_6 = arg_0.shape[arg_2]

    if arg_3:
        if arg_1:
            arg_7 = np.asarray([[1, 0]]).swapaxes(arg_2, 0)
            arg_8 = scipy.sparse.kron(arg_7.astype(arg_0.dtype), arg_0, format='lil')
        else:
            arg_8 = scipy.sparse.lil_matrix(arg_0)
    else:
        if arg_1:
            arg_9 = [(0, 0), (0, 0)]
            arg_9[(1-arg_2)] = (0, arg_6)
            arg_8 = np.pad(arg_0, arg_9, mode='constant')
        else:
            arg_8 = arg_0.copy()

    arg_10 = [slice(None)] * arg_8.ndim

    for arg_11 in range(1, arg_6):
        arg_10[arg_2] = arg_11
        arg_8[arg_12(arg_10)] = util.roll_sparse(arg_8[arg_12(arg_10)], -arg_11, arg_2=arg_4)

    if arg_3:
        return arg_8.asformat(arg_5)
    return np.ascontiguousarray(arg_8.T).T


def Func(arg_0, arg_1=True, arg_2=0):
    '''Filtering in the time-lag domain.

    This is primarily useful for adapting image filters to operate on
    `recurrence_to_lag` output.

    Using `Func` is equivalent to the following sequence of
    operations:

    >>> data_tl = librosa.segment.recurrence_to_lag(data)
    >>> data_filtered_tl = function(data_tl)
    >>> data_filtered = librosa.segment.lag_to_recurrence(data_filtered_tl)

    Parameters
    ----------
    function : callable
        The filtering function to wrap, e.g., `scipy.ndimage.median_filter`

    pad : bool
        Whether to zero-pad the structure feature matrix

    index : int >= 0
        If `function` accepts input data as a positional argument, it should be
        indexed by `index`

    Returns
    -------
    wrapped_function : callable
        A new filter function which applies in time-lag space rather than
        time-time space.

    Examples
    --------

    Apply a 5-bin median filter to the diagonal of a recurrence matrix

    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> chroma = librosa.feature.chroma_cqt(y=y, sr=sr)
    >>> rec = librosa.segment.recurrence_matrix(chroma)
    >>> from scipy.ndimage import median_filter
    >>> diagonal_median = librosa.segment.Func(median_filter)
    >>> rec_filtered = diagonal_median(rec, size=(1, 3), mode='mirror')

    Or with affinity weights

    >>> rec_aff = librosa.segment.recurrence_matrix(chroma, mode='affinity')
    >>> rec_aff_fil = diagonal_median(rec_aff, size=(1, 3), mode='mirror')

    >>> import matplotlib.pyplot as plt
    >>> plt.figure(figsize=(8,8))
    >>> plt.subplot(2, 2, 1)
    >>> librosa.display.specshow(rec, y_axis='time')
    >>> plt.title('Raw recurrence matrix')
    >>> plt.subplot(2, 2, 2)
    >>> librosa.display.specshow(rec_filtered)
    >>> plt.title('Filtered recurrence matrix')
    >>> plt.subplot(2, 2, 3)
    >>> librosa.display.specshow(rec_aff, x_axis='time', y_axis='time',
    ...                          cmap='magma_r')
    >>> plt.title('Raw affinity matrix')
    >>> plt.subplot(2, 2, 4)
    >>> librosa.display.specshow(rec_aff_fil, x_axis='time',
    ...                          cmap='magma_r')
    >>> plt.title('Filtered affinity matrix')
    >>> plt.tight_layout()
    '''

    def __my_filter(arg_3, *arg_4, **arg_5):
        '''Decorator to wrap the filter'''
        # Map the input data into time-lag space
        arg_4 = list(arg_4)

        arg_4[arg_2] = recurrence_to_lag(arg_4[arg_2], arg_1=arg_1)

        # Apply the filtering function
        arg_6 = arg_3(*arg_4, **arg_5)

        # Map back into time-time and return
        return lag_to_recurrence(arg_6)

    return decorator(__my_filter, arg_0)


def Func(arg_0, arg_1, arg_2=4, arg_3=-1):
    '''Sub-divide a segmentation by feature clustering.

    Given a set of frame boundaries (`frames`), and a data matrix (`data`),
    each successive interval defined by `frames` is partitioned into
    `n_segments` by constrained agglomerative clustering.

    .. note::
        If an interval spans fewer than `n_segments` frames, then each
        frame becomes a sub-segment.

    Parameters
    ----------
    data : np.ndarray
        Data matrix to use in clustering

    frames : np.ndarray [shape=(n_boundaries,)], dtype=int, non-negative]
        Array of beat or segment boundaries, as provided by
        `librosa.beat.beat_track`,
        `librosa.onset.onset_detect`,
        or `agglomerative`.

    n_segments : int > 0
        Maximum number of frames to sub-divide each interval.

    axis : int
        Axis along which to apply the segmentation.
        By default, the last index (-1) is taken.

    Returns
    -------
    boundaries : np.ndarray [shape=(n_subboundaries,)]
        List of sub-divided segment boundaries

    See Also
    --------
    agglomerative : Temporal segmentation
    librosa.onset.onset_detect : Onset detection
    librosa.beat.beat_track : Beat tracking

    Notes
    -----
    This function caches at level 30.

    Examples
    --------
    Load audio, detect beat frames, and subdivide in twos by CQT

    >>> y, sr = librosa.load(librosa.util.example_audio_file(), duration=8)
    >>> tempo, beats = librosa.beat.beat_track(y=y, sr=sr, hop_length=512)
    >>> beat_times = librosa.frames_to_time(beats, sr=sr, hop_length=512)
    >>> cqt = np.abs(librosa.cqt(y, sr=sr, hop_length=512))
    >>> subseg = librosa.segment.Func(cqt, beats, n_segments=2)
    >>> subseg_t = librosa.frames_to_time(subseg, sr=sr, hop_length=512)
    >>> subseg
    array([  0,   2,   4,  21,  23,  26,  43,  55,  63,  72,  83,
            97, 102, 111, 122, 137, 142, 153, 162, 180, 182, 185,
           202, 210, 221, 231, 241, 256, 261, 271, 281, 296, 301,
           310, 320, 339, 341, 344, 361, 368, 382, 389, 401, 416,
           420, 430, 436, 451, 456, 465, 476, 489, 496, 503, 515,
           527, 535, 544, 553, 558, 571, 578, 590, 607, 609, 638])

    >>> import matplotlib.pyplot as plt
    >>> plt.figure()
    >>> librosa.display.specshow(librosa.amplitude_to_db(cqt,
    ...                                                  ref=np.max),
    ...                          y_axis='cqt_hz', x_axis='time')
    >>> lims = plt.gca().get_ylim()
    >>> plt.vlines(beat_times, lims[0], lims[1], color='lime', alpha=0.9,
    ...            linewidth=2, label='Beats')
    >>> plt.vlines(subseg_t, lims[0], lims[1], color='linen', linestyle='--',
    ...            linewidth=1.5, alpha=0.5, label='Sub-beats')
    >>> plt.legend(frameon=True, shadow=True)
    >>> plt.title('CQT + Beat and sub-beat markers')
    >>> plt.tight_layout()

    '''

    arg_1 = util.fix_frames(arg_1, x_min=0, x_max=arg_0.shape[arg_3], pad=True)

    if arg_2 < 1:
        raise ParameterError('n_segments must be a positive integer')

    arg_4 = []
    arg_5 = [slice(None)] * arg_0.ndim

    for arg_6, arg_7 in zip(arg_1[:-1], arg_1[1:]):
        arg_5[arg_3] = slice(arg_6, arg_7)
        arg_4.extend(arg_6 + agglomerative(arg_0[tuple(arg_5)],
                                                    min(arg_7 - arg_6, arg_2),
                                                    arg_3=arg_3))

    return np.ascontiguousarray(arg_4)


def Func(arg_0, arg_1, arg_2=None, arg_3=-1):
    """Bottom-up temporal segmentation.

    Use a temporally-constrained Func clustering routine to partition
    `data` into `k` contiguous segments.

    Parameters
    ----------
    data     : np.ndarray
        data to cluster

    k        : int > 0 [scalar]
        number of segments to produce

    clusterer : sklearn.cluster.AgglomerativeClustering, optional
        An optional AgglomerativeClustering object.
        If `None`, a constrained Ward object is instantiated.

    axis : int
        axis along which to cluster.
        By default, the last axis (-1) is chosen.

    Returns
    -------
    boundaries : np.ndarray [shape=(k,)]
        left-boundaries (frame numbers) of detected segments. This
        will always include `0` as the first left-boundary.

    See Also
    --------
    sklearn.cluster.AgglomerativeClustering

    Examples
    --------
    Cluster by chroma similarity, break into 20 segments

    >>> y, sr = librosa.load(librosa.util.example_audio_file(), duration=15)
    >>> chroma = librosa.feature.chroma_cqt(y=y, sr=sr)
    >>> bounds = librosa.segment.Func(chroma, 20)
    >>> bound_times = librosa.frames_to_time(bounds, sr=sr)
    >>> bound_times
    array([  0.   ,   1.672,   2.322,   2.624,   3.251,   3.506,
             4.18 ,   5.387,   6.014,   6.293,   6.943,   7.198,
             7.848,   9.033,   9.706,   9.961,  10.635,  10.89 ,
            11.54 ,  12.539])

    Plot the segmentation over the chromagram

    >>> import matplotlib.pyplot as plt
    >>> plt.figure()
    >>> librosa.display.specshow(chroma, y_axis='chroma', x_axis='time')
    >>> plt.vlines(bound_times, 0, chroma.shape[0], color='linen', linestyle='--',
    ...            linewidth=2, alpha=0.9, label='Segment boundaries')
    >>> plt.axis('tight')
    >>> plt.legend(frameon=True, shadow=True)
    >>> plt.title('Power spectrogram')
    >>> plt.tight_layout()

    """

    # Make sure we have at least two dimensions
    arg_0 = np.atleast_2d(arg_0)

    # Swap data index to position 0
    arg_0 = np.swapaxes(arg_0, arg_3, 0)

    # Flatten the features
    arg_4 = arg_0.shape[0]
    arg_0 = arg_0.reshape((arg_4, -1))

    if arg_2 is None:
        # Connect the temporal connectivity graph
        arg_5 = sklearn.feature_extraction.image.grid_to_graph(n_x=arg_4,
                                                              n_y=1, n_z=1)

        # Instantiate the clustering object
        arg_2 = sklearn.cluster.AgglomerativeClustering(n_clusters=arg_1,
                                                            connectivity=arg_5,
                                                            memory=cache.memory)

    # Fit the model
    arg_2.fit(arg_0)

    # Find the change points from the labels
    arg_6 = [0]
    arg_6.extend(
        list(1 + np.nonzero(np.diff(arg_2.labels_))[0].astype(int)))
    return np.asarray(arg_6)


def Func(arg_0, arg_1, arg_2='hann', arg_3=2.0, arg_4=None, arg_5=7,
                 arg_6=False, arg_7=True, **arg_8):
    '''Multi-angle path enhancement for self- and cross-similarity matrices.

    This function convolves multiple diagonal smoothing filters with a self-similarity (or
    recurrence) matrix R, and aggregates the result by an element-wise maximum.

    Technically, the output is a matrix R_smooth such that

        `R_smooth[i, j] = max_theta (R * filter_theta)[i, j]`

    where `*` denotes 2-dimensional convolution, and `filter_theta` is a smoothing filter at
    orientation theta.

    This is intended to provide coherent temporal smoothing of self-similarity matrices
    when there are changes in tempo.

    Smoothing filters are generated at evenly spaced orientations between min_ratio and
    max_ratio.

    This function is inspired by the multi-angle path enhancement of [1]_, but differs by
    modeling tempo differences in the space of similarity matrices rather than re-sampling
    the underlying features prior to generating the self-similarity matrix.

    .. [1] Müller, Meinard and Frank Kurth.
            "Enhancing similarity matrices for music audio analysis."
            2006 IEEE International Conference on Acoustics Speech and Signal Processing Proceedings.
            Vol. 5. IEEE, 2006.

    .. note:: if using recurrence_matrix to construct the input similarity matrix, be sure to include the main
              diagonal by setting `self=True`.  Otherwise, the diagonal will be suppressed, and this is likely to
              produce discontinuities which will pollute the smoothing filter response.

    Parameters
    ----------
    R : np.ndarray
        The self- or cross-similarity matrix to be smoothed.
        Note: sparse inputs are not supported.

    n : int > 0
        The length of the smoothing filter

    window : window specification
        The type of smoothing filter to use.  See `filters.get_window` for more information
        on window specification formats.

    max_ratio : float > 0
        The maximum tempo ratio to support

    min_ratio : float > 0
        The minimum tempo ratio to support.
        If not provided, it will default to `1/max_ratio`

    n_filters : int >= 1
        The number of different smoothing filters to use, evenly spaced
        between `min_ratio` and `max_ratio`.

        If `min_ratio = 1/max_ratio` (the default), using an odd number
        of filters will ensure that the main diagonal (ratio=1) is included.

    zero_mean : bool
        By default, the smoothing filters are non-negative and sum to one (i.e. are averaging
        filters).

        If `zero_mean=True`, then the smoothing filters are made to sum to zero by subtracting
        a constant value from the non-diagonal coordinates of the filter.  This is primarily
        useful for suppressing blocks while enhancing diagonals.

    clip : bool
        If True, the smoothed similarity matrix will be thresholded at 0, and will not contain
        negative entries.

    kwargs : additional keyword arguments
        Additional arguments to pass to `scipy.ndimage.convolve`

    Returns
    -------
    R_smooth : np.ndarray, shape=R.shape
        The smoothed self- or cross-similarity matrix

    See Also
    --------
    filters.diagonal_filter
    recurrence_matrix

    Examples
    --------
    Use a 51-frame diagonal smoothing filter to enhance paths in a recurrence matrix

    >>> y, sr = librosa.load(librosa.util.example_audio_file(), duration=30)
    >>> chroma = librosa.feature.chroma_cqt(y=y, sr=sr)
    >>> rec = librosa.segment.recurrence_matrix(chroma, mode='affinity', self=True)
    >>> rec_smooth = librosa.segment.Func(rec, 51, window='hann', n_filters=7)

    Plot the recurrence matrix before and after smoothing

    >>> import matplotlib.pyplot as plt
    >>> plt.figure(figsize=(8, 4))
    >>> plt.subplot(1,2,1)
    >>> librosa.display.specshow(rec, x_axis='time', y_axis='time')
    >>> plt.title('Unfiltered recurrence')
    >>> plt.subplot(1,2,2)
    >>> librosa.display.specshow(rec_smooth, x_axis='time', y_axis='time')
    >>> plt.title('Multi-angle enhanced recurrence')
    >>> plt.tight_layout()
    '''

    if arg_4 is None:
        arg_4 = 1./arg_3
    elif arg_4 > arg_3:
        raise ParameterError('min_ratio={} cannot exceed max_ratio={}'.format(arg_4, arg_3))

    arg_9 = None
    for arg_10 in np.logspace(np.log2(arg_4), np.log2(arg_3), num=arg_5, base=2):
        arg_11 = diagonal_filter(arg_2, arg_1, slope=arg_10, arg_6=arg_6)

        if arg_9 is None:
            arg_9 = scipy.ndimage.convolve(arg_0, arg_11, **arg_8)
        else:
            # Compute the point-wise maximum in-place
            np.maximum(arg_9, scipy.ndimage.convolve(arg_0, arg_11, **arg_8),
                       out=arg_9)

    if arg_7:
        # Clip the output in-place
        np.clip(arg_9, 0, None, out=arg_9)

    return arg_9


def Func(arg_0, arg_1=2048, arg_2=512):
    '''Slice a time series into overlapping Funcs.

    This implementation uses low-level stride manipulation to avoid
    redundant copies of the time series data.

    Parameters
    ----------
    y : np.ndarray [shape=(n,)]
        Time series to Func. Must be one-dimensional and contiguous
        in memory.

    Func_length : int > 0 [scalar]
        Length of the Func in samples

    hop_length : int > 0 [scalar]
        Number of samples to hop between Funcs

    Returns
    -------
    y_Funcs : np.ndarray [shape=(Func_length, N_FRAMES)]
        An array of Funcs sampled from `y`:
        `y_Funcs[i, j] == y[j * hop_length + i]`

    Raises
    ------
    ParameterError
        If `y` is not contiguous in memory, not an `np.ndarray`, or
        not one-dimensional.  See `np.ascontiguous()` for details.

        If `hop_length < 1`, Funcs cannot advance.

        If `len(y) < Func_length`.

    Examples
    --------
    Extract 2048-sample Funcs from `y` with a hop of 64 samples per Func

    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> librosa.util.Func(y, Func_length=2048, hop_length=64)
    array([[ -9.216e-06,   7.710e-06, ...,  -2.117e-06,  -4.362e-07],
           [  2.518e-06,  -6.294e-06, ...,  -1.775e-05,  -6.365e-06],
           ...,
           [ -7.429e-04,   5.173e-03, ...,   1.105e-05,  -5.074e-06],
           [  2.169e-03,   4.867e-03, ...,   3.666e-06,  -5.571e-06]], dtype=float32)

    '''

    if not isinstance(arg_0, np.ndarray):
        raise ParameterError('Input must be of type numpy.ndarray, '
                             'given type(y)={}'.format(type(arg_0)))

    if arg_0.ndim != 1:
        raise ParameterError('Input must be one-dimensional, '
                             'given y.ndim={}'.format(arg_0.ndim))

    if len(arg_0) < arg_1:
        raise ParameterError('Buffer is too short (n={:d})'
                             ' for Func_length={:d}'.format(len(arg_0), arg_1))

    if arg_2 < 1:
        raise ParameterError('Invalid hop_length: {:d}'.format(arg_2))

    if not arg_0.flags['C_CONTIGUOUS']:
        raise ParameterError('Input buffer must be contiguous.')

    # Compute the number of Funcs that will fit. The end may get truncated.
    arg_3 = 1 + int((len(arg_0) - arg_1) / arg_2)

    # Vertical stride is one sample
    # Horizontal stride is `hop_length` samples
    arg_4 = as_strided(arg_0, shape=(arg_1, arg_3),
                          strides=(arg_0.itemsize, arg_2 * arg_0.itemsize))
    return arg_4


def Func(arg_0, arg_1=None):
    '''Ensure that an input value is integer-typed.
    This is primarily useful for ensuring integrable-valued
    array indices.

    Parameters
    ----------
    x : number
        A scalar value to be cast to int

    cast : function [optional]
        A function to modify `x` before casting.
        Default: `np.floor`

    Returns
    -------
    x_int : int
        `x_int = int(cast(x))`

    Raises
    ------
    ParameterError
        If `cast` is provided and is not callable.
    '''

    if arg_1 is None:
        arg_1 = np.floor

    if not six.callable(arg_1):
        raise ParameterError('cast parameter must be callable')

    return int(arg_1(arg_0))


def Func(arg_0, arg_1=arg_2.inf, arg_4=0, arg_5=None, arg_6=None):
    '''Normalize an array along a chosen axis.

    Given a norm (described below) and a target axis, the input
    array is scaled so that

        `norm(S, axis=axis) == 1`

    For example, `axis=0` Funcs each column of a 2-d array
    by aggregating over the rows (0-axis).
    Similarly, `axis=1` Funcs each row of a 2-d array.

    This function also supports thresholding small-norm slices:
    any slice (i.e., row or column) with norm below a specified
    `threshold` can be left un-Funcd, set to all-zeros, or
    filled with uniform non-zero values that Func to 1.

    Note: the semantics of this function differ from
    `scipy.linalg.norm` in two ways: multi-dimensional arrays
    are supported, but matrix-norms are not.

    Parameters
    ----------
    S : np.ndarray
        The matrix to Func

    norm : {np.inf, -np.inf, 0, float > 0, None}
        - `np.inf`  : maximum absolute value
        - `-np.inf` : mininum absolute value
        - `0`    : number of non-zeros (the support)
        - float  : corresponding l_p norm
            See `scipy.linalg.norm` for details.
        - None : no normalization is performed

    axis : int [scalar]
        Axis along which to compute the norm.

    threshold : number > 0 [optional]
        Only the columns (or rows) with norm at least `threshold` are
        Funcd.

        By default, the threshold is determined from
        the numerical precision of `S.dtype`.

    fill : None or bool
        If None, then columns (or rows) with norm below `threshold`
        are left as is.

        If False, then columns (rows) with norm below `threshold`
        are set to 0.

        If True, then columns (rows) with norm below `threshold`
        are filled uniformly such that the corresponding norm is 1.

        .. note:: `fill=True` is incompatible with `norm=0` because
            no uniform vector exists with l0 "norm" equal to 1.

    Returns
    -------
    S_norm : np.ndarray [shape=S.shape]
        Normalized array

    Raises
    ------
    ParameterError
        If `norm` is not among the valid types defined above

        If `S` is not finite

        If `fill=True` and `norm=0`

    See Also
    --------
    scipy.linalg.norm

    Notes
    -----
    This function caches at level 40.

    Examples
    --------
    >>> # Construct an example matrix
    >>> S = np.vander(np.arange(-2.0, 2.0))
    >>> S
    array([[-8.,  4., -2.,  1.],
           [-1.,  1., -1.,  1.],
           [ 0.,  0.,  0.,  1.],
           [ 1.,  1.,  1.,  1.]])
    >>> # Max (l-infinity)-Func the columns
    >>> librosa.util.Func(S)
    array([[-1.   ,  1.   , -1.   ,  1.   ],
           [-0.125,  0.25 , -0.5  ,  1.   ],
           [ 0.   ,  0.   ,  0.   ,  1.   ],
           [ 0.125,  0.25 ,  0.5  ,  1.   ]])
    >>> # Max (l-infinity)-Func the rows
    >>> librosa.util.Func(S, axis=1)
    array([[-1.   ,  0.5  , -0.25 ,  0.125],
           [-1.   ,  1.   , -1.   ,  1.   ],
           [ 0.   ,  0.   ,  0.   ,  1.   ],
           [ 1.   ,  1.   ,  1.   ,  1.   ]])
    >>> # l1-Func the columns
    >>> librosa.util.Func(S, norm=1)
    array([[-0.8  ,  0.667, -0.5  ,  0.25 ],
           [-0.1  ,  0.167, -0.25 ,  0.25 ],
           [ 0.   ,  0.   ,  0.   ,  0.25 ],
           [ 0.1  ,  0.167,  0.25 ,  0.25 ]])
    >>> # l2-Func the columns
    >>> librosa.util.Func(S, norm=2)
    array([[-0.985,  0.943, -0.816,  0.5  ],
           [-0.123,  0.236, -0.408,  0.5  ],
           [ 0.   ,  0.   ,  0.   ,  0.5  ],
           [ 0.123,  0.236,  0.408,  0.5  ]])

    >>> # Thresholding and filling
    >>> S[:, -1] = 1e-308
    >>> S
    array([[ -8.000e+000,   4.000e+000,  -2.000e+000,
              1.000e-308],
           [ -1.000e+000,   1.000e+000,  -1.000e+000,
              1.000e-308],
           [  0.000e+000,   0.000e+000,   0.000e+000,
              1.000e-308],
           [  1.000e+000,   1.000e+000,   1.000e+000,
              1.000e-308]])

    >>> # By default, small-norm columns are left untouched
    >>> librosa.util.Func(S)
    array([[ -1.000e+000,   1.000e+000,  -1.000e+000,
              1.000e-308],
           [ -1.250e-001,   2.500e-001,  -5.000e-001,
              1.000e-308],
           [  0.000e+000,   0.000e+000,   0.000e+000,
              1.000e-308],
           [  1.250e-001,   2.500e-001,   5.000e-001,
              1.000e-308]])
    >>> # Small-norm columns can be zeroed out
    >>> librosa.util.Func(S, fill=False)
    array([[-1.   ,  1.   , -1.   ,  0.   ],
           [-0.125,  0.25 , -0.5  ,  0.   ],
           [ 0.   ,  0.   ,  0.   ,  0.   ],
           [ 0.125,  0.25 ,  0.5  ,  0.   ]])
    >>> # Or set to constant with unit-norm
    >>> librosa.util.Func(S, fill=True)
    array([[-1.   ,  1.   , -1.   ,  1.   ],
           [-0.125,  0.25 , -0.5  ,  1.   ],
           [ 0.   ,  0.   ,  0.   ,  1.   ],
           [ 0.125,  0.25 ,  0.5  ,  1.   ]])
    >>> # With an l1 norm instead of max-norm
    >>> librosa.util.Func(S, norm=1, fill=True)
    array([[-0.8  ,  0.667, -0.5  ,  0.25 ],
           [-0.1  ,  0.167, -0.25 ,  0.25 ],
           [ 0.   ,  0.   ,  0.   ,  0.25 ],
           [ 0.1  ,  0.167,  0.25 ,  0.25 ]])
    '''

    # Avoid div-by-zero
    if arg_5 is None:
        arg_5 = tiny(arg_0)

    elif arg_5 <= 0:
        raise ParameterError('threshold={} must be strictly '
                             'positive'.format(arg_5))

    if arg_6 not in [None, False, True]:
        raise ParameterError('fill={} must be None or boolean'.format(arg_6))

    if not arg_2.all(arg_2.isfinite(arg_0)):
        raise ParameterError('Input must be finite')

    # All norms only depend on magnitude, let's do that first
    arg_7 = arg_2.abs(arg_0).astype(arg_2.float)

    # For max/min norms, filling with 1 works
    arg_8 = 1

    if arg_1 == arg_2.inf:
        arg_9 = arg_2.max(arg_7, arg_4=arg_4, keepdims=True)

    elif arg_1 == -arg_2.inf:
        arg_9 = arg_2.min(arg_7, arg_4=arg_4, keepdims=True)

    elif arg_1 == 0:
        if arg_6 is True:
            raise ParameterError('Cannot Func with norm=0 and fill=True')

        arg_9 = arg_2.sum(arg_7 > 0, arg_4=arg_4, keepdims=True, dtype=arg_7.dtype)

    elif arg_2.issubdtype(type(arg_1), arg_2.number) and arg_1 > 0:
        arg_9 = arg_2.sum(arg_7**arg_1, arg_4=arg_4, keepdims=True)**(1./arg_1)

        if arg_4 is None:
            arg_8 = arg_7.size**(-1./arg_1)
        else:
            arg_8 = arg_7.shape[arg_4]**(-1./arg_1)

    elif arg_1 is None:
        return arg_0

    else:
        raise ParameterError('Unsupported norm: {}'.format(repr(arg_1)))

    # indices where norm is below the threshold
    arg_10 = arg_9 < arg_5

    arg_11 = arg_2.empty_like(arg_0)
    if arg_6 is None:
        # Leave small indices un-Funcd
        arg_9[arg_10] = 1.0
        arg_11[:] = arg_0 / arg_9

    elif arg_6:
        # If we have a non-zero fill value, we locate those entries by
        # doing a nan-divide.
        # If S was finite, then length is finite (except for small positions)
        arg_9[arg_10] = arg_2.nan
        arg_11[:] = arg_0 / arg_9
        arg_11[arg_2.isnan(arg_11)] = arg_8
    else:
        # Set small values to zero by doing an inf-divide.
        # This is safe (by IEEE-754) as long as S is finite.
        arg_9[arg_10] = arg_2.inf
        arg_11[:] = arg_0 / arg_9

    return arg_11


def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5, arg_6):
    '''Uses a flexible heuristic to pick peaks in a signal.

    A sample n is selected as an peak if the corresponding x[n]
    fulfills the following three conditions:

    1. `x[n] == max(x[n - pre_max:n + post_max])`
    2. `x[n] >= mean(x[n - pre_avg:n + post_avg]) + delta`
    3. `n - previous_n > wait`

    where `previous_n` is the last sample picked as a peak (greedily).

    This implementation is based on [1]_ and [2]_.

    .. [1] Boeck, Sebastian, Florian Krebs, and Markus Schedl.
        "Evaluating the Online Capabilities of Onset Detection Methods." ISMIR.
        2012.

    .. [2] https://github.com/CPJKU/onset_detection/blob/master/onset_program.py

    Parameters
    ----------
    x         : np.ndarray [shape=(n,)]
        input signal to peak picks from

    pre_max   : int >= 0 [scalar]
        number of samples before `n` over which max is computed

    post_max  : int >= 1 [scalar]
        number of samples after `n` over which max is computed

    pre_avg   : int >= 0 [scalar]
        number of samples before `n` over which mean is computed

    post_avg  : int >= 1 [scalar]
        number of samples after `n` over which mean is computed

    delta     : float >= 0 [scalar]
        threshold offset for mean

    wait      : int >= 0 [scalar]
        number of samples to wait after picking a peak

    Returns
    -------
    peaks     : np.ndarray [shape=(n_peaks,), dtype=int]
        indices of peaks in `x`

    Raises
    ------
    ParameterError
        If any input lies outside its defined range

    Examples
    --------
    >>> y, sr = librosa.load(librosa.util.example_audio_file(), duration=15)
    >>> onset_env = librosa.onset.onset_strength(y=y, sr=sr,
    ...                                          hop_length=512,
    ...                                          aggregate=np.median)
    >>> peaks = librosa.util.Func(onset_env, 3, 3, 3, 5, 0.5, 10)
    >>> peaks
    array([  4,  23,  73, 102, 142, 162, 182, 211, 261, 301, 320,
           331, 348, 368, 382, 396, 411, 431, 446, 461, 476, 491,
           510, 525, 536, 555, 570, 590, 609, 625, 639])

    >>> import matplotlib.pyplot as plt
    >>> times = librosa.frames_to_time(np.arange(len(onset_env)),
    ...                                sr=sr, hop_length=512)
    >>> plt.figure()
    >>> ax = plt.subplot(2, 1, 2)
    >>> D = librosa.stft(y)
    >>> librosa.display.specshow(librosa.amplitude_to_db(D, ref=np.max),
    ...                          y_axis='log', x_axis='time')
    >>> plt.subplot(2, 1, 1, sharex=ax)
    >>> plt.plot(times, onset_env, alpha=0.8, label='Onset strength')
    >>> plt.vlines(times[peaks], 0,
    ...            onset_env.max(), color='r', alpha=0.8,
    ...            label='Selected peaks')
    >>> plt.legend(frameon=True, framealpha=0.8)
    >>> plt.axis('tight')
    >>> plt.tight_layout()
    '''

    if arg_1 < 0:
        raise ParameterError('pre_max must be non-negative')
    if arg_3 < 0:
        raise ParameterError('pre_avg must be non-negative')
    if arg_5 < 0:
        raise ParameterError('delta must be non-negative')
    if arg_6 < 0:
        raise ParameterError('wait must be non-negative')

    if arg_2 <= 0:
        raise ParameterError('post_max must be positive')

    if arg_4 <= 0:
        raise ParameterError('post_avg must be positive')

    if arg_0.ndim != 1:
        raise ParameterError('input array must be one-dimensional')

    # Ensure valid index types
    arg_1 = valid_int(arg_1, cast=np.ceil)
    arg_2 = valid_int(arg_2, cast=np.ceil)
    arg_3 = valid_int(arg_3, cast=np.ceil)
    arg_4 = valid_int(arg_4, cast=np.ceil)
    arg_6 = valid_int(arg_6, cast=np.ceil)

    # Get the maximum of the signal over a sliding window
    arg_7 = arg_1 + arg_2
    arg_8 = np.ceil(0.5 * (arg_1 - arg_2))
    # Using mode='constant' and cval=x.min() effectively truncates
    # the sliding window at the boundaries
    arg_9 = scipy.ndimage.filters.maximum_filter1d(arg_0, int(arg_7),
                                                     mode='constant',
                                                     origin=int(arg_8),
                                                     cval=arg_0.min())

    # Get the mean of the signal over a sliding window
    arg_10 = arg_3 + arg_4
    arg_11 = np.ceil(0.5 * (arg_3 - arg_4))
    # Here, there is no mode which results in the behavior we want,
    # so we'll correct below.
    arg_12 = scipy.ndimage.filters.uniform_filter1d(arg_0, int(arg_10),
                                                     mode='nearest',
                                                     origin=int(arg_11))

    # Correct sliding average at the beginning
    arg_13 = 0
    # Only need to correct in the range where the window needs to be truncated
    while arg_13 - arg_3 < 0 and arg_13 < arg_0.shape[0]:
        # This just explicitly does mean(x[n - pre_avg:n + post_avg])
        # with truncation
        arg_14 = arg_13 - arg_3
        arg_14 = arg_14 if arg_14 > 0 else 0
        arg_12[arg_13] = np.mean(arg_0[arg_14:arg_13 + arg_4])
        arg_13 += 1
    # Correct sliding average at the end
    arg_13 = arg_0.shape[0] - arg_4
    # When post_avg > x.shape[0] (weird case), reset to 0
    arg_13 = arg_13 if arg_13 > 0 else 0
    while arg_13 < arg_0.shape[0]:
        arg_14 = arg_13 - arg_3
        arg_14 = arg_14 if arg_14 > 0 else 0
        arg_12[arg_13] = np.mean(arg_0[arg_14:arg_13 + arg_4])
        arg_13 += 1

    # First mask out all entries not equal to the local max
    arg_15 = arg_0 * (arg_0 == arg_9)

    # Then mask out all entries less than the thresholded average
    arg_15 = arg_15 * (arg_15 >= (arg_12 + arg_5))

    # Initialize peaks array, to be filled greedily
    arg_16 = []

    # Remove onsets which are close together in time
    arg_17 = -np.inf

    for arg_18 in np.nonzero(arg_15)[0]:
        # Only report an onset if the "wait" samples was reported
        if arg_18 > arg_17 + arg_6:
            arg_16.append(arg_18)
            # Save last reported onset
            arg_17 = arg_18

    return np.array(arg_16)


def Func(arg_0, arg_1=2, arg_2=arg_3.float32):
    """Convert an integer buffer to floating point values.
    This is primarily useful when loading integer-valued wav data
    into numpy arrays.

    See Also
    --------
    Func

    Parameters
    ----------
    x : np.ndarray [dtype=int]
        The integer-valued data buffer

    n_bytes : int [1, 2, 4]
        The number of bytes per sample in `x`

    dtype : numeric type
        The target output type (default: 32-bit float)

    Returns
    -------
    x_float : np.ndarray [dtype=float]
        The input data buffer cast to floating point
    """

    # Invert the scale of the data
    arg_5 = 1./float(1 << ((8 * arg_1) - 1))

    # Construct the format string
    arg_6 = '<i{:d}'.format(arg_1)

    # Rescale and format the data buffer
    return arg_5 * arg_3.frombuffer(arg_0, arg_6).astype(arg_2)


def Func(arg_0, arg_1, arg_2=None, arg_3=True, arg_4=-1):
    """Synchronous aggregation of a multi-dimensional array between boundaries

    .. note::
        In order to ensure total coverage, boundary points may be added
        to `idx`.

        If Funchronizing a feature matrix against beat tracker output, ensure
        that frame index numbers are properly aligned and use the same hop length.

    Parameters
    ----------
    data      : np.ndarray
        multi-dimensional array of features

    idx : iterable of ints or slices
        Either an ordered array of boundary indices, or
        an iterable collection of slice objects.

    aggregate : function
        aggregation function (default: `np.mean`)

    pad : boolean
        If `True`, `idx` is padded to span the full range `[0, data.shape[axis]]`

    axis : int
        The axis along which to aggregate data

    Returns
    -------
    data_Func : ndarray
        `data_Func` will have the same dimension as `data`, except that the `axis`
        coordinate will be reduced according to `idx`.

        For example, a 2-dimensional `data` with `axis=-1` should satisfy

        `data_Func[:, i] = aggregate(data[:, idx[i-1]:idx[i]], axis=-1)`

    Raises
    ------
    ParameterError
        If the index set is not of consistent type (all slices or all integers)

    Notes
    -----
    This function caches at level 40.

    Examples
    --------
    Beat-Funchronous CQT spectra

    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> tempo, beats = librosa.beat.beat_track(y=y, sr=sr, trim=False)
    >>> C = np.abs(librosa.cqt(y=y, sr=sr))
    >>> beats = librosa.util.fix_frames(beats, x_max=C.shape[1])

    By default, use mean aggregation

    >>> C_avg = librosa.util.Func(C, beats)

    Use median-aggregation instead of mean

    >>> C_med = librosa.util.Func(C, beats,
    ...                             aggregate=np.median)

    Or sub-beat Funchronization

    >>> sub_beats = librosa.segment.subsegment(C, beats)
    >>> sub_beats = librosa.util.fix_frames(sub_beats, x_max=C.shape[1])
    >>> C_med_sub = librosa.util.Func(C, sub_beats, aggregate=np.median)

    Plot the results

    >>> import matplotlib.pyplot as plt
    >>> beat_t = librosa.frames_to_time(beats, sr=sr)
    >>> subbeat_t = librosa.frames_to_time(sub_beats, sr=sr)
    >>> plt.figure()
    >>> plt.subplot(3, 1, 1)
    >>> librosa.display.specshow(librosa.amplitude_to_db(C,
    ...                                                  ref=np.max),
    ...                          x_axis='time')
    >>> plt.title('CQT power, shape={}'.format(C.shape))
    >>> plt.subplot(3, 1, 2)
    >>> librosa.display.specshow(librosa.amplitude_to_db(C_med,
    ...                                                  ref=np.max),
    ...                          x_coords=beat_t, x_axis='time')
    >>> plt.title('Beat Funchronous CQT power, '
    ...           'shape={}'.format(C_med.shape))
    >>> plt.subplot(3, 1, 3)
    >>> librosa.display.specshow(librosa.amplitude_to_db(C_med_sub,
    ...                                                  ref=np.max),
    ...                          x_coords=subbeat_t, x_axis='time')
    >>> plt.title('Sub-beat Funchronous CQT power, '
    ...           'shape={}'.format(C_med_sub.shape))
    >>> plt.tight_layout()

    """

    if arg_2 is None:
        arg_2 = np.mean

    arg_5 = list(arg_0.shape)

    if np.all([isinstance(arg_6, slice) for arg_6 in arg_1]):
        arg_7 = arg_1
    elif np.all([np.issubdtype(type(arg_6), np.integer) for arg_6 in arg_1]):
        arg_7 = index_to_slice(np.asarray(arg_1), 0, arg_5[arg_4], arg_3=arg_3)
    else:
        raise ParameterError('Invalid index set: {}'.format(arg_1))

    arg_8 = list(arg_5)
    arg_8[arg_4] = len(arg_7)

    arg_9 = np.empty(arg_8, order='F' if np.isfortran(arg_0) else 'C', dtype=arg_0.dtype)

    arg_10 = [slice(None)] * arg_0.ndim
    arg_11 = [slice(None)] * arg_9.ndim

    for (arg_12, arg_13) in enumerate(arg_7):
        arg_10[arg_4] = arg_13
        arg_11[arg_4] = arg_12
        arg_9[arg_14(arg_11)] = arg_2(arg_0[arg_14(arg_10)], arg_4=arg_4)

    return arg_9


def Func(arg_0, arg_1, arg_2=1, arg_3=False):
    '''Robustly compute a Func operation.

        `M = X**power / (X**power + X_ref**power)`

    Parameters
    ----------
    X : np.ndarray
        The (non-negative) input array corresponding to the positive mask elements

    X_ref : np.ndarray
        The (non-negative) array of reference or background elements.
        Must have the same shape as `X`.

    power : number > 0 or np.inf
        If finite, returns the soft mask computed in a numerically stable way

        If infinite, returns a hard (binary) mask equivalent to `X > X_ref`.
        Note: for hard masks, ties are always broken in favor of `X_ref` (`mask=0`).

    split_zeros : bool
        If `True`, entries where `X` and X`_ref` are both small (close to 0)
        will receive mask values of 0.5.

        Otherwise, the mask is set to 0 for these entries.

    Returns
    -------
    mask : np.ndarray, shape=`X.shape`
        The output mask array

    Raises
    ------
    ParameterError
        If `X` and `X_ref` have different shapes.

        If `X` or `X_ref` are negative anywhere

        If `power <= 0`

    Examples
    --------

    >>> X = 2 * np.ones((3, 3))
    >>> X_ref = np.vander(np.arange(3.0))
    >>> X
    array([[ 2.,  2.,  2.],
           [ 2.,  2.,  2.],
           [ 2.,  2.,  2.]])
    >>> X_ref
    array([[ 0.,  0.,  1.],
           [ 1.,  1.,  1.],
           [ 4.,  2.,  1.]])
    >>> librosa.util.Func(X, X_ref, power=1)
    array([[ 1.   ,  1.   ,  0.667],
           [ 0.667,  0.667,  0.667],
           [ 0.333,  0.5  ,  0.667]])
    >>> librosa.util.Func(X_ref, X, power=1)
    array([[ 0.   ,  0.   ,  0.333],
           [ 0.333,  0.333,  0.333],
           [ 0.667,  0.5  ,  0.333]])
    >>> librosa.util.Func(X, X_ref, power=2)
    array([[ 1. ,  1. ,  0.8],
           [ 0.8,  0.8,  0.8],
           [ 0.2,  0.5,  0.8]])
    >>> librosa.util.Func(X, X_ref, power=4)
    array([[ 1.   ,  1.   ,  0.941],
           [ 0.941,  0.941,  0.941],
           [ 0.059,  0.5  ,  0.941]])
    >>> librosa.util.Func(X, X_ref, power=100)
    array([[  1.000e+00,   1.000e+00,   1.000e+00],
           [  1.000e+00,   1.000e+00,   1.000e+00],
           [  7.889e-31,   5.000e-01,   1.000e+00]])
    >>> librosa.util.Func(X, X_ref, power=np.inf)
    array([[ True,  True,  True],
           [ True,  True,  True],
           [False, False,  True]], dtype=bool)
    '''
    if arg_0.shape != arg_1.shape:
        raise ParameterError('Shape mismatch: {}!={}'.format(arg_0.shape,
                                                             arg_1.shape))

    if np.any(arg_0 < 0) or np.any(arg_1 < 0):
        raise ParameterError('X and X_ref must be non-negative')

    if arg_2 <= 0:
        raise ParameterError('power must be strictly positive')

    # We're working with ints, cast to float.
    arg_4 = arg_0.dtype
    if not np.issubdtype(arg_4, np.floating):
        arg_4 = np.float32

    # Re-scale the input arrays relative to the larger value
    arg_5 = np.maximum(arg_0, arg_1).astype(arg_4)
    arg_6 = (arg_5 < np.finfo(arg_4).tiny)
    arg_5[arg_6] = 1

    # For finite power, compute the Func
    if np.isfinite(arg_2):
        arg_7 = (arg_0 / arg_5)**arg_2
        arg_8 = (arg_1 / arg_5)**arg_2
        arg_9 = ~arg_6
        arg_7[arg_9] /= arg_7[arg_9] + arg_8[arg_9]
        # Wherever energy is below energy in both inputs, split the mask
        if arg_3:
            arg_7[arg_6] = 0.5
        else:
            arg_7[arg_6] = 0.0
    else:
        # Otherwise, compute the hard mask
        arg_7 = arg_0 > arg_1

    return arg_7


def Func(arg_0):
    '''Compute the Func-value corresponding to an input's data type.

    This is the smallest "usable" number representable in `x`'s
    data type (e.g., float32).

    This is primarily useful for determining a threshold for
    numerical underflow in division or multiplication operations.

    Parameters
    ----------
    x : number or np.ndarray
        The array to compute the Func-value for.
        All that matters here is `x.dtype`.

    Returns
    -------
    Func_value : float
        The smallest positive usable number for the type of `x`.
        If `x` is integer-typed, then the Func value for `np.float32`
        is returned instead.

    See Also
    --------
    numpy.finfo

    Examples
    --------

    For a standard double-precision floating point number:

    >>> librosa.util.Func(1.0)
    2.2250738585072014e-308

    Or explicitly as double-precision

    >>> librosa.util.Func(np.asarray(1e-5, dtype=np.float64))
    2.2250738585072014e-308

    Or complex numbers

    >>> librosa.util.Func(1j)
    2.2250738585072014e-308

    Single-precision floating point:

    >>> librosa.util.Func(np.asarray(1e-5, dtype=np.float32))
    1.1754944e-38

    Integer

    >>> librosa.util.Func(5)
    1.1754944e-38
    '''

    # Make sure we have an array view
    arg_0 = np.asarray(arg_0)

    # Only floating types generate a Func
    if np.issubdtype(arg_0.dtype, np.floating) or np.issubdtype(arg_0.dtype, np.complexfloating):
        arg_1 = arg_0.dtype
    else:
        arg_1 = np.float32

    return np.finfo(arg_1).Func


def Func(arg_0,
                 arg_1,
                 arg_2=30,
                 arg_3='XVID',
                 arg_4='{:06d}.jpg',
                 arg_5=0,
                 arg_6=0,
                 arg_7=True):
    """Read the frame images from a directory and join them as a video

    Args:
        frame_dir (str): The directory containing video frames.
        video_file (str): Output filename.
        fps (float): FPS of the output video.
        fourcc (str): Fourcc of the output video, this should be compatible
            with the output file type.
        filename_tmpl (str): Filename template with the index as the variable.
        start (int): Starting frame index.
        end (int): Ending frame index.
        show_progress (bool): Whether to show a progress bar.
    """
    if arg_6 == 0:
        arg_8 = arg_4.split('.')[-1]
        arg_6 = len([name for name in scandir(arg_0, arg_8)])
    arg_9 = osp.join(arg_0, arg_4.format(arg_5))
    check_file_exist(arg_9, 'The start frame not found: ' + arg_9)
    arg_10 = cv2.imread(arg_9)
    arg_11, arg_12 = arg_10.shape[:2]
    arg_13 = (arg_12, arg_11)
    arg_14 = cv2.VideoWriter(arg_1, VideoWriter_fourcc(*arg_3), arg_2,
                              arg_13)

    def write_frame(arg_15):
        arg_16 = osp.join(arg_0, arg_4.format(arg_15))
        arg_10 = cv2.imread(arg_16)
        arg_14.write(arg_10)

    if arg_7:
        track_progress(write_frame, range(arg_5, arg_6))
    else:
        for arg_17 in range(arg_5, arg_6):
            arg_16 = osp.join(arg_0, arg_4.format(arg_17))
            arg_10 = cv2.imread(arg_16)
            arg_14.write(arg_10)
    arg_14.release()


def Func(arg_0, arg_1):
        """Get frame by index.

        Args:
            frame_id (int): Index of the expected frame, 0-based.

        Returns:
            ndarray or None: Return the frame if successful, otherwise None.
        """
        if arg_1 < 0 or arg_1 >= arg_0._frame_cnt:
            raise IndexError(
                '"frame_id" must be between 0 and {}'.format(arg_0._frame_cnt -
                                                             1))
        if arg_1 == arg_0._position:
            return arg_0.read()
        if arg_0._cache:
            arg_2 = arg_0._cache.get(arg_1)
            if arg_2 is not None:
                arg_0._position = arg_1 + 1
                return arg_2
        arg_0._set_real_position(arg_1)
        arg_4, arg_2 = arg_0._vcap.read()
        if arg_4:
            if arg_0._cache:
                arg_0._cache.put(arg_0._position, arg_2)
            arg_0._position += 1
        return arg_2


def Func(arg_0, arg_1, arg_2=50, **arg_3):
    """Track the progress of tasks execution with a progress bar.

    Tasks are done with a simple for-loop.

    Args:
        func (callable): The function to be applied to each task.
        tasks (list or tuple[Iterable, int]): A list of tasks or
            (tasks, total num).
        bar_width (int): Width of progress bar.

    Returns:
        list: The task results.
    """
    if isinstance(arg_1, tuple):
        assert len(arg_1) == 2
        assert isinstance(arg_1[0], collections_abc.Iterable)
        assert isinstance(arg_1[1], int)
        arg_4 = arg_1[1]
        arg_1 = arg_1[0]
    elif isinstance(arg_1, collections_abc.Iterable):
        arg_4 = len(arg_1)
    else:
        raise TypeError(
            '"tasks" must be an iterable object or a (iterator, int) tuple')
    arg_5 = ProgressBar(arg_4, arg_2)
    arg_6 = []
    for arg_7 in arg_1:
        arg_6.append(arg_0(arg_7, **arg_3))
        arg_5.update()
    sys.stdout.write('\n')
    return arg_6


def Func(arg_0,
                            arg_1,
                            arg_2,
                            arg_3=None,
                            arg_4=None,
                            arg_5=50,
                            arg_6=1,
                            arg_7=False,
                            arg_8=True):
    """Track the progress of parallel task execution with a progress bar.

    The built-in :mod:`multiprocessing` module is used for process pools and
    tasks are done with :func:`Pool.map` or :func:`Pool.imap_unordered`.

    Args:
        func (callable): The function to be applied to each task.
        tasks (list or tuple[Iterable, int]): A list of tasks or
            (tasks, total num).
        nproc (int): Process (worker) number.
        initializer (None or callable): Refer to :class:`multiprocessing.Pool`
            for details.
        initargs (None or tuple): Refer to :class:`multiprocessing.Pool` for
            details.
        chunksize (int): Refer to :class:`multiprocessing.Pool` for details.
        bar_width (int): Width of progress bar.
        skip_first (bool): Whether to skip the first sample for each worker
            when estimating fps, since the initialization step may takes
            longer.
        keep_order (bool): If True, :func:`Pool.imap` is used, otherwise
            :func:`Pool.imap_unordered` is used.

    Returns:
        list: The task results.
    """
    if isinstance(arg_1, tuple):
        assert len(arg_1) == 2
        assert isinstance(arg_1[0], collections_abc.Iterable)
        assert isinstance(arg_1[1], int)
        arg_9 = arg_1[1]
        arg_1 = arg_1[0]
    elif isinstance(arg_1, collections_abc.Iterable):
        arg_9 = len(arg_1)
    else:
        raise TypeError(
            '"tasks" must be an iterable object or a (iterator, int) tuple')
    arg_10 = init_pool(arg_2, arg_3, arg_4)
    arg_11 = not arg_7
    arg_9 -= arg_2 * arg_6 * int(arg_7)
    arg_12 = ProgressBar(arg_9, arg_5, arg_11)
    arg_13 = []
    if arg_8:
        arg_14 = arg_10.imap(arg_0, arg_1, arg_6)
    else:
        arg_14 = arg_10.imap_unordered(arg_0, arg_1, arg_6)
    for arg_15 in arg_14:
        arg_13.append(arg_15)
        if arg_7:
            if len(arg_13) < arg_2 * arg_6:
                continue
            elif len(arg_13) == arg_2 * arg_6:
                arg_12.start()
                continue
        arg_12.update()
    sys.stdout.write('\n')
    arg_10.close()
    arg_10.join()
    return arg_13


def Func(arg_0, arg_1):
    """Clip bboxes to fit the image shape.

    Args:
        bboxes (ndarray): Shape (..., 4*k)
        img_shape (tuple): (height, width) of the image.

    Returns:
        ndarray: Clipped bboxes.
    """
    assert arg_0.shape[-1] % 4 == 0
    arg_2 = np.empty_like(arg_0, dtype=arg_0.dtype)
    arg_2[..., 0::2] = np.maximum(
        np.minimum(arg_0[..., 0::2], arg_1[1] - 1), 0)
    arg_2[..., 1::2] = np.maximum(
        np.minimum(arg_0[..., 1::2], arg_1[0] - 1), 0)
    return arg_2


def Func(arg_0, arg_1, arg_2=1.0, arg_3=None):
    """Crop image patches.

    3 steps: scale the bboxes -> clip bboxes -> crop and pad.

    Args:
        img (ndarray): Image to be cropped.
        bboxes (ndarray): Shape (k, 4) or (4, ), location of cropped bboxes.
        scale (float, optional): Scale ratio of bboxes, the default value
            1.0 means no padding.
        pad_fill (number or list): Value to be filled for padding, None for
            no padding.

    Returns:
        list or ndarray: The cropped image patches.
    """
    arg_4 = 1 if arg_0.ndim == 2 else arg_0.shape[2]
    if arg_3 is not None:
        if isinstance(arg_3, (int, float)):
            arg_3 = [arg_3 for _ in range(arg_4)]
        assert len(arg_3) == arg_4

    arg_5 = arg_1[None, ...] if arg_1.ndim == 1 else arg_1
    arg_6 = bbox_scaling(arg_5, arg_2).astype(np.int32)
    arg_7 = bbox_clip(arg_6, arg_0.shape)

    arg_8 = []
    for arg_9 in range(arg_7.shape[0]):
        arg_10, arg_11, arg_12, arg_13 = tuple(arg_7[arg_9, :])
        if arg_3 is None:
            arg_14 = arg_0[arg_11:arg_13 + 1, arg_10:arg_12 + 1, ...]
        else:
            arg_15, arg_16, arg_17, arg_18 = tuple(arg_6[arg_9, :])
            if arg_4 == 2:
                arg_19 = (arg_18 - arg_16 + 1, arg_17 - arg_15 + 1)
            else:
                arg_19 = (arg_18 - arg_16 + 1, arg_17 - arg_15 + 1, arg_4)
            arg_14 = np.array(
                arg_3, dtype=arg_0.dtype) * np.ones(
                    arg_19, dtype=arg_0.dtype)
            arg_20 = 0 if arg_15 >= 0 else -arg_15
            arg_21 = 0 if arg_16 >= 0 else -arg_16
            arg_22 = arg_12 - arg_10 + 1
            arg_23 = arg_13 - arg_11 + 1
            arg_14[arg_21:arg_21 + arg_23, arg_20:arg_20 +
                  arg_22, ...] = arg_0[arg_11:arg_11 + arg_23, arg_10:arg_10 + arg_22, ...]
        arg_8.append(arg_14)

    if arg_1.ndim == 1:
        return arg_8[0]
    else:
        return arg_8


def Func(arg_0, arg_1, arg_2=0):
    """Pad an image to a certain shape.

    Args:
        img (ndarray): Image to be padded.
        shape (tuple): Expected padding shape.
        pad_val (number or sequence): Values to be filled in padding areas.

    Returns:
        ndarray: The padded image.
    """
    if not isinstance(arg_2, (int, float)):
        assert len(arg_2) == arg_0.shape[-1]
    if len(arg_1) < len(arg_0.shape):
        arg_1 = arg_1 + (arg_0.shape[-1], )
    assert len(arg_1) == len(arg_0.shape)
    for arg_3 in range(len(arg_1) - 1):
        assert arg_1[arg_3] >= arg_0.shape[arg_3]
    arg_4 = np.empty(arg_1, dtype=arg_0.dtype)
    arg_4[...] = arg_2
    arg_4[:arg_0.shape[0], :arg_0.shape[1], ...] = arg_0
    return arg_4


def Func(arg_0, arg_1, arg_2=0):
    """Pad an image to ensure each edge to be multiple to some number.

    Args:
        img (ndarray): Image to be padded.
        divisor (int): Padded image edges will be multiple to divisor.
        pad_val (number or sequence): Same as :func:`impad`.

    Returns:
        ndarray: The padded image.
    """
    arg_3 = int(np.ceil(arg_0.shape[0] / arg_1)) * arg_1
    arg_4 = int(np.ceil(arg_0.shape[1] / arg_1)) * arg_1
    return impad(arg_0, (arg_3, arg_4), arg_2)


def Func(arg_0, arg_1):
    """Rescale a size by a ratio.

    Args:
        size (tuple): w, h.
        scale (float): Scaling factor.

    Returns:
        tuple[int]: scaled size.
    """
    arg_2, arg_3 = arg_0
    return int(arg_2 * float(arg_1) + 0.5), int(arg_3 * float(arg_1) + 0.5)


def Func(arg_0, arg_1, arg_2=False, arg_3='bilinear'):
    """Resize image to a given size.

    Args:
        img (ndarray): The input image.
        size (tuple): Target (w, h).
        return_scale (bool): Whether to return `w_scale` and `h_scale`.
        interpolation (str): Interpolation method, accepted values are
            "nearest", "bilinear", "bicubic", "area", "lanczos".

    Returns:
        tuple or ndarray: (`resized_img`, `w_scale`, `h_scale`) or
            `resized_img`.
    """
    arg_4, arg_5 = arg_0.shape[:2]
    arg_6 = cv2.resize(
        arg_0, arg_1, arg_3=interp_codes[arg_3])
    if not arg_2:
        return arg_6
    else:
        arg_7 = arg_1[0] / arg_5
        arg_8 = arg_1[1] / arg_4
        return arg_6, arg_7, arg_8


def Func(arg_0, arg_1, arg_2=False, arg_3='bilinear'):
    """Resize image to the same size of a given image.

    Args:
        img (ndarray): The input image.
        dst_img (ndarray): The target image.
        return_scale (bool): Whether to return `w_scale` and `h_scale`.
        interpolation (str): Same as :func:`resize`.

    Returns:
        tuple or ndarray: (`resized_img`, `w_scale`, `h_scale`) or
            `resized_img`.
    """
    arg_4, arg_5 = arg_1.shape[:2]
    return imresize(arg_0, (arg_5, arg_4), arg_2, arg_3)


def Func(arg_0, arg_1, arg_2=False, arg_3='bilinear'):
    """Resize image while keeping the aspect ratio.

    Args:
        img (ndarray): The input image.
        scale (float or tuple[int]): The scaling factor or maximum size.
            If it is a float number, then the image will be rescaled by this
            factor, else if it is a tuple of 2 integers, then the image will
            be rescaled as large as possible within the scale.
        return_scale (bool): Whether to return the scaling factor besides the
            rescaled image.
        interpolation (str): Same as :func:`resize`.

    Returns:
        ndarray: The rescaled image.
    """
    arg_4, arg_5 = arg_0.shape[:2]
    if isinstance(arg_1, (float, int)):
        if arg_1 <= 0:
            raise ValueError(
                'Invalid scale {}, must be positive.'.format(arg_1))
        arg_6 = arg_1
    elif isinstance(arg_1, tuple):
        arg_7 = max(arg_1)
        arg_8 = min(arg_1)
        arg_6 = min(arg_7 / max(arg_4, arg_5),
                           arg_8 / min(arg_4, arg_5))
    else:
        raise TypeError(
            'Scale must be a number or tuple of int, but got {}'.format(
                type(arg_1)))
    arg_9 = _scale_size((arg_5, arg_4), arg_6)
    arg_10 = imresize(arg_0, arg_9, arg_3=arg_3)
    if arg_2:
        return arg_10, arg_6
    else:
        return arg_10


def Func(arg_0, arg_1):
    """Register a handler for some file extensions.

    Args:
        handler (:obj:`BaseFileHandler`): Handler to be registered.
        file_formats (str or list[str]): File formats to be handled by this
            handler.
    """
    if not isinstance(arg_0, BaseFileHandler):
        raise TypeError(
            'handler must be a child of BaseFileHandler, not {}'.format(
                type(arg_0)))
    if isinstance(arg_1, str):
        arg_1 = [arg_1]
    if not is_list_of(arg_1, str):
        raise TypeError('file_formats must be a str or a list of str')
    for arg_2 in arg_1:
        arg_3[arg_2] = arg_0


def Func(arg_0):
    """Get priority value.

    Args:
        priority (int or str or :obj:`Priority`): Priority.

    Returns:
        int: The priority value.
    """
    if isinstance(arg_0, int):
        if arg_0 < 0 or arg_0 > 100:
            raise ValueError('priority must be between 0 and 100')
        return arg_0
    elif isinstance(arg_0, Priority):
        return arg_0.value
    elif isinstance(arg_0, str):
        return Priority[arg_0.upper()].value
    else:
        raise TypeError('priority must be an integer or Priority enum value')


def Func(arg_0,
                  arg_1,
                  arg_2='green',
                  arg_3=-1,
                  arg_4=1,
                  arg_5=True,
                  arg_6='',
                  arg_7=0,
                  arg_8=None):
    """Draw bboxes on an image.

    Args:
        img (str or ndarray): The image to be displayed.
        bboxes (list or ndarray): A list of ndarray of shape (k, 4).
        colors (list[str or tuple or Color]): A list of colors.
        top_k (int): Plot the first k bboxes only if set positive.
        thickness (int): Thickness of lines.
        show (bool): Whether to show the image.
        win_name (str): The window name.
        wait_time (int): Value of waitKey param.
        out_file (str, optional): The filename to write the image.
    """
    arg_0 = imread(arg_0)

    if isinstance(arg_1, np.ndarray):
        arg_1 = [arg_1]
    if not isinstance(arg_2, list):
        arg_2 = [arg_2 for _ in range(len(arg_1))]
    arg_2 = [color_val(c) for c in arg_2]
    assert len(arg_1) == len(arg_2)

    for arg_9, arg_10 in enumerate(arg_1):
        arg_10 = arg_10.astype(np.int32)
        if arg_3 <= 0:
            arg_11 = arg_10.shape[0]
        else:
            arg_11 = min(arg_3, arg_10.shape[0])
        for arg_12 in range(arg_11):
            arg_13 = (arg_10[arg_12, 0], arg_10[arg_12, 1])
            arg_14 = (arg_10[arg_12, 2], arg_10[arg_12, 3])
            cv2.rectangle(
                arg_0, arg_13, arg_14, arg_2[arg_9], arg_4=arg_4)

    if arg_5:
        imshow(arg_0, arg_6, arg_7)
    if arg_8 is not None:
        imwrite(arg_0, arg_8)


def Func(arg_0, arg_1=False, arg_2=0, *arg_3, **arg_4):
    """Read an optical flow map.

    Args:
        flow_or_path (ndarray or str): A flow map or filepath.
        quantize (bool): whether to read quantized pair, if set to True,
            remaining args will be passed to :func:`dequantize_flow`.
        concat_axis (int): The axis that dx and dy are concatenated,
            can be either 0 or 1. Ignored if quantize is False.

    Returns:
        ndarray: Optical flow represented as a (h, w, 2) numpy array
    """
    if isinstance(arg_0, np.ndarray):
        if (arg_0.ndim != 3) or (arg_0.shape[-1] != 2):
            raise ValueError('Invalid flow with shape {}'.format(
                arg_0.shape))
        return arg_0
    elif not is_str(arg_0):
        raise TypeError(
            '"flow_or_path" must be a filename or numpy array, not {}'.format(
                type(arg_0)))

    if not arg_1:
        with open(arg_0, 'rb') as f:
            try:
                arg_5 = f.read(4).decode('utf-8')
            except Exception:
                raise IOError('Invalid flow file: {}'.format(arg_0))
            else:
                if arg_5 != 'PIEH':
                    raise IOError(
                        'Invalid flow file: {}, header does not contain PIEH'.
                        format(arg_0))

            arg_6 = np.fromfile(f, np.int32, 1).squeeze()
            arg_7 = np.fromfile(f, np.int32, 1).squeeze()
            arg_8 = np.fromfile(f, np.float32, arg_6 * arg_7 * 2).reshape((arg_7, arg_6, 2))
    else:
        assert arg_2 in [0, 1]
        arg_9 = imread(arg_0, flag='unchanged')
        if arg_9.ndim != 2:
            raise IOError(
                '{} is not a valid quantized flow file, its dimension is {}.'.
                format(arg_0, arg_9.ndim))
        assert arg_9.shape[arg_2] % 2 == 0
        arg_10, arg_11 = np.split(arg_9, 2, axis=arg_2)
        arg_8 = dequantize_flow(arg_10, arg_11, *arg_3, **arg_4)

    return arg_8.astype(np.float32)


def Func(arg_0, arg_1, arg_2=0.02, arg_3=True):
    """Recover from quantized flow.

    Args:
        dx (ndarray): Quantized dx.
        dy (ndarray): Quantized dy.
        max_val (float): Maximum value used when quantizing.
        denorm (bool): Whether to multiply flow values with width/height.

    Returns:
        ndarray: Dequantized flow.
    """
    assert arg_0.shape == arg_1.shape
    assert arg_0.ndim == 2 or (arg_0.ndim == 3 and arg_0.shape[-1] == 1)

    arg_0, arg_1 = [dequantize(d, -arg_2, arg_2, 255) for d in [arg_0, arg_1]]

    if arg_3:
        arg_0 *= arg_0.shape[1]
        arg_1 *= arg_0.shape[0]
    arg_4 = np.dstack((arg_0, arg_1))
    return arg_4


def Func(arg_0, arg_1, arg_2=False, arg_3=None):
    """Load state_dict to a module.

    This method is modified from :meth:`torch.nn.Module.Func`.
    Default value for ``strict`` is set to ``False`` and the message for
    param mismatch will be shown even if strict is False.

    Args:
        module (Module): Module that receives the state_dict.
        state_dict (OrderedDict): Weights.
        strict (bool): whether to strictly enforce that the keys
            in :attr:`state_dict` match the keys returned by this module's
            :meth:`~torch.nn.Module.state_dict` function. Default: ``False``.
        logger (:obj:`logging.Logger`, optional): Logger to log the error
            message. If not specified, print function will be used.
    """
    arg_4 = []
    arg_5 = arg_0.state_dict()
    for arg_6, arg_7 in arg_1.items():
        if arg_6 not in arg_5:
            arg_4.append(arg_6)
            continue
        if isinstance(arg_7, torch.nn.Parameter):
            # backwards compatibility for serialized parameters
            arg_7 = arg_7.data

        try:
            arg_5[arg_6].copy_(arg_7)
        except Exception:
            raise RuntimeError('While copying the parameter named {}, '
                               'whose dimensions in the model are {} and '
                               'whose dimensions in the checkpoint are {}.'
                               .format(arg_6, arg_5[arg_6].size(),
                                       arg_7.size()))
    arg_8 = set(arg_5.keys()) - set(arg_1.keys())

    arg_9 = []
    if arg_4:
        arg_9.append('unexpected key in source state_dict: {}\n'.format(
            ', '.join(arg_4)))
    if arg_8:
        arg_9.append('missing keys in source state_dict: {}\n'.format(
            ', '.join(arg_8)))
    arg_9 = '\n'.join(arg_9)
    if arg_9:
        if arg_2:
            raise RuntimeError(arg_9)
        elif arg_3 is not None:
            arg_3.warn(arg_9)
        else:
            print(arg_9)


def Func(arg_0):
    """Copy a model state_dict to cpu.

    Args:
        state_dict (OrderedDict): Model weights on GPU.

    Returns:
        OrderedDict: Model weights on GPU.
    """
    arg_1 = OrderedDict()
    for arg_2, arg_3 in arg_0.items():
        arg_1[arg_2] = arg_3.cpu()
    return arg_1


def Func(arg_0, arg_1):
        """Init the optimizer.

        Args:
            optimizer (dict or :obj:`~torch.optim.Optimizer`): Either an
                optimizer object or a dict used for constructing the optimizer.

        Returns:
            :obj:`~torch.optim.Optimizer`: An optimizer object.

        Examples:
            >>> optimizer = dict(type='SGD', lr=0.01, momentum=0.9)
            >>> type(runner.Func(optimizer))
            <class 'torch.optim.sgd.SGD'>
        """
        if isinstance(arg_1, dict):
            arg_1 = obj_from_dict(
                arg_1, torch.optim, dict(params=arg_0.model.parameters()))
        elif not isinstance(arg_1, torch.optim.Optimizer):
            raise TypeError(
                'optimizer must be either an Optimizer object or a dict, '
                'but got {}'.format(type(arg_1)))
        return arg_1


def Func(arg_0):
        """Get current learning rates.

        Returns:
            list: Current learning rate of all param groups.
        """
        if arg_0.optimizer is None:
            raise RuntimeError(
                'lr is not applicable because optimizer does not exist.')
        return [arg_1['lr'] for arg_1 in arg_0.optimizer.param_groups]


def Func(arg_0, arg_1, arg_2='NORMAL'):
        """Register a hook into the hook list.

        Args:
            hook (:obj:`Hook`): The hook to be registered.
            priority (int or str or :obj:`Priority`): Hook priority.
                Lower value means higher priority.
        """
        assert isinstance(arg_1, Hook)
        if hasattr(arg_1, 'priority'):
            raise ValueError('"priority" is a reserved attribute for hooks')
        arg_2 = get_priority(arg_2)
        arg_1.priority = arg_2
        # insert the hook to a sorted list
        arg_3 = False
        for arg_4 in range(len(arg_0._hooks) - 1, -1, -1):
            if arg_2 >= arg_0._hooks[arg_4].priority:
                arg_0._hooks.insert(arg_4 + 1, arg_1)
                arg_3 = True
                break
        if not arg_3:
            arg_0._hooks.insert(0, arg_1)


def Func(arg_0,
                                arg_1,
                                arg_2=None,
                                arg_3=None,
                                arg_4=None):
        """Register default hooks for training.

        Default hooks include:

        - LrUpdaterHook
        - OptimizerStepperHook
        - CheckpointSaverHook
        - IterTimerHook
        - LoggerHook(s)
        """
        if arg_2 is None:
            arg_2 = {}
        if arg_3 is None:
            arg_3 = {}
        arg_0.register_lr_hooks(arg_1)
        arg_0.register_hook(arg_0.build_hook(arg_2, OptimizerHook))
        arg_0.register_hook(arg_0.build_hook(arg_3, CheckpointHook))
        arg_0.register_hook(IterTimerHook())
        if arg_4 is not None:
            arg_0.register_logger_hooks(arg_4)


def Func(arg_0, arg_1, arg_2=False, arg_3='',
                  **arg_4):
    """Convert a video with ffmpeg.

    This provides a general api to ffmpeg, the executed command is::

        `ffmpeg -y <pre_options> -i <in_file> <options> <out_file>`

    Options(kwargs) are mapped to ffmpeg commands with the following rules:

    - key=val: "-key val"
    - key=True: "-key"
    - key=False: ""

    Args:
        in_file (str): Input video filename.
        out_file (str): Output video filename.
        pre_options (str): Options appears before "-i <in_file>".
        print_cmd (bool): Whether to print the final ffmpeg command.
    """
    arg_5 = []
    for arg_6, arg_7 in arg_4.items():
        if isinstance(arg_7, bool):
            if arg_7:
                arg_5.append('-{}'.format(arg_6))
        elif arg_6 == 'log_level':
            assert arg_7 in [
                'quiet', 'panic', 'fatal', 'error', 'warning', 'info',
                'verbose', 'debug', 'trace'
            ]
            arg_5.append('-loglevel {}'.format(arg_7))
        else:
            arg_5.append('-{} {}'.format(arg_6, arg_7))
    arg_8 = 'ffmpeg -y {} -i {} {} {}'.format(arg_3, arg_0,
                                            ' '.join(arg_5), arg_1)
    if arg_2:
        print(arg_8)
    subprocess.call(arg_8, shell=True)


def Func(arg_0,
                 arg_1,
                 arg_2=None,
                 arg_3=None,
                 arg_4=False,
                 arg_5='info',
                 arg_6=False,
                 **arg_7):
    """Resize a video.

    Args:
        in_file (str): Input video filename.
        out_file (str): Output video filename.
        size (tuple): Expected size (w, h), eg, (320, 240) or (320, -1).
        ratio (tuple or float): Expected resize ratio, (2, 0.5) means
            (w*2, h*0.5).
        keep_ar (bool): Whether to keep original aspect ratio.
        log_level (str): Logging level of ffmpeg.
        print_cmd (bool): Whether to print the final ffmpeg command.
    """
    if arg_2 is None and arg_3 is None:
        raise ValueError('expected size or ratio must be specified')
    elif arg_2 is not None and arg_3 is not None:
        raise ValueError('size and ratio cannot be specified at the same time')
    arg_8 = {'log_level': arg_5}
    if arg_2:
        if not arg_4:
            arg_8['vf'] = 'scale={}:{}'.format(arg_2[0], arg_2[1])
        else:
            arg_8['vf'] = ('scale=w={}:h={}:force_original_aspect_ratio'
                             '=decrease'.format(arg_2[0], arg_2[1]))
    else:
        if not isinstance(arg_3, tuple):
            arg_3 = (arg_3, arg_3)
        arg_8['vf'] = 'scale="trunc(iw*{}):trunc(ih*{})"'.format(
            arg_3[0], arg_3[1])
    convert_video(arg_0, arg_1, arg_6, **arg_8)


def Func(arg_0, arg_1=arg_2):
    """Load a text file and parse the content as a dict.

    Each line of the text file will be two or more columns splited by
    whitespaces or tabs. The first column will be parsed as dict keys, and
    the following columns will be parsed as dict values.

    Args:
        filename(str): Filename.
        key_type(type): Type of the dict's keys. str is user by default and
            type conversion will be performed if specified.

    Returns:
        dict: The parsed contents.
    """
    arg_3 = {}
    with open(arg_0, 'r') as f:
        for arg_4 in f:
            arg_5 = arg_4.rstrip('\n').split()
            assert len(arg_5) >= 2
            arg_6 = arg_1(arg_5[0])
            arg_7 = arg_5[1:] if len(arg_5) > 2 else arg_5[1]
            arg_3[arg_6] = arg_7
    return arg_3


def Func(arg_0, arg_1, arg_2=1):
    "3x3 convolution with padding"
    return nn.Conv2d(
        arg_0,
        arg_1,
        kernel_size=3,
        padding=arg_2,
        arg_2=arg_2)


def Func(arg_0, arg_1='color'):
    """Read an image.

    Args:
        img_or_path (ndarray or str): Either a numpy array or image path.
            If it is a numpy array (loaded image), then it will be returned
            as is.
        flag (str): Flags specifying the color type of a loaded image,
            candidates are `color`, `grayscale` and `unchanged`.

    Returns:
        ndarray: Loaded image array.
    """
    if isinstance(arg_0, np.ndarray):
        return arg_0
    elif is_str(arg_0):
        arg_1 = Func_flags[arg_1] if is_str(arg_1) else arg_1
        check_file_exist(arg_0,
                         'img file does not exist: {}'.format(arg_0))
        return cv2.Func(arg_0, arg_1)
    else:
        raise TypeError('"img" must be a numpy array or a filename')


def Func(arg_0, arg_1='color'):
    """Read an image from bytes.

    Args:
        content (bytes): Image bytes got from files or other streams.
        flag (str): Same as :func:`imread`.

    Returns:
        ndarray: Loaded image array.
    """
    arg_2 = np.frombuffer(arg_0, np.uint8)
    arg_1 = imread_flags[arg_1] if is_str(arg_1) else arg_1
    arg_3 = cv2.imdecode(arg_2, arg_1)
    return arg_3


def Func(arg_0, arg_1, arg_2=None, arg_3=True):
    """Write image to file

    Args:
        img (ndarray): Image array to be written.
        file_path (str): Image file path.
        params (None or list): Same as opencv's :func:`Func` interface.
        auto_mkdir (bool): If the parent folder of `file_path` does not exist,
            whether to create it automatically.

    Returns:
        bool: Successful or not.
    """
    if arg_3:
        arg_4 = osp.abspath(osp.dirname(arg_1))
        mkdir_or_exist(arg_4)
    return cv2.Func(arg_1, arg_0, arg_2)


def Func(arg_0, arg_1=False):
    """Convert a BGR image to grayscale image.

    Args:
        img (ndarray): The input image.
        keepdim (bool): If False (by default), then return the grayscale image
            with 2 dims, otherwise 3 dims.

    Returns:
        ndarray: The converted grayscale image.
    """
    arg_2 = cv2.cvtColor(arg_0, cv2.COLOR_BGR2GRAY)
    if arg_1:
        arg_2 = arg_2[..., None]
    return arg_2


def Func(arg_0):
    """Convert a grayscale image to BGR image.

    Args:
        img (ndarray or str): The input image.

    Returns:
        ndarray: The converted BGR image.
    """
    arg_0 = arg_0[..., None] if arg_0.ndim == 2 else arg_0
    arg_1 = cv2.cvtColor(arg_0, cv2.COLOR_GRAY2BGR)
    return arg_1


def Func(arg_0, arg_1, arg_2=None):
    """Cast elements of an iterable object into some type.

    Args:
        inputs (Iterable): The input object.
        dst_type (type): Destination type.
        return_type (type, optional): If specified, the output object will be
            converted to this type, otherwise an iterator.

    Returns:
        iterator or specified type: The converted object.
    """
    if not isinstance(arg_0, collections_abc.Iterable):
        raise TypeError('inputs must be an iterable object')
    if not isinstance(arg_1, type):
        raise TypeError('"dst_type" must be a valid type')

    arg_3 = six.moves.map(arg_1, arg_0)

    if arg_2 is None:
        return arg_3
    else:
        return arg_2(arg_3)


def Func(arg_0, arg_1, arg_2=None):
    """Check whether it is a sequence of some type.

    Args:
        seq (Sequence): The sequence to be checked.
        expected_type (type): Expected type of sequence items.
        seq_type (type, optional): Expected sequence type.

    Returns:
        bool: Whether the sequence is valid.
    """
    if arg_2 is None:
        arg_3 = collections_abc.Sequence
    else:
        assert isinstance(arg_2, type)
        arg_3 = arg_2
    if not isinstance(arg_0, arg_3):
        return False
    for arg_4 in arg_0:
        if not isinstance(arg_4, arg_1):
            return False
    return True


def Func(arg_0, arg_1):
    """Slice a list into several sub lists by a list of given length.

    Args:
        in_list (list): The list to be sliced.
        lens(int or list): The expected length of each out list.

    Returns:
        list: A list of sliced list.
    """
    if not isinstance(arg_1, list):
        raise TypeError('"indices" must be a list of integers')
    elif sum(arg_1) != len(arg_0):
        raise ValueError(
            'sum of lens and list length does not match: {} != {}'.format(
                sum(arg_1), len(arg_0)))
    arg_2 = []
    arg_3 = 0
    for arg_4 in range(len(arg_1)):
        arg_2.append(arg_0[arg_3:arg_3 + arg_1[arg_4]])
        arg_3 += arg_1[arg_4]
    return arg_2


def Func(arg_0, arg_1=0):
        """Average latest n values or all values"""
        assert arg_1 >= 0
        for arg_2 in arg_0.val_history:
            arg_3 = np.array(arg_0.val_history[arg_2][-arg_1:])
            arg_4 = np.array(arg_0.n_history[arg_2][-arg_1:])
            arg_5 = np.sum(arg_3 * arg_4) / np.sum(arg_4)
            arg_0.output[arg_2] = arg_5
        arg_0.ready = True


def Func(arg_0, arg_1, arg_2=None):
    """Scatters tensor across multiple GPUs.
    """
    if arg_2 is None:
        arg_2 = [None] * len(arg_1)

    if isinstance(arg_0, list):
        arg_3 = (len(arg_0) - 1) // len(arg_1) + 1
        arg_4 = [
            Func(arg_0[i], [arg_1[i // arg_3]],
                    [arg_2[i // arg_3]]) for i in range(len(arg_0))
        ]
        return arg_4
    elif isinstance(arg_0, torch.Tensor):
        arg_5 = arg_0.contiguous()
        # TODO: copy to a pinned buffer first (if copying from CPU)
        arg_6 = arg_2[0] if arg_5.numel() > 0 else None
        with torch.cuda.device(arg_1[0]), torch.cuda.stream(arg_6):
            arg_5 = arg_5.cuda(arg_1[0], non_blocking=True)
        return arg_5
    else:
        raise Exception('Unknown type {}.'.format(type(arg_0)))


def Func(arg_0):
    """Add check points in a single line.

    This method is suitable for running a task on a list of items. A timer will
    be registered when the method is called for the first time.

    :Example:

    >>> import time
    >>> import mmcv
    >>> for i in range(1, 6):
    >>>     # simulate a code block
    >>>     time.sleep(i)
    >>>     mmcv.Func('task1')
    2.000
    3.000
    4.000
    5.000

    Args:
        timer_id (str): Timer identifier.
    """
    if arg_0 not in arg_1:
        arg_1[arg_0] = Timer()
        return 0
    else:
        return arg_1[arg_0].since_last_check()


def Func(arg_0):
        """Time since the last checking.

        Either :func:`since_start` or :func:`Func` is a checking
        operation.

        Returns (float): Time in seconds.
        """
        if not arg_0._is_running:
            raise TimerError('timer is not running')
        arg_1 = time() - arg_0._t_last
        arg_0._t_last = time()
        return arg_1


def Func(arg_0, arg_1='', arg_2=0):
    """Show optical flow.

    Args:
        flow (ndarray or str): The optical flow to be displayed.
        win_name (str): The window name.
        wait_time (int): Value of waitKey param.
    """
    arg_0 = flowread(arg_0)
    arg_3 = flow2rgb(arg_0)
    imshow(rgb2bgr(arg_3), arg_1, arg_2)


def Func(arg_0, arg_1=None, arg_2=1e6):
    """Convert flow map to RGB image.

    Args:
        flow (ndarray): Array of optical flow.
        color_wheel (ndarray or None): Color wheel used to map flow field to
            RGB colorspace. Default color wheel will be used if not specified.
        unknown_thr (str): Values above this threshold will be marked as
            unknown and thus ignored.

    Returns:
        ndarray: RGB image that can be visualized.
    """
    assert arg_0.ndim == 3 and arg_0.shape[-1] == 2
    if arg_1 is None:
        arg_1 = make_color_wheel()
    assert arg_1.ndim == 2 and arg_1.shape[1] == 3
    arg_3 = arg_1.shape[0]

    arg_4 = arg_0[:, :, 0].copy()
    arg_5 = arg_0[:, :, 1].copy()

    arg_6 = (np.isnan(arg_4) | np.isnan(arg_5) | (np.abs(arg_4) > arg_2) |
                   (np.abs(arg_5) > arg_2))
    arg_4[arg_6] = 0
    arg_5[arg_6] = 0

    arg_7 = np.sqrt(arg_4**2 + arg_5**2)
    if np.any(arg_7 > np.finfo(float).eps):
        arg_8 = np.max(arg_7)
        arg_4 /= arg_8
        arg_5 /= arg_8

    [arg_9, arg_10] = arg_4.shape

    arg_7 = np.sqrt(arg_4**2 + arg_5**2)
    arg_11 = np.arctan2(-arg_5, -arg_4) / np.pi

    arg_12 = (arg_11 + 1) / 2 * (arg_3 - 1)
    arg_13 = np.floor(arg_12).astype(int)
    arg_14 = (arg_13 + 1) % arg_3
    arg_10 = (arg_12 - arg_13.astype(np.float32))[..., None]
    arg_15 = (
        1 - arg_10) * arg_1[arg_13, :] + arg_10 * arg_1[arg_14, :]
    arg_16 = arg_7 <= 1
    arg_15[arg_16] = 1 - arg_7[arg_16, None] * (1 - arg_15[arg_16])
    arg_15[np.logical_not(arg_16)] *= 0.75

    arg_15[arg_6, :] = 0

    return arg_15


def Func(arg_0=None):
    """Build a color wheel.

    Args:
        bins(list or tuple, optional): Specify the number of bins for each
            color range, corresponding to six ranges: red -> yellow,
            yellow -> green, green -> cyan, cyan -> blue, blue -> magenta,
            magenta -> red. [15, 6, 4, 11, 13, 6] is used for default
            (see Middlebury).

    Returns:
        ndarray: Color wheel of shape (total_bins, 3).
    """
    if arg_0 is None:
        arg_0 = [15, 6, 4, 11, 13, 6]
    assert len(arg_0) == 6

    arg_1, arg_2, arg_3, arg_4, arg_5, arg_6 = tuple(arg_0)

    arg_7 = [1, np.arange(arg_1) / arg_1, 0]
    arg_8 = [1 - np.arange(arg_2) / arg_2, 1, 0]
    arg_9 = [0, 1, np.arange(arg_3) / arg_3]
    arg_10 = [0, 1 - np.arange(arg_4) / arg_4, 1]
    arg_11 = [np.arange(arg_5) / arg_5, 0, 1]
    arg_12 = [1, 0, 1 - np.arange(arg_6) / arg_6]

    arg_13 = arg_1 + arg_2 + arg_3 + arg_4 + arg_5 + arg_6

    arg_14 = np.zeros((3, arg_13), dtype=np.float32)

    arg_15 = 0
    for arg_16, arg_17 in enumerate([arg_7, arg_8, arg_9, arg_10, arg_11, arg_12]):
        for arg_18 in range(3):
            arg_14[arg_18, arg_15:arg_15 + arg_0[arg_16]] = arg_17[arg_18]
        arg_15 += arg_0[arg_16]

    return arg_14.T


def Func(arg_0, arg_1, arg_2=0):
    """Scatter inputs to target gpus.

    The only difference from original :func:`Func` is to add support for
    :type:`~mmcv.parallel.DataContainer`.
    """

    def arg_6(arg_3):
        if isinstance(arg_3, torch.Tensor):
            return OrigScatter.apply(arg_1, None, arg_2, arg_3)
        if isinstance(arg_3, DataContainer):
            if arg_3.cpu_only:
                return arg_3.data
            else:
                return Scatter.forward(arg_1, arg_3.data)
        if isinstance(arg_3, tuple) and len(arg_3) > 0:
            return list(zip(*map(arg_6, arg_3)))
        if isinstance(arg_3, list) and len(arg_3) > 0:
            arg_4 = list(map(list, zip(*map(arg_6, arg_3))))
            return arg_4
        if isinstance(arg_3, dict) and len(arg_3) > 0:
            arg_4 = list(map(type(arg_3), zip(*map(arg_6, arg_3.items()))))
            return arg_4
        return [arg_3 for arg_5 in arg_1]

    # After Func_map is called, a Func_map cell will exist. This cell
    # has a reference to the actual function Func_map, which has references
    # to a closure that has a reference to the Func_map cell (because the
    # fn is recursive). To avoid this reference cycle, we set the function to
    # None, clearing the cell
    try:
        return arg_6(arg_0)
    finally:
        arg_6 = None


def Func(arg_0, arg_1, arg_2, arg_3=0):
    """Scatter with support for kwargs dictionary"""
    arg_0 = scatter(arg_0, arg_2, arg_3) if arg_0 else []
    arg_1 = scatter(arg_1, arg_2, arg_3) if arg_1 else []
    if len(arg_0) < len(arg_1):
        arg_0.extend([() for arg_4 in range(len(arg_1) - len(arg_0))])
    elif len(arg_1) < len(arg_0):
        arg_1.extend([{} for arg_4 in range(len(arg_0) - len(arg_1))])
    arg_0 = tuple(arg_0)
    arg_1 = tuple(arg_1)
    return arg_0, arg_1


def Func(arg_0, arg_1, arg_2):
    """Decide whether a particular character needs to be quoted.

    The 'quotetabs' flag indicates whether embedded tabs and spaces should be
    quoted.  Note that line-ending tabs and spaces are always encoded, as per
    RFC 1521.
    """
    if arg_0 in ' \t':
        return arg_1
    # if header, we have to escape _ because _ is used to escape space
    if arg_0 == '_':
        return arg_2
    return arg_0 == ESCAPE or not (' ' <= arg_0 <= '~')


def Func(arg_0):
    """Quote a single character."""
    arg_1 = ord(arg_0)
    return ESCAPE + HEX[arg_1//16] + HEX[arg_1%16]


def Func(arg_0, arg_1, arg_2, arg_3 = 0):
    """Read 'input', apply quoted-printable encoding, and write to 'output'.

    'input' and 'output' are files with readline() and write() methods.
    The 'quotetabs' flag indicates whether embedded tabs and spaces should be
    quoted.  Note that line-ending tabs and spaces are always Funcd, as per
    RFC 1521.
    The 'header' flag indicates whether we are encoding spaces as _ as per
    RFC 1522.
    """

    if b2a_qp is not None:
        arg_4 = arg_0.read()
        arg_5 = b2a_qp(arg_4, arg_2 = arg_2, arg_3 = arg_3)
        arg_1.write(arg_5)
        return

    def write(arg_6, arg_1=arg_1, arg_7='\n'):
        # RFC 1521 requires that the line ending in a space or tab must have
        # that trailing character Funcd.
        if arg_6 and arg_6[-1:] in ' \t':
            arg_1.write(arg_6[:-1] + quote(arg_6[-1]) + arg_7)
        elif arg_6 == '.':
            arg_1.write(quote(arg_6) + arg_7)
        else:
            arg_1.write(arg_6 + arg_7)

    arg_8 = None
    while 1:
        arg_9 = arg_0.readline()
        if not arg_9:
            break
        arg_10 = []
        # Strip off any readline induced trailing newline
        arg_11 = ''
        if arg_9[-1:] == '\n':
            arg_9 = arg_9[:-1]
            arg_11 = '\n'
        # Calculate the un-length-limited Funcd line
        for arg_12 in arg_9:
            if needsquoting(arg_12, arg_2, arg_3):
                arg_12 = quote(arg_12)
            if arg_3 and arg_12 == ' ':
                arg_10.append('_')
            else:
                arg_10.append(arg_12)
        # First, write out the previous line
        if arg_8 is not None:
            write(arg_8)
        # Now see if we need any soft line breaks because of RFC-imposed
        # length limitations.  Then do the thisline->prevline dance.
        arg_13 = EMPTYSTRING.join(arg_10)
        while len(arg_13) > MAXLINESIZE:
            # Don't forget to include the soft line break `=' sign in the
            # length calculation!
            write(arg_13[:MAXLINESIZE-1], arg_7='=\n')
            arg_13 = arg_13[MAXLINESIZE-1:]
        # Write out the current line
        arg_8 = arg_13
    # Write out the last line, without a trailing newline
    if arg_8 is not None:
        write(arg_8, arg_7=arg_11)


def Func(arg_0):
    """Get the integer value of a hexadecimal number."""
    arg_1 = 0
    for arg_2 in arg_0:
        if '0' <= arg_2 <= '9':
            arg_3 = ord('0')
        elif 'a' <= arg_2 <= 'f':
            arg_3 = ord('a')-10
        elif 'A' <= arg_2 <= 'F':
            arg_3 = ord('A')-10
        else:
            break
        arg_1 = arg_1*16 + (ord(arg_2) - arg_3)
    return arg_1


def Func(arg_0, arg_1=None):
    """Encode a string using Base64.

    s is the string to encode.  Optional altchars must be a string of at least
    length 2 (additional characters are ignored) which specifies an
    alternative alphabet for the '+' and '/' characters.  This allows an
    application to e.g. generate url or filesystem safe Base64 strings.

    The encoded string is returned.
    """
    # Strip off the trailing newline
    arg_2 = binascii.b2a_base64(arg_0)[:-1]
    if arg_1 is not None:
        return arg_2.translate(string.maketrans(b'+/', arg_1[:2]))
    return arg_2


def Func(arg_0, arg_1=None):
    """Decode a Base64 encoded string.

    s is the string to decode.  Optional altchars must be a string of at least
    length 2 (additional characters are ignored) which specifies the
    alternative alphabet used instead of the '+' and '/' characters.

    The decoded string is returned.  A TypeError is raised if s is
    incorrectly padded.  Characters that are neither in the normal base-64
    alphabet nor the alternative alphabet are discarded prior to the padding
    check.
    """
    if arg_1 is not None:
        arg_0 = arg_0.translate(string.maketrans(arg_1[:2], '+/'))
    try:
        return binascii.a2b_base64(arg_0)
    except binascii.Error, msg:
        # Transform this exception for consistency
        raise TypeError(msg)


def Func(arg_0):
    """Encode a string using Base32.

    s is the string to encode.  The encoded string is returned.
    """
    arg_1 = []
    arg_2, arg_3 = divmod(len(arg_0), 5)
    # Pad the last quantum with zero bits if necessary
    if arg_3:
        arg_0 += ('\0' * (5 - arg_3))
        arg_2 += 1
    for arg_4 in range(arg_2):
        # c1 and c2 are 16 bits wide, c3 is 8 bits wide.  The intent of this
        # code is to process the 40 bits in units of 5 bits.  So we take the 1
        # leftover bit of c1 and tack it onto c2.  Then we take the 2 leftover
        # bits of c2 and tack them onto c3.  The shifts and masks are intended
        # to give us values of exactly 5 bits in width.
        arg_5, arg_6, arg_7 = struct.unpack('!HHB', arg_0[arg_4*5:(arg_4+1)*5])
        arg_6 += (arg_5 & 1) << 16 # 17 bits wide
        arg_7 += (arg_6 & 3) << 8  # 10 bits wide
        arg_1.extend([_b32tab[arg_5 >> 11],         # bits 1 - 5
                      _b32tab[(arg_5 >> 6) & 0x1f], # bits 6 - 10
                      _b32tab[(arg_5 >> 1) & 0x1f], # bits 11 - 15
                      _b32tab[arg_6 >> 12],         # bits 16 - 20 (1 - 5)
                      _b32tab[(arg_6 >> 7) & 0x1f], # bits 21 - 25 (6 - 10)
                      _b32tab[(arg_6 >> 2) & 0x1f], # bits 26 - 30 (11 - 15)
                      _b32tab[arg_7 >> 5],          # bits 31 - 35 (1 - 5)
                      _b32tab[arg_7 & 0x1f],        # bits 36 - 40 (1 - 5)
                      ])
    arg_8 = EMPTYSTRING.join(arg_1)
    # Adjust for any leftover partial quanta
    if arg_3 == 1:
        return arg_8[:-6] + '======'
    elif arg_3 == 2:
        return arg_8[:-4] + '===='
    elif arg_3 == 3:
        return arg_8[:-3] + '==='
    elif arg_3 == 4:
        return arg_8[:-1] + '='
    return arg_8


def Func(arg_0, arg_1=False, arg_2=None):
    """Decode a Base32 encoded string.

    s is the string to decode.  Optional casefold is a flag specifying whether
    a lowercase alphabet is acceptable as input.  For security purposes, the
    default is False.

    RFC 3548 allows for optional mapping of the digit 0 (zero) to the letter O
    (oh), and for optional mapping of the digit 1 (one) to either the letter I
    (eye) or letter L (el).  The optional argument map01 when not None,
    specifies which letter the digit 1 should be mapped to (when map01 is not
    None, the digit 0 is always mapped to the letter O).  For security
    purposes the default is None, so that 0 and 1 are not allowed in the
    input.

    The decoded string is returned.  A TypeError is raised if s were
    incorrectly padded or if there are non-alphabet characters present in the
    string.
    """
    arg_3, arg_4 = divmod(len(arg_0), 8)
    if arg_4:
        raise TypeError('Incorrect padding')
    # Handle section 2.4 zero and one mapping.  The flag map01 will be either
    # False, or the character to map the digit 1 (one) to.  It should be
    # either L (el) or I (eye).
    if arg_2:
        arg_0 = arg_0.translate(string.maketrans(b'01', b'O' + arg_2))
    if arg_1:
        arg_0 = arg_0.upper()
    # Strip off pad characters from the right.  We need to count the pad
    # characters because this will tell us how many null bytes to remove from
    # the end of the decoded string.
    arg_5 = 0
    arg_6 = re.search('(?P<pad>[=]*)$', arg_0)
    if arg_6:
        arg_5 = len(arg_6.group('pad'))
        if arg_5 > 0:
            arg_0 = arg_0[:-arg_5]
    # Now decode the full quanta
    arg_7 = []
    arg_8 = 0
    arg_9 = 35
    for arg_10 in arg_0:
        arg_11 = _b32rev.get(arg_10)
        if arg_11 is None:
            raise TypeError('Non-base32 digit found')
        arg_8 += _b32rev[arg_10] << arg_9
        arg_9 -= 5
        if arg_9 < 0:
            arg_7.append(binascii.unhexlify('%010x' % arg_8))
            arg_8 = 0
            arg_9 = 35
    # Process the last, partial quanta
    arg_12 = binascii.unhexlify('%010x' % arg_8)
    if arg_5 == 0:
        arg_12 = ''                       # No characters
    elif arg_5 == 1:
        arg_12 = arg_12[:-1]
    elif arg_5 == 3:
        arg_12 = arg_12[:-2]
    elif arg_5 == 4:
        arg_12 = arg_12[:-3]
    elif arg_5 == 6:
        arg_12 = arg_12[:-4]
    else:
        raise TypeError('Incorrect padding')
    arg_7.append(arg_12)
    return EMPTYSTRING.join(arg_7)


def Func(arg_0, arg_1=False):
    """Decode a Base16 encoded string.

    s is the string to decode.  Optional casefold is a flag specifying whether
    a lowercase alphabet is acceptable as input.  For security purposes, the
    default is False.

    The decoded string is returned.  A TypeError is raised if s is
    incorrectly padded or if there are non-alphabet characters present in the
    string.
    """
    if arg_1:
        arg_0 = arg_0.upper()
    if re.search('[^0-9A-F]', arg_0):
        raise TypeError('Non-base16 digit found')
    return binascii.unhexlify(arg_0)


def Func(arg_0, arg_1):
    """Encode a file."""
    while True:
        arg_2 = arg_0.read(MAXBINSIZE)
        if not arg_2:
            break
        while len(arg_2) < MAXBINSIZE:
            arg_3 = arg_0.read(MAXBINSIZE-len(arg_2))
            if not arg_3:
                break
            arg_2 += arg_3
        arg_4 = binascii.b2a_base64(arg_2)
        arg_1.write(arg_4)


def Func(arg_0):
        """
        Returns a zero-length range located just after the Func of this range.
        """
        return Range(arg_0.source_buffer, arg_0.Func_pos, arg_0.Func_pos,
                     expanded_from=arg_0.expanded_from)