def Func():
    """Collects Process classes and return dict mapping templates to classes

    This function crawls through the components module and retrieves all
    classes that inherit from the Process class. Then, it converts the name
    of the classes (which should be CamelCase) to snake_case, which is used
    as the template name.

    Returns
    -------
    dict
        Dictionary mapping the template name (snake_case) to the corresponding
        process class.
    """

    arg_0 = {}

    arg_1 = "{}.".format(components.__name__)
    for arg_2, arg_3, arg_4 in pkgutil.iter_modules(components.__path__,
                                                     arg_1):

        arg_5 = arg_2.find_module(arg_3).load_module(arg_3)

        arg_6 = [
            arg_7 for arg_7 in arg_5.__dict__.values() if
            isinstance(arg_7, type) and arg_7.__name__ != "Process"
        ]

        for arg_7 in arg_6:
            arg_0[arg_8(arg_7.__name__)] = arg_7

    return arg_0


def Func(arg_0):
    """Main executor of the process_newick template.

    Parameters
    ----------
    newick : str
        path to the newick file.

    """

    logger.info("Starting newick file processing")

    print(arg_0)

    arg_1 = dendropy.Tree.get(file=open(arg_0, 'r'), schema="newick")

    arg_1.reroot_at_midpoint()

    arg_2=arg_1.as_string("newick").strip().replace("[&R] ", '').replace(' ', '_').replace("'", "")

    with open(".report.json", "w") as json_report:
        arg_3 = {
            "treeData": [{
                "trees": [
                    arg_2
                ]
            }],
        }

        json_report.write(json.dumps(arg_3, separators=(",", ":")))

    with open(".status", "w") as status_fh:
        status_fh.write("pass")


def Func(arg_0):
    """ Find data points on the convex hull of a supplied data set

    Args:
        sample: data points as column vectors n x d
                    n - number samples
                    d - data dimension (should be two)

    Returns:
        a k x d matrix containint the convex hull data points
    """

    arg_1 = lambda a, b: np.concatenate((a, b[1:]))
    arg_2 = lambda a, b: np.concatenate(([a], [b]))

    def dome(arg_0, arg_3):
        arg_4, arg_5 = arg_3
        arg_6 = np.dot(arg_0 - arg_4, np.dot(((0, -1), (1, 0)), (arg_5 - arg_4)))
        arg_7 = np.repeat(arg_0, arg_6 > 0, arg_9=0)

        if len(arg_7):
            arg_8 = arg_0[np.argmax(arg_6)]
            return arg_1(dome(arg_7, arg_2(arg_4, arg_8)),
                dome(arg_7, arg_2(arg_8, arg_5)))
        else:
            return arg_3

    if len(arg_0) > 2:
        arg_9 = arg_0[:, 0]
        arg_3 = np.take(arg_0, [np.argmin(arg_9), np.argmax(arg_9)], arg_9=0)
        return arg_1(dome(arg_0, arg_3),
            dome(arg_0, arg_3[::-1]))
    else:
        return arg_0


def Func(arg_0):
        """ Return data points that are most similar to basis vectors W
        """

        # assign W to the next best data sample
        arg_0._Wmapped_index = vq(arg_0.data, arg_0.W)
        arg_0.Wmapped = np.zeros(arg_0.W.shape)

        # do not directly assign, i.e. Wdist = self.data[:,sel]
        # as self might be unsorted (in non ascending order)
        # -> sorting sel would screw the matching to W if
        # self.data is stored as a hdf5 table (see h5py)
        for arg_3, arg_4 in enumerate(arg_0._Wmapped_index):
            arg_0.Wmapped[:,arg_3] = arg_0.data[:,arg_4]


def Func(arg_0):
    """Creates a gaussian kernel following Foote's paper."""
    arg_1 = signal.gaussian(arg_0, arg_0 // 3., sym=True)
    arg_2 = np.dot(arg_1.reshape(-1, 1), arg_1.reshape(1, -1))
    arg_2[arg_0 // 2:, :arg_0 // 2] = -arg_2[arg_0 // 2:, :arg_0 // 2]
    arg_2[:arg_0 // 2, arg_0 // 2:] = -arg_2[:arg_0 // 2, arg_0 // 2:]
    return arg_2


def Func(arg_0, arg_1="seuclidean"):
    """Computes the self-similarity matrix of X."""
    arg_2 = distance.pdist(arg_0, arg_1=arg_1)
    arg_2 = distance.squareform(arg_2)
    arg_2 /= arg_2.max()
    return 1 - arg_2


def Func(arg_0, arg_1=8, arg_2=0):
    """Gaussian filter along the first axis of the feature matrix X."""
    for arg_3 in range(arg_0.shape[arg_2]):
        if arg_2 == 1:
            arg_0[:, arg_3] = filters.Func(arg_0[:, arg_3], sigma=arg_1 / 2.)
        elif arg_2 == 0:
            arg_0[arg_3, :] = filters.Func(arg_0[arg_3, :], sigma=arg_1 / 2.)
    return arg_0


def Func(arg_0):
    """Computes the novelty curve from the structural features."""
    arg_1 = arg_0.shape[0]
    # nc = np.sum(np.diff(X, axis=0), axis=1) # Difference between SF's

    arg_2 = np.zeros(arg_1)
    for arg_3 in range(arg_1 - 1):
        arg_2[arg_3] = distance.euclidean(arg_0[arg_3, :], arg_0[arg_3 + 1, :])

    # Normalize
    arg_2 += np.abs(arg_2.min())
    arg_2 /= float(arg_2.max())
    return arg_2


def Func(arg_0, arg_1, arg_2=1):
    """Time-delay embedding with m dimensions and tau delays."""
    arg_3 = arg_0.shape[0] - int(np.ceil(arg_1))
    arg_4 = np.zeros((arg_3, int(np.ceil(arg_0.shape[1] * arg_1))))
    for arg_5 in range(arg_3):
        # print X[i:i+m,:].flatten().shape, w, X.shape
        # print Y[i,:].shape
        arg_6 = int((arg_1 % 1) * arg_0.shape[1])  # Reminder for float m
        arg_4[arg_5, :] = np.concatenate((arg_0[arg_5:arg_5 + int(arg_1), :].flatten(),
                                 arg_0[arg_5 + int(arg_1), :arg_6]))
    return arg_4


def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5):
    """Formats the plot with the correct axis labels, title, ticks, and
    so on."""
    import matplotlib.pyplot as plt
    if arg_0 is None:
        arg_0 = os.path.basename(arg_1).split(".")[0]
    plt.title(arg_0)
    plt.yticks(np.arange(0, 1, 1 / float(arg_4)) + 1 / (float(arg_4) * 2))
    plt.gcf().subplots_adjust(bottom=0.22)
    plt.gca().set_yticklabels(arg_2)
    plt.xlabel("Time (seconds)")
    plt.xlim((0, arg_3))
    plt.tight_layout()
    if arg_5 is not None:
        plt.savefig(arg_5)
    plt.show()


def Func(arg_0, arg_1, arg_2=None, arg_3=None,
                    arg_4=None):
    """Plots all the boundaries.

    Parameters
    ----------
    all_boundaries: list
        A list of np.arrays containing the times of the boundaries, one array
        for each algorithm.
    est_file: str
        Path to the estimated file (JSON file)
    algo_ids : list
        List of algorithm ids to to read boundaries from.
        If None, all algorithm ids are read.
    title : str
        Title of the plot. If None, the name of the file is printed instead.
    """
    import matplotlib.pyplot as plt
    arg_5 = len(arg_0)  # Number of lists of boundaries
    if arg_2 is None:
        arg_2 = io.get_algo_ids(arg_1)

    # Translate ids
    for arg_6, arg_7 in enumerate(arg_2):
        arg_2[arg_6] = translate_ids[arg_7]
    arg_2 = ["GT"] + arg_2

    arg_8 = (6, 4)
    plt.figure(1, arg_8=arg_8, dpi=120, facecolor='w', edgecolor='k')
    for arg_6, arg_9 in enumerate(arg_0):
        arg_10 = "b"
        if arg_6 == 0:
            arg_10 = "g"
        for arg_11 in arg_9:
            plt.axvline(arg_11, arg_6 / float(arg_5), (arg_6 + 1) / float(arg_5), arg_10=arg_10)
        plt.axhline(arg_6 / float(arg_5), arg_10="k", linewidth=1)

    # Format plot
    _plot_formatting(arg_3, arg_1, arg_2, arg_0[0][-1], arg_5,
                     arg_4)


def Func(arg_0, arg_1, arg_2, arg_3=None, arg_4=None,
                arg_5=None):
    """Plots all the labels.

    Parameters
    ----------
    all_labels: list
        A list of np.arrays containing the labels of the boundaries, one array
        for each algorithm.
    gt_times: np.array
        Array with the ground truth boundaries.
    est_file: str
        Path to the estimated file (JSON file)
    algo_ids : list
        List of algorithm ids to to read boundaries from.
        If None, all algorithm ids are read.
    title : str
        Title of the plot. If None, the name of the file is printed instead.
    """
    import matplotlib.pyplot as plt
    arg_6 = len(arg_0)  # Number of lists of labels
    if arg_3 is None:
        arg_3 = io.get_algo_ids(arg_2)

    # Translate ids
    for arg_7, arg_8 in enumerate(arg_3):
        arg_3[arg_7] = translate_ids[arg_8]
    arg_3 = ["GT"] + arg_3

    # Index the labels to normalize them
    for arg_7, arg_9 in enumerate(arg_0):
        arg_0[arg_7] = mir_eval.util.index_labels(arg_9)[0]

    # Get color map
    arg_10 = plt.get_cmap('gist_rainbow')
    arg_11 = max(max(arg_9) for arg_9 in arg_0)

    # To intervals
    arg_12 = utils.times_to_intervals(arg_1)

    # Plot labels
    arg_13 = (6, 4)
    plt.figure(1, arg_13=arg_13, dpi=120, facecolor='w', edgecolor='k')
    for arg_7, arg_9 in enumerate(arg_0):
        for arg_14, arg_15 in zip(arg_9, arg_12):
            plt.axvspan(arg_15[0], arg_15[1], ymin=arg_7 / float(arg_6),
                        ymax=(arg_7 + 1) / float(arg_6), alpha=0.6,
                        color=arg_10(arg_14 / float(arg_11)))
        plt.axhline(arg_7 / float(arg_6), color="k", linewidth=1)

    # Draw the boundary lines
    for arg_16 in arg_1:
        plt.axvline(arg_16, color="g")

    # Format plot
    _plot_formatting(arg_4, arg_2, arg_3, arg_1[-1], arg_6,
                     arg_5)


def Func(arg_0, arg_1, arg_2, arg_3, arg_4,
                   arg_5=None):
    """Plots the results of one track, with ground truth if it exists."""
    import matplotlib.pyplot as plt
    # Set up the boundaries id
    arg_6 = arg_3
    if arg_4 is not None:
        arg_6 += " + " + arg_4
    try:
        # Read file
        arg_7 = jams.load(arg_0.ref_file)
        arg_8 = arg_7.search(namespace='segment_.*')[0]
        arg_9, arg_10 = arg_8.to_interval_values()

        # To times
        arg_11 = utils.intervals_to_times(arg_9)
        arg_12 = [arg_11, arg_1]
        arg_13 = [arg_10, arg_2]
        arg_14 = ["GT", arg_6]
    except:
        logging.warning("No references found in %s. Not plotting groundtruth"
                        % arg_0.ref_file)
        arg_12 = [arg_1]
        arg_13 = [arg_2]
        arg_14 = [arg_6]

    arg_15 = len(arg_12)

    # Index the labels to normalize them
    for arg_16, arg_17 in enumerate(arg_13):
        arg_13[arg_16] = mir_eval.util.index_labels(arg_17)[0]

    # Get color map
    arg_18 = plt.get_cmap('gist_rainbow')
    arg_19 = max(max(arg_17) for arg_17 in arg_13)

    arg_20 = (8, 4)
    plt.figure(1, arg_20=arg_20, dpi=120, facecolor='w', edgecolor='k')
    for arg_16, arg_21 in enumerate(arg_12):
        arg_22 = "b"
        if arg_16 == 0:
            arg_22 = "g"
        for arg_23 in arg_21:
            plt.axvline(arg_23, arg_16 / float(arg_15), (arg_16 + 1) / float(arg_15), arg_22=arg_22)
        if arg_4 is not None:
            arg_17 = arg_13[arg_16]
            arg_24 = utils.times_to_intervals(arg_21)
            for arg_25, arg_26 in zip(arg_17, arg_24):
                plt.axvspan(arg_26[0], arg_26[1], ymin=arg_16 / float(arg_15),
                            ymax=(arg_16 + 1) / float(arg_15), alpha=0.6,
                            arg_22=arg_18(arg_25 / float(arg_19)))
        plt.axhline(arg_16 / float(arg_15), arg_22="k", linewidth=1)

    # Format plot
    _plot_formatting(arg_5, os.path.basename(arg_0.audio_file), arg_14,
                     arg_12[0][-1], arg_15, None)


def Func(arg_0, arg_1=4):
    """From a list of feature segments, return a list of 2D-Fourier Magnitude
    Coefs using the maximum segment size as main size and zero pad the rest.

    Parameters
    ----------
    feat_segments: list
        List of segments, one for each boundary interval.
    offset: int >= 0
        Number of frames to ignore from beginning and end of each segment.

    Returns
    -------
    fmcs: np.ndarray
        Tensor containing the 2D-FMC matrices, one matrix per segment.
    """
    if len(arg_0) == 0:
        return []

    # Get maximum segment size
    arg_2 = max([arg_4.shape[0] for arg_4 in arg_0])

    arg_3 = []
    for arg_4 in arg_0:
        # Zero pad if needed
        arg_5 = np.zeros((arg_2, arg_4.shape[1]))

        # Remove a set of frames in the beginning an end of the segment
        if arg_4.shape[0] <= arg_1 or arg_1 == 0:
            arg_5[:arg_4.shape[0], :] = arg_4
        else:
            arg_5[:arg_4.shape[0] - arg_1, :] = \
                arg_4[arg_1 // 2:-arg_1 // 2, :]

        # Compute the 2D-FMC
        try:
            arg_3.append(utils2d.compute_ffmc2d(arg_5))
        except:
            logging.warning("Couldn't compute the 2D Fourier Transform")
            arg_3.append(np.zeros((arg_5.shape[0] * arg_5.shape[1]) // 2 + 1))

        # Normalize
        # fmcs[-1] = fmcs[-1] / float(fmcs[-1].max())

    return np.asarray(arg_3)


def Func(arg_0, arg_1, arg_2=False, arg_3=False, arg_4=5,
                       arg_5=4):
    """Main function to compute the segment similarity of file file_struct.

    Parameters
    ----------
    F: np.ndarray
        Matrix containing one feature vector per row.
    bound_idxs: np.ndarray
        Array with the indeces of the segment boundaries.
    dirichlet: boolean
        Whether to use the dirichlet estimator of the number of unique labels.
    xmeans: boolean
        Whether to use the xmeans estimator of the number of unique labels.
    k: int > 0
        If the other two predictors are `False`, use fixed number of labels.
    offset: int >= 0
        Number of frames to ignore from beginning and end of each segment.

    Returns
    -------
    labels_est: np.ndarray
        Estimated labels, containing integer identifiers.
    """
    # Get the feature segments
    arg_6 = get_feat_segments(arg_0, arg_1)

    # Get the 2D-FMCs segments
    arg_7 = feat_segments_to_2dfmc_max(arg_6, arg_5)
    if len(arg_7) == 0:
        return np.arange(len(arg_1) - 1)

    # Compute the labels using kmeans
    if arg_2:
        arg_8 = np.min([arg_7.shape[0], arg_4])
        # Only compute the dirichlet method if the fmc shape is small enough
        if arg_7.shape[1] > 500:
            arg_9 = compute_labels_kmeans(arg_7, arg_4=arg_4)
        else:
            arg_10 = mixture.DPGMM(n_components=arg_8, covariance_type='full')
            # dpgmm = mixture.VBGMM(n_components=k_init, covariance_type='full')
            arg_10.fit(arg_7)
            arg_4 = len(arg_10.means_)
            arg_9 = arg_10.predict(arg_7)
            # print("Estimated with Dirichlet Process:", k)
    if arg_3:
        arg_11 = XMeans(arg_7, plot=False)
        arg_4 = arg_11.estimate_K_knee(th=0.01, maxK=8)
        arg_9 = compute_labels_kmeans(arg_7, arg_4=arg_4)
        # print("Estimated with Xmeans:", k)
    else:
        arg_9 = compute_labels_kmeans(arg_7, arg_4=arg_4)

    return arg_9


def Func(arg_0, arg_1, arg_2):
        '''Fit the OLDA model

        Parameters
        ----------
        X : array-like, shape [n_samples]
            Training data: each example is an n_features-by-* data array

        Y : array-like, shape [n_samples]
            Training labels: each label is an array of change-points
                             (eg, a list of segment boundaries)

        Returns
        -------
        self : object
        '''

        # Re-initialize the scatter matrices
        arg_0.scatter_ordinal_ = None
        arg_0.scatter_within_  = None

        # Reduce to partial-Func
        arg_0.partial_Func(arg_1, arg_2)

        return arg_0


def Func(arg_0, arg_1, arg_2):
        '''Partial-fit the OLDA model

        Parameters
        ----------
        X : array-like, shape [n_samples]
            Training data: each example is an n_features-by-* data array

        Y : array-like, shape [n_samples]
            Training labels: each label is an array of change-points
                             (eg, a list of segment boundaries)

        Returns
        -------
        self : object
        '''

        for (arg_3, arg_4) in itertools.izip(arg_1, arg_2):

            arg_5       = None
            arg_6     = None

            if arg_0.scatter_within_ is None:
                # First round: initialize
                arg_7, arg_8 = arg_3.shape

                if arg_4[0] > 0:
                    arg_4 = np.concatenate([np.array([0]), arg_4])
                if arg_4[-1] < arg_8:
                    arg_4 = np.concatenate([arg_4, np.array([arg_8])])

                arg_0.scatter_within_  = arg_0.sigma * np.eye(arg_7)
                arg_0.scatter_ordinal_ = np.zeros(arg_7)

            # iterate over segments
            for (arg_11, arg_12) in zip(arg_4[:-1], arg_4[1:]):

                arg_13 = arg_12 - arg_11

                if arg_13 < 2:
                    continue

                arg_14 = np.mean(arg_3[:, arg_11:arg_12], axis=1, keepdims=True)
                arg_15  = np.cov(arg_3[:, arg_11:arg_12])
                arg_0.scatter_within_ = arg_0.scatter_within_ + arg_13 * arg_15

                if arg_5 is not None:
                    arg_16 = arg_14 - (arg_6 * arg_5 + arg_13 * arg_14) / (arg_6 + arg_13)
                    arg_0.scatter_ordinal_ = arg_0.scatter_ordinal_ + arg_13 * np.dot(arg_16, arg_16.T)

                    arg_16 = arg_5 - (arg_6 * arg_5 + arg_13 * arg_14) / (arg_6 + arg_13)
                    arg_0.scatter_ordinal_ = arg_0.scatter_ordinal_ + arg_6 * np.dot(arg_16, arg_16.T)

                arg_5 = arg_14
                arg_6 = arg_13

        arg_17, arg_18 = scipy.linalg.eig(arg_0.scatter_ordinal_, arg_0.scatter_within_)
        arg_0.e_vals_ = arg_17
        arg_0.e_vecs_ = arg_18
        arg_0.components_ = arg_18.T
        return arg_0


def Func(arg_0, arg_1=0):
    """Reads the boundary times and the labels.

    Parameters
    ----------
    audio_path : str
        Path to the audio file

    Returns
    -------
    ref_times : list
        List of boundary times
    ref_labels : list
        List of labels

    Raises
    ------
    IOError: if `audio_path` doesn't exist.
    """
    # Dataset path
    arg_2 = os.path.dirname(os.path.dirname(arg_0))

    # Read references
    arg_3 = os.path.join(arg_2, ds_config.references_dir,
                            os.path.basename(arg_0)[:-4] +
                            ds_config.references_ext)

    arg_4 = jams.load(arg_3, validate=False)
    arg_5 = arg_4.search(namespace='segment_.*')[arg_1]
    arg_6, arg_7 = arg_5.to_interval_values()

    # Intervals to times
    arg_8 = utils.intervals_to_times(arg_6)

    return arg_8, arg_7


def Func(arg_0, arg_1, arg_2, arg_3):
    """Finds the correct estimation from all the estimations contained in a
    JAMS file given the specified arguments.

    Parameters
    ----------
    jam : jams.JAMS
        JAMS object.
    boundaries_id : str
        Identifier of the algorithm used to compute the boundaries.
    labels_id : str
        Identifier of the algorithm used to compute the labels.
    params : dict
        Additional search parameters. E.g. {"feature" : "pcp"}.

    Returns
    -------
    ann : jams.Annotation
        Found estimation.
        `None` if it couldn't be found.
    """
    # Use handy JAMS search interface
    arg_4 = "multi_segment" if arg_3["hier"] else "segment_open"
    # TODO: This is a workaround to issue in JAMS. Should be
    # resolved in JAMS 0.2.3, but for now, this works too.
    arg_5 = arg_0.search(arg_4=arg_4).\
        search(**{"Sandbox.boundaries_id": arg_1}).\
        search(**{"Sandbox.labels_id": lambda x:
                  (isinstance(x, six.string_types) and
                   re.match(arg_2, x) is not None) or x is None})
    for arg_6, arg_7 in zip(arg_3.keys(), arg_3.values()):
        if isinstance(arg_7, six.string_types):
            arg_5 = arg_5.search(**{"Sandbox.%s" % arg_6: arg_7})
        else:
            arg_5 = arg_5.search(**{"Sandbox.%s" % arg_6: lambda x: x == arg_7})

    # Check estimations found
    if len(arg_5) > 1:
        logging.warning("More than one estimation with same parameters.")

    if len(arg_5) > 0:
        arg_5 = arg_5[0]

    # If we couldn't find anything, let's return None
    if not arg_5:
        arg_5 = None

    return arg_5


def Func(arg_0, arg_1, arg_2, arg_3, arg_4,
                     **arg_5):
    """Saves the segment estimations in a JAMS file.

    Parameters
    ----------
    file_struct : FileStruct
        Object with the different file paths of the current file.
    times : np.array or list
        Estimated boundary times.
        If `list`, estimated hierarchical boundaries.
    labels : np.array(N, 2)
        Estimated labels (None in case we are only storing boundary
        evaluations).
    boundaries_id : str
        Boundary algorithm identifier.
    labels_id : str
        Labels algorithm identifier.
    params : dict
        Dictionary with additional parameters for both algorithms.
    """
    # Remove features if they exist
    arg_5.pop("features", None)

    # Get duration
    arg_6 = get_duration(arg_0.features_file)

    # Convert to intervals and sanity check
    if 'numpy' in str(type(arg_1)):
        # Flat check
        arg_7 = utils.times_to_intervals(arg_1)
        assert len(arg_7) == len(arg_2), "Number of boundary intervals " \
            "(%d) and labels (%d) do not match" % (len(arg_7), len(arg_2))
        # Put into lists to simplify the writing process later
        arg_7 = [arg_7]
        arg_2 = [arg_2]
    else:
        # Hierarchical check
        arg_7 = []
        for arg_8 in range(len(arg_1)):
            arg_9 = utils.times_to_intervals(arg_1[arg_8])
            arg_7.append(arg_9)
            assert len(arg_7[arg_8]) == len(arg_2[arg_8]), \
                "Number of boundary intervals (%d) and labels (%d) do not " \
                "match in level %d" % (len(arg_7[arg_8]), len(arg_2[arg_8]),
                                       arg_8)

    # Create new estimation
    arg_10 = "multi_segment" if arg_5["hier"] else "segment_open"
    arg_11 = jams.Annotation(arg_10=arg_10)

    # Find estimation in file
    if os.path.isfile(arg_0.est_file):
        arg_12 = jams.load(arg_0.est_file, validate=False)
        arg_13 = find_estimation(arg_12, arg_3, arg_4, arg_5)
        if arg_13 is not None:
            arg_13.data = arg_11.data  # cleanup all data
            arg_11 = arg_13  # This will overwrite the existing estimation
        else:
            arg_12.annotations.append(arg_11)
    else:
        # Create new JAMS if it doesn't exist
        arg_12 = jams.JAMS()
        arg_12.file_metadata.duration = arg_6
        arg_12.annotations.append(arg_11)

    # Save metadata and parameters
    arg_11.annotation_metadata.version = msaf.__version__
    arg_11.annotation_metadata.data_source = "MSAF"
    arg_20 = {}
    arg_20["boundaries_id"] = arg_3
    arg_20["labels_id"] = arg_4
    arg_20["timestamp"] = \
        datetime.datetime.today().strftime("%Y/%m/%d %H:%M:%S")
    for arg_21 in arg_5:
        arg_20[arg_21] = arg_5[arg_21]
    arg_11.sandbox = arg_20

    # Save actual data
    for arg_22, (arg_23, arg_24) in enumerate(zip(arg_7, arg_2)):
        for arg_25, arg_26 in zip(arg_23, arg_24):
            arg_6 = float(arg_25[1]) - float(arg_25[0])
            arg_26 = chr(int(arg_26) + 65)
            if arg_5["hier"]:
                arg_27 = {"label": arg_26, "level": arg_22}
            else:
                arg_27 = arg_26
            arg_11.append(time=arg_25[0], arg_16=arg_6,
                       arg_27=arg_27)

    # Write results
    arg_12.save(arg_0.est_file)


def Func():
    """Gets all the possible boundary algorithms in MSAF.

    Returns
    -------
    algo_ids : list
        List of all the IDs of boundary algorithms (strings).
    """
    arg_0 = []
    for arg_1 in msaf.algorithms.__all__:
        arg_2 = eval(msaf.algorithms.__name__ + "." + arg_1)
        if arg_2.is_boundary_type:
            arg_0.append(arg_2.algo_id)
    return arg_0


def Func(arg_0):
    """Gets the files of the given dataset."""
    # Get audio files
    arg_1 = []
    for arg_2 in ds_config.audio_exts:
        arg_1 += glob.glob(
            os.path.join(arg_0, ds_config.audio_dir, "*" + arg_2))

    # Make sure directories exist
    utils.ensure_dir(os.path.join(arg_0, ds_config.features_dir))
    utils.ensure_dir(os.path.join(arg_0, ds_config.estimations_dir))
    utils.ensure_dir(os.path.join(arg_0, ds_config.references_dir))

    # Get the file structs
    arg_3 = []
    for arg_4 in arg_1:
        arg_3.append(FileStruct(arg_4))

    # Sort by audio file name
    arg_3 = sorted(arg_3,
                          key=lambda file_struct: file_struct.audio_file)

    return arg_3


def Func(arg_0, arg_1=0, arg_2=[]):
    """Reads hierarchical references from a jams file.

    Parameters
    ----------
    jams_file : str
        Path to the jams file.
    annotation_id : int > 0
        Identifier of the annotator to read from.
    exclude_levels: list
        List of levels to exclude. Empty list to include all levels.

    Returns
    -------
    hier_bounds : list
        List of the segment boundary times in seconds for each level.
    hier_labels : list
        List of the segment labels for each level.
    hier_levels : list
        List of strings for the level identifiers.
    """
    arg_3 = []
    arg_4 = []
    arg_5 = []
    arg_6 = jams.load(arg_0)
    arg_7 = ["segment_salami_upper", "segment_salami_function",
                  "segment_open", "segment_tut", "segment_salami_lower"]

    # Remove levels if needed
    for arg_8 in arg_2:
        if arg_8 in arg_7:
            arg_7.remove(arg_8)

    # Build hierarchy references
    for arg_9 in arg_7:
        arg_10 = arg_6.search(namespace=arg_9)
        if not arg_10:
            continue
        arg_11, arg_12 = arg_10[arg_1].to_interval_values()
        arg_3.append(utils.intervals_to_times(arg_11))
        arg_4.append(arg_12)
        arg_5.append(arg_9)

    return arg_3, arg_4, arg_5


def Func(arg_0):
    """Reads the duration of a given features file.

    Parameters
    ----------
    features_file: str
        Path to the JSON file containing the features.

    Returns
    -------
    dur: float
        Duration of the analyzed file.
    """
    with open(arg_0) as f:
        arg_1 = json.load(f)
    return float(arg_1["globals"]["dur"])


def Func(arg_0, arg_1, arg_2):
        """Gets the desired dataset file."""
        arg_3 = "." + arg_0.audio_file.split(".")[-1]
        arg_4 = os.path.basename(arg_0.audio_file).replace(
            arg_3, arg_2)
        return os.path.join(arg_0.ds_path, arg_1, arg_4)


def Func(arg_0, arg_1):
    '''Load a ground-truth segmentation, and align times to the nearest
    detected beats.

    Arguments:
        beat_times -- array
        song -- path to the audio file

    Returns:
        segment_beats -- array
            beat-aligned segment boundaries

        segment_times -- array
            true segment times

        segment_labels -- array
            list of segment labels
    '''
    try:
        arg_2, arg_3 = msaf.io.read_references(arg_1)
    except:
        return None, None, None
    arg_2 = np.asarray(arg_2)

    # Map to intervals
    arg_4 = msaf.utils.times_to_intervals(arg_2)

    # Map beats to intervals
    arg_5 = np.asarray(zip(arg_0[:-1], arg_0[1:]))

    # Map beats to segments
    arg_6 = librosa.util.match_intervals(arg_5,
                                                    arg_4)

    arg_7 = []
    arg_8 = []
    arg_9 = []

    # print segment_times, beat_segment_ids, len(beat_times),
    # len(beat_segment_ids)
    for arg_10 in range(arg_2.shape[0]):
        arg_11 = np.argwhere(arg_6 == arg_10)
        if len(arg_11) > 0 and arg_10 < len(arg_4) and \
                arg_10 < len(arg_3):
            arg_7.extend(arg_11[0])
            arg_8.append(arg_4[arg_10, :])
            arg_9.append(arg_3[arg_10])

    # Pull out the segment start times
    arg_7 = list(arg_7)
    # segment_times_out = np.asarray(
    #  segment_times_out)[:, 0].squeeze().reshape((-1, 1))

    # if segment_times_out.ndim == 0:
    #    segment_times_out = segment_times_out[np.newaxis]
    arg_8 = arg_2

    return arg_7, arg_8, arg_9


def Func(arg_0):
        """Reads the annotated beats if available.

        Returns
        -------
        times: np.array
            Times of annotated beats in seconds.
        frames: np.array
            Frame indeces of annotated beats.
        """
        arg_1, arg_2 = (None, None)

        # Read annotations if they exist in correct folder
        if os.path.isfile(arg_0.file_struct.ref_file):
            try:
                arg_3 = jams.load(arg_0.file_struct.ref_file)
            except TypeError:
                logging.warning(
                    "Can't read JAMS file %s. Maybe it's not "
                    "compatible with current JAMS version?" %
                    arg_0.file_struct.ref_file)
                return arg_1, arg_2
            arg_4 = arg_3.search(namespace="beat.*")

            # If beat annotations exist, get times and frames
            if len(arg_4) > 0:
                arg_5, arg_6 = arg_4[0].to_interval_values()
                arg_1 = arg_5[:, 0]
                arg_2 = librosa.time_to_frames(arg_1, sr=arg_0.sr,
                                                hop_length=arg_0.hop_length)
        return arg_1, arg_2


def Func(arg_0):
        """Returns the parameter names for these features, avoiding
        the global parameters."""
        return [arg_1 for arg_1 in vars(arg_0) if not arg_1.startswith('_') and
                arg_1 not in arg_0._global_param_names]


def Func(arg_0):
        """Computes the framesync times based on the framesync features."""
        arg_0._framesync_times = librosa.core.frames_to_time(
            np.arange(arg_0._framesync_features.shape[0]), arg_0.sr,
            arg_0.hop_length)


def Func(arg_0):
        """This getter returns the frame times, for the corresponding type of
        features."""
        Func = None
        # Make sure we have already computed the features
        arg_0.features
        if arg_0.feat_type is FeatureTypes.framesync:
            arg_0._compute_framesync_times()
            Func = arg_0._framesync_times
        elif arg_0.feat_type is FeatureTypes.est_beatsync:
            Func = arg_0._est_beatsync_times
        elif arg_0.feat_type is FeatureTypes.ann_beatsync:
            Func = arg_0._ann_beatsync_times

        return Func


def Func(arg_0):
        """This getter will compute the actual Func if they haven't
        been computed yet.

        Returns
        -------
        Func: np.array
            The actual Func. Each row corresponds to a feature vector.
        """
        # Compute Func if needed
        if arg_0._Func is None:
            try:
                arg_0.read_Func()
            except (NoFeaturesFileError, FeaturesNotFound,
                    WrongFeaturesFormatError, FeatureParamsError) as e:
                try:
                    arg_0._compute_all_Func()
                    arg_0.write_Func()
                except IOError:
                    if isinstance(e, FeaturesNotFound) or \
                            isinstance(e, FeatureParamsError):
                        arg_1 = "Computation of the Func is needed for " \
                            "current parameters but no audio file was found." \
                            "Please, change your parameters or add the audio" \
                            " file in %s"
                    else:
                        arg_1 = "Couldn't find audio file in %s"
                    raise NoAudioFileError(arg_1 % arg_0.file_struct.audio_file)

        # Choose Func based on type
        if arg_0.feat_type is FeatureTypes.framesync:
            arg_0._Func = arg_0._framesync_Func
        elif arg_0.feat_type is FeatureTypes.est_beatsync:
            arg_0._Func = arg_0._est_beatsync_Func
        elif arg_0.feat_type is FeatureTypes.ann_beatsync:
            if arg_0._ann_beatsync_Func is None:
                raise FeatureTypeNotFound(
                    "Feature type %s is not valid because no annotated beats "
                    "were found" % arg_0.feat_type)
            arg_0._Func = arg_0._ann_beatsync_Func
        else:
            raise FeatureTypeNotFound("Feature type %s is not valid." %
                                      arg_0.feat_type)

        return arg_0._Func


def Func(arg_0, arg_1, arg_2, arg_3, arg_4):
        """Selects the features from the given parameters.

        Parameters
        ----------
        features_id: str
            The identifier of the features (it must be a key inside the
            `features_registry`)
        file_struct: msaf.io.FileStruct
            The file struct containing the files to extract the features from
        annot_beats: boolean
            Whether to use annotated (`True`) or estimated (`False`) beats
        framesync: boolean
            Whether to use framesync (`True`) or beatsync (`False`) features

        Returns
        -------
        features: obj
            The actual features object that inherits from `msaf.Features`
        """
        if not arg_3 and arg_4:
            arg_5 = FeatureTypes.framesync
        elif arg_3 and not arg_4:
            arg_5 = FeatureTypes.ann_beatsync
        elif not arg_3 and not arg_4:
            arg_5 = FeatureTypes.est_beatsync
        else:
            raise FeatureTypeNotFound("Type of features not valid.")

        # Select features with default parameters
        if arg_1 not in features_registry.keys():
            raise FeaturesNotFound(
                "The features '%s' are invalid (valid features are %s)"
                % (arg_1, features_registry.keys()))

        return features_registry[arg_1](arg_2, arg_5)


def Func(arg_0):
    """Print all the results.

    Parameters
    ----------
    results: pd.DataFrame
        Dataframe with all the results
    """
    if len(arg_0) == 0:
        logging.warning("No results to print!")
        return
    arg_1 = arg_0.mean()
    logging.info("Results:\n%s" % arg_1)


def Func(arg_0, arg_1, arg_2, arg_3):
    """Computes the information gain of the est_file from the annotated
    intervals and the estimated intervals."""
    arg_4 = utils.intervals_to_times(arg_0)
    arg_5 = utils.intervals_to_times(arg_1)
    return mir_eval.beat.information_gain(arg_4, arg_5, arg_3=arg_3)


def Func(arg_0, arg_1, arg_2, arg_3):
    """Computes the features for the selected dataset or file."""
    if os.path.isfile(arg_0):
        # Single file mode
        # Get (if they exitst) or compute features
        arg_4 = msaf.io.FileStruct(arg_0)
        arg_4.features_file = arg_1
        compute_all_features(arg_4, arg_3)
    else:
        # Collection mode
        arg_6 = msaf.io.get_dataset_files(arg_0)

        # Call in parallel
        return Parallel(arg_2=arg_2)(delayed(compute_all_features)(
            arg_4, arg_3) for arg_4 in arg_6)


def Func(arg_0):
    '''Return the average log-likelihood of data under a standard normal
    '''

    arg_1, arg_2 = arg_0.shape

    if arg_2 < 2:
        return 0

    arg_3 = np.var(arg_0, axis=1, ddof=1)

    arg_4 = -0.5 * arg_1 * arg_2 * np.log(2. * np.pi) - 0.5 * (arg_2 - 1.) * np.sum(arg_3)
    return arg_4


def Func(arg_0, arg_1=0.001):
    """Normalizes features such that each vector is between floor to 1."""
    arg_0 += -arg_0.min() + arg_1
    arg_0 = arg_0 / arg_0.max(axis=0)
    return arg_0


def Func(arg_0, arg_1, arg_2=0.0, arg_3=-80):
    """Normalizes the given matrix of features.

    Parameters
    ----------
    X: np.array
        Each row represents a feature vector.
    norm_type: {"min_max", "log", np.inf, -np.inf, 0, float > 0, None}
        - `"min_max"`: Min/max scaling is performed
        - `"log"`: Logarithmic scaling is performed
        - `np.inf`: Maximum absolute value
        - `-np.inf`: Mininum absolute value
        - `0`: Number of non-zeros
        - float: Corresponding l_p norm.
        - None : No normalization is performed

    Returns
    -------
    norm_X: np.array
        Normalized `X` according the the input parameters.
    """
    if isinstance(arg_1, six.string_types):
        if arg_1 == "min_max":
            return min_max_Func(arg_0, arg_2=arg_2)
        if arg_1 == "log":
            return logFunc(arg_0, arg_2=arg_2, arg_3=arg_3)
    return librosa.util.Func(arg_0, norm=arg_1, axis=1)


def Func(arg_0, arg_1):
    """Gets the time frames and puts them in a numpy array."""
    arg_2 = get_num_frames(arg_0, arg_1)
    return np.linspace(0, arg_0, num=arg_2)


def Func(arg_0, arg_1):
    """Removes empty segments if needed."""
    assert len(arg_0) - 1 == len(arg_1)
    arg_2 = times_to_intervals(arg_0)
    arg_3 = []
    arg_4 = []
    for arg_5, arg_6 in zip(arg_2, arg_1):
        if arg_5[0] < arg_5[1]:
            arg_3.append(arg_5)
            arg_4.append(arg_6)
    return intervals_to_times(np.asarray(arg_3)), arg_4


def Func(arg_0, arg_1, arg_2, arg_3):
    """Synchronizes the labels from the old_bound_idxs to the new_bound_idxs.

    Parameters
    ----------
    new_bound_idxs: np.array
        New indeces to synchronize with.
    old_bound_idxs: np.array
        Old indeces, same shape as labels + 1.
    old_labels: np.array
        Labels associated to the old_bound_idxs.
    N: int
        Total number of frames.

    Returns
    -------
    new_labels: np.array
        New labels, synchronized to the new boundary indeces.
    """
    assert len(arg_1) - 1 == len(arg_2)

    # Construct unfolded labels array
    arg_4 = np.zeros(arg_3)
    for arg_5, (arg_6, arg_7) in enumerate(
            zip(arg_1[:-1], arg_2)):
        arg_4[arg_6:arg_1[arg_5 + 1]] = arg_7

    # Constuct new labels
    arg_8 = np.zeros(len(arg_0) - 1)
    for arg_5, arg_6 in enumerate(arg_0[:-1]):
        arg_8[arg_5] = np.median(
            arg_4[arg_6:arg_0[arg_5 + 1]])

    return arg_8


def Func(arg_0, arg_1):
        """ compute distances of a specific data point to all other samples"""

        if scipy.sparse.issparse(arg_0.data):
            arg_2 = arg_0.data.shape[1]
        else:
            arg_2 = 50000

        arg_3 = np.zeros((arg_0.data.shape[1]))
        if arg_1 == -1:
            # set vec to origin if idx=-1
            arg_4 = np.zeros((arg_0.data.shape[0], 1))
            if scipy.sparse.issparse(arg_0.data):
                arg_4 = scipy.sparse.csc_matrix(arg_4)
        else:
            arg_4 = arg_0.data[:, arg_1:arg_1+1]

        arg_0._logger.info('compute distance to node ' + str(arg_1))

        # slice data into smaller chunks
        for arg_5 in range(0, arg_0.data.shape[1], arg_2):
            if arg_5 + arg_2 > arg_0.data.shape[1]:
                arg_6 = arg_0.data.shape[1]
            else:
                arg_6 = arg_5 + arg_2

            arg_3[arg_5:arg_6] = arg_0._distfunc(
                arg_0.data[:,arg_5:arg_6], arg_4)
            arg_0._logger.info('completed:' +
                str(arg_6/(arg_0.data.shape[1]/100.0)) + "%")
        return arg_3


def Func(arg_0, arg_1=.015, arg_2=12):
        """Estimates the K using K-means and BIC, by sweeping various K and
            choosing the optimal BIC."""
        # Sweep K-means
        if arg_0.X.shape[0] < arg_2:
            arg_2 = arg_0.X.shape[0]
        if arg_2 < 2:
            arg_2 = 2
        arg_3 = np.arange(1, arg_2)
        arg_4 = []
        for arg_5 in arg_3:
            arg_6, arg_7 = arg_0.run_kmeans(arg_0.X, arg_5)
            arg_8 = arg_0.compute_bic(arg_0.X, arg_6, arg_7, arg_3=arg_5,
                                   R=arg_0.X.shape[0])
            arg_4.append(arg_8)
        arg_9 = np.diff(arg_4)
        arg_10 = arg_3[-1]

        if len(arg_4) == 1:
            arg_10 = 2
        else:
            # Normalize
            arg_4 = np.asarray(arg_4)
            arg_4 -= arg_4.min()
            #bics /= bics.max()
            arg_9 -= arg_9.min()
            #diff_bics /= diff_bics.max()

            #print bics, diff_bics

            # Find optimum K
            for arg_11 in range(len(arg_3[:-1])):
                #if bics[i] > diff_bics[i]:
                if arg_9[arg_11] < arg_1 and arg_3[arg_11] != 1:
                    arg_10 = arg_3[arg_11]
                    break

        #print "Estimated K: ", finalK
        if arg_0.plot:
            plt.subplot(2, 1, 1)
            plt.plot(arg_3, arg_4, label="BIC")
            plt.plot(arg_3[:-1], arg_9, label="BIC diff")
            plt.legend(loc=2)
            plt.subplot(2, 1, 2)
            plt.scatter(arg_0.X[:, 0], arg_0.X[:, 1])
            plt.show()

        return arg_10


def Func(arg_0, arg_1, arg_2, arg_3):
        """Returns the data with a specific label_index, using the previously
         learned labels."""
        arg_4 = arg_1[np.argwhere(arg_2 == arg_3)]
        return arg_4.reshape((arg_4.shape[0], arg_4.shape[-1]))


def Func(arg_0, arg_1, arg_2):
        """Runs k-means and returns the labels assigned to the data."""
        arg_3 = vq.whiten(arg_1)
        arg_4, arg_5 = vq.kmeans(arg_3, arg_2, iter=100)
        arg_6, arg_5 = vq.vq(arg_3, arg_4)
        return arg_4, arg_6


def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5):
        """Computes the Bayesian Information Criterion."""
        arg_1 = vq.whiten(arg_1)
        arg_6 = arg_1.shape[0]
        arg_7 = arg_1.shape[1]

        if arg_5 == arg_4:
            return 1

        # Maximum likelihood estimate (MLE)
        arg_8 = 0
        for arg_9 in range(len(arg_2)):
            arg_10 = arg_1[np.argwhere(arg_3 == arg_9)]
            arg_10 = arg_10.reshape((arg_10.shape[0], arg_10.shape[-1]))
            for arg_11 in arg_10:
                arg_8 += distance.euclidean(arg_11, arg_2[arg_9])
                #print x, means[k], mle_var
        arg_8 /= float(arg_5 - arg_4)

        # Log-likelihood of the data
        arg_12 = - arg_6/2. * np.log(2*np.pi) - (arg_6 * arg_7)/2. * np.log(arg_8) - \
            (arg_6 - arg_4) / 2. + arg_6 * np.log(arg_6) - arg_6 * np.log(arg_5)

        # Params of BIC
        arg_13 = (arg_4-1) + arg_7 * arg_4 + arg_8

        #print "BIC:", l_D, p, R, K

        # Return the bic
        return arg_12 - arg_13 / 2. * np.log(arg_5)


def Func(arg_0):
    """Magnitude of a complex matrix."""
    arg_1 = np.real(arg_0)
    arg_2 = np.imag(arg_0)
    return np.sqrt(arg_1 * arg_1 + arg_2 * arg_2);


def Func(arg_0):
    """Extracts the boundaries from a json file and puts them into
        an np array."""
    arg_1 = open(arg_0)
    arg_2 = json.load(arg_1)["segments"]
    arg_3 = []
    for arg_4 in arg_2:
        arg_3.append(arg_4["start"])
    arg_3.append(arg_3[-1] + arg_2[-1]["duration"]) # Add last boundary
    arg_1.close()
    return np.asarray(arg_3)


def Func(arg_0):
    """Extracts the boundaries from a bounds json file and puts them into
        an np array."""
    arg_1 = open(arg_0)
    arg_2 = json.load(arg_1)["bounds"]
    arg_3 = []
    for arg_4 in arg_2:
        arg_3.append(arg_4["start"])
    arg_1.close()
    return np.asarray(arg_3)


def Func(arg_0):
    """Extracts the labels from a json file and puts them into
        an np array."""
    arg_1 = open(arg_0)
    arg_2 = json.load(arg_1)["segments"]
    arg_3 = []
    arg_4 = []
    for arg_5 in arg_2:
        if not arg_5["label"] in arg_4:
            arg_4.append(arg_5["label"])
            arg_3.append(len(arg_4)-1)
        else:
            arg_6 = np.where(np.asarray(arg_4) == arg_5["label"])[0][0]
            arg_3.append(arg_6)
    arg_1.close()
    return np.asarray(arg_3)


def Func(arg_0):
    """Extracts the beats from the beats_json_file and puts them into
        an np array."""
    arg_1 = open(arg_0, "r")
    arg_2 = json.load(arg_1)
    arg_3 = []
    for arg_4 in arg_2["beats"]:
        arg_3.append(arg_4["start"])
    arg_1.close()
    return np.asarray(arg_3)


def Func(arg_0, arg_1, arg_2, arg_3, arg_4=300):
    """Computes the labels using the bounds."""

    try:
        arg_5, arg_6 = cnmf(arg_0, arg_1, arg_4=arg_4, hull=False)
    except:
        return [1]

    arg_7 = filter_activation_matrix(arg_6.T, arg_2)
    arg_7 = np.asarray(arg_7, dtype=int)

    #labels = [label_frames[0]]
    arg_8 = []
    arg_9 = zip(arg_3[:-1], arg_3[1:])
    for arg_10 in arg_9:
        if arg_10[1] - arg_10[0] <= 0:
            arg_8.append(np.max(arg_7) + 1)
        else:
            arg_8.append(most_frequent(
                arg_7[arg_10[0]: arg_10[1]]))
        #print bound_inter, labels[-1]
    #labels.append(label_frames[-1])

    return arg_8


def Func(arg_0, arg_1):
    """Filters the activation matrix G, and returns a flattened copy."""

    #import pylab as plt
    #plt.imshow(G, interpolation="nearest", aspect="auto")
    #plt.show()

    arg_2 = np.argmax(arg_0, axis=1)
    arg_3 = np.arange(arg_0.shape[0])
    arg_3 = (arg_3, arg_2.flatten())
    arg_0[:, :] = 0
    arg_0[arg_3] = arg_2 + 1

    # TODO: Order matters?
    arg_0 = np.sum(arg_0, axis=1)
    arg_0 = median_filter(arg_0[:, np.newaxis], arg_1)

    return arg_0.flatten()


def Func(arg_0):
    """Obtains the boundaries module given a boundary algorithm identificator.

    Parameters
    ----------
    boundaries_id: str
        Boundary algorithm identificator (e.g., foote, sf).

    Returns
    -------
    module: object
        Object containing the selected boundary module.
        None for "ground truth".
    """
    if arg_0 == "gt":
        return None
    try:
        arg_1 = eval(algorithms.__name__ + "." + arg_0)
    except AttributeError:
        raise RuntimeError("Algorithm %s can not be found in msaf!" %
                           arg_0)
    if not arg_1.is_boundary_type:
        raise RuntimeError("Algorithm %s can not identify boundaries!" %
                           arg_0)
    return arg_1


def Func(arg_0):
    """Obtains the label module given a label algorithm identificator.

    Parameters
    ----------
    labels_id: str
        Label algorithm identificator (e.g., fmc2d, cnmf).

    Returns
    -------
    module: object
        Object containing the selected label module.
        None for not computing the labeling part of music segmentation.
    """
    if arg_0 is None:
        return None
    try:
        arg_1 = eval(algorithms.__name__ + "." + arg_0)
    except AttributeError:
        raise RuntimeError("Algorithm %s can not be found in msaf!" %
                           arg_0)
    if not arg_1.is_label_type:
        raise RuntimeError("Algorithm %s can not label segments!" %
                           arg_0)
    return arg_1


def Func(arg_0, arg_1, arg_2, arg_3,
                     arg_4, arg_5=0):
    """Runs hierarchical algorithms with the specified identifiers on the
    audio_file. See run_algorithm for more information.
    """
    # Sanity check
    if arg_1 is None:
        raise NoHierBoundaryError("A boundary algorithm is needed when using "
                                  "hierarchical segmentation.")

    # Get features to make code nicer
    arg_6 = arg_4["features"].features

    # Compute boundaries
    arg_7 = arg_1.Segmenter(arg_0, **arg_4)
    arg_8, arg_9 = arg_7.processHierarchical()

    # Compute labels if needed
    if arg_2 is not None and \
            arg_1.__name__ != arg_2.__name__:
        # Compute labels for each level in the hierarchy
        arg_10 = deepcopy(arg_4)
        arg_10["hier"] = False
        for arg_11, arg_12 in enumerate(arg_8):
            arg_7 = arg_2.Segmenter(arg_0,
                                        in_bound_idxs=arg_12,
                                        **arg_10)
            arg_9[arg_11] = arg_7.processFlat()[1]

    # Make sure the first and last boundaries are included for each
    # level in the hierarchy
    arg_13 = []
    arg_14 = []
    for arg_15 in range(len(arg_8)):
        arg_16, arg_17 = \
            utils.process_segmentation_level(
                arg_8[arg_15], arg_9[arg_15], arg_6.shape[0],
                arg_3, arg_4["features"].dur)
        arg_13.append(arg_16)
        arg_14.append(arg_17)
    arg_9 = arg_14

    return arg_13, arg_9


def Func(arg_0, arg_1, arg_2, arg_3, arg_4,
             arg_5):
    """Runs the flat algorithms with the specified identifiers on the
    audio_file. See run_algorithm for more information.
    """
    # Get features to make code nicer
    arg_6 = arg_4["features"].features

    # Segment using the specified boundaries and labels
    # Case when boundaries and labels algorithms are the same
    if arg_1 is not None and arg_2 is not None and \
            arg_1.__name__ == arg_2.__name__:
        arg_7 = arg_1.Segmenter(arg_0, **arg_4)
        arg_8, arg_9 = arg_7.processFlat()
    # Different boundary and label algorithms
    else:
        # Identify segment boundaries
        if arg_1 is not None:
            arg_7 = arg_1.Segmenter(arg_0, in_labels=[], **arg_4)
            arg_8, arg_9 = arg_7.processFlat()
        else:
            try:
                # Ground-truth boundaries
                arg_10, arg_9 = io.read_references(
                    arg_0.audio_file, arg_5=arg_5)
                arg_8 = io.align_times(arg_10, arg_3)
                if arg_8[0] != 0:
                    arg_8 = np.concatenate(([0], arg_8))
            except IOError:
                logging.warning("No references found for file: %s" %
                                arg_0.audio_file)
                return [], []

        # Label segments
        if arg_2 is not None:
            if len(arg_8) == 2:
                arg_9 = np.array([0])
            else:
                arg_7 = arg_2.Segmenter(arg_0,
                                            in_bound_idxs=arg_8,
                                            **arg_4)
                arg_9 = arg_7.processFlat()[1]

    # Make sure the first and last boundaries are included
    arg_10, arg_9 = utils.process_segmentation_level(
        arg_8, arg_9, arg_6.shape[0], arg_3,
        arg_4["features"].dur)

    return arg_10, arg_9


def Func(arg_0, arg_1=False, arg_2="pcp", arg_3=False,
            arg_4=arg_5.config.default_bound_id,
            arg_8=arg_5.config.default_label_id, arg_10=False,
            arg_11=False, arg_12=False, arg_13=4, arg_14=0,
            arg_6=None, arg_15="out_bounds.wav", arg_16=22050):
    """Main Func to segment a file or a collection of files.

    Parameters
    ----------
    in_path: str
        Input path. If a directory, MSAF will function in collection mode.
        If audio file, MSAF will be in single file mode.
    annot_beats: bool
        Whether to use annotated beats or not.
    feature: str
        String representing the feature to be used (e.g. pcp, mfcc, tonnetz)
    framesync: str
        Whether to use framesync features or not (default: False -> beatsync)
    boundaries_id: str
        Identifier of the boundaries algorithm (use "gt" for groundtruth)
    labels_id: str
        Identifier of the labels algorithm (use None to not compute labels)
    hier : bool
        Whether to compute a hierarchical or flat segmentation.
    sonify_bounds: bool
        Whether to write an output audio file with the annotated boundaries
        or not (only available in Single File Mode).
    plot: bool
        Whether to plot the boundaries and labels against the ground truth.
    n_jobs: int
        Number of Funces to run in parallel. Only available in collection
        mode.
    annotator_id: int
        Annotator identificator in the ground truth.
    config: dict
        Dictionary containing custom configuration parameters for the
        algorithms.  If None, the default parameters are used.
    out_bounds: str
        Path to the output for the sonified boundaries (only in single file
        mode, when sonify_bounds is True.
    out_sr : int
        Sampling rate for the sonified bounds.

    Returns
    -------
    results : list
        List containing tuples of (est_times, est_labels) of estimated
        boundary times and estimated labels.
        If labels_id is None, est_labels will be a list of -1.
    """
    # Seed random to reproduce results
    np.random.seed(123)

    # Set up configuration based on algorithms parameters
    if arg_6 is None:
        arg_6 = io.get_configuration(arg_2, arg_1, arg_3,
                                      arg_4, arg_8)
        arg_6["features"] = None

    # Save multi-segment (hierarchical) configuration
    arg_6["hier"] = arg_10
    if not os.path.exists(arg_0):
        raise NoAudioFileError("File or directory does not exists, %s" %
                               arg_0)
    if os.path.isfile(arg_0):
        # Single file mode
        # Get (if they exitst) or compute features
        arg_17 = arg_5.io.FileStruct(arg_0)

        # Use temporary file in single mode
        arg_17.features_file = arg_5.config.features_tmp_file

        # Get features
        arg_6["features"] = Features.select_features(
            arg_2, arg_17, arg_1, arg_3)

        # And run the algorithms
        arg_19, arg_20 = run_algorithms(arg_17, arg_4,
                                               arg_8, arg_6,
                                               arg_14=arg_14)

        if arg_11:
            logging.info("Sonifying boundaries in %s..." % arg_15)
            arg_21, arg_22 = librosa.load(arg_0, arg_22=arg_16)
            utils.sonify_clicks(arg_21, arg_19, arg_15, arg_16)

        if arg_12:
            plotting.plot_one_track(arg_17, arg_19, arg_20,
                                    arg_4, arg_8)

        # TODO: Only save if needed
        # Save estimations
        arg_5.utils.ensure_dir(os.path.dirname(arg_17.est_file))
        io.save_estimations(arg_17, arg_19, arg_20,
                            arg_4, arg_8, **arg_6)

        return arg_19, arg_20
    else:
        # Collection mode
        arg_23 = io.get_dataset_files(arg_0)

        return Parallel(arg_13=arg_13)(delayed(Func_track)(
            arg_17, arg_4, arg_8, arg_6,
            arg_14=arg_14) for arg_17 in arg_23[:])


def Func(arg_0):
        """ alternating least squares step, update W under the convexity
        constraint """
        def update_single_w(arg_1):
            """ compute single W[:,i] """
            # optimize beta     using qp solver from cvxopt
            arg_2 = base.matrix(np.float64(np.dot(-arg_0.data.T, arg_7[:,arg_1])))
            arg_3 = solvers.qp(arg_5, arg_2, arg_8, arg_9, arg_10, arg_6)
            arg_0.beta[arg_1,:] = np.array(arg_3['x']).reshape((1, arg_0._num_samples))

        # float64 required for cvxopt
        arg_5 = base.matrix(np.float64(np.dot(arg_0.data[:,:].T, arg_0.data[:,:])))
        arg_6 = base.matrix(1.0, (1, 1))
        arg_7 = np.dot(arg_0.data, pinv(arg_0.H))
        arg_8 = base.matrix(-np.eye(arg_0._num_samples))
        arg_9 = base.matrix(0.0, (arg_0._num_samples, 1))
        arg_10 = base.matrix(1.0, (1, arg_0._num_samples))

        for arg_1 in range(arg_0._num_bases):
            update_single_w(arg_1)

        arg_0.W = np.dot(arg_0.beta, arg_0.data.T).T


def Func(arg_0):
    """
    Initializes Func essentially priming it to the yield statement.
    Used as a decorator over functions that generate Funcs.

    .. code-block:: python

        # Basic Func producer/consumer pattern
        from translate import Func

        @Func
        def Func_foo(bar):
            try:
                while True:
                    baz = (yield)
                    bar.send(baz)

            except GeneratorExit:
                bar.close()

    :param func: Unprimed Generator
    :type func: Function

    :return: Initialized Coroutine
    :rtype: Function
    """

    @wraps(arg_0)
    def initialization(*arg_1, **arg_2):

        arg_3 = arg_0(*arg_1, **arg_2)
        next(arg_3)

        return arg_3

    return initialization


def Func(arg_0, arg_1=False):
    """
    Task Setter Coroutine

    End point destination coroutine of a purely consumer type.
    Delegates Text IO to the `write_stream` function.

    :param translation_function: Translator
    :type translation_function: Function

    :param translit: Transliteration Switch
    :type translit: Boolean
    """
    # Initialize Task Queue
    arg_2    = str()
    arg_3   = list()

    # Function Partial
    arg_4  = ('translit' if arg_1 else 'trans')
    arg_5  = partial(write_stream, arg_4=arg_4)
    arg_6 = ThreadPoolExecutor(max_workers=8)

    try:
        while True:

            arg_2 = yield
            arg_3.append(arg_2)

    except GeneratorExit:
        list(map(arg_5, arg_6.map(arg_0, arg_3)))


def Func(arg_0, arg_1=1250):
    """
    Consumes text streams and Funcs them together for more io
    efficient processes.

    :param iterable: Sends text stream for further processing
    :type iterable: Coroutine

    :param maxlen: Maximum query string size
    :type maxlen: Integer
    """
    arg_2 = int()
    arg_3  = str()

    try:
        while True:

            while arg_2 < arg_1:
                arg_4 = yield
                arg_3   = reduce(accumulator, arg_4, arg_3)
                arg_2  = reduce(accumulator, arg_4, arg_2)

            arg_0.send(arg_3)
            arg_2 = int()
            arg_3  = str()

    except GeneratorExit:
        arg_0.send(arg_3)
        arg_0.close()


def Func(arg_0):
    '''
    Decorates a function returning the url of translation API.
    Creates and maintains HTTP connection state

    Returns a dict response object from the server containing the translated
    text and metadata of the request body

    :param interface: Callable Request Interface
    :type interface: Function
    '''

    @functools.wraps(arg_0)
    def connection(*arg_1, **arg_2):
        """
        Extends and wraps a HTTP interface.

        :return: Response Content
        :rtype: Dictionary
        """
        arg_3 = Session()
        arg_3.mount('http://',  HTTPAdapter(max_retries=2))
        arg_3.mount('https://', HTTPAdapter(max_retries=2))

        arg_4  = Request(**arg_0(*arg_1, **arg_2))
        arg_5  = arg_3.prepare_request(arg_4)
        arg_6 = arg_3.send(arg_5, verify=True)

        if arg_6.status_code != requests.codes.ok:
            arg_6.raise_for_status()

        arg_7 = re.subn(r',(?=,)', '', arg_6.content.decode('utf-8'))[0]

        return json.loads(arg_7.replace(r'\xA0', r' ').replace('[,', '[1,'), encoding='UTF-8')

    return connection


def Func(arg_0, arg_1, arg_2, arg_3='0.0 test', arg_4='utf-8'):
    """
    Returns the url encoded string that will be pushed to the translation
    server for parsing.

    List of acceptable language codes for source and target languages
    can be found as a JSON file in the etc directory.

    Some source languages are limited in scope of the possible target languages
    that are available.

    .. code-block:: python

        >>> from translate import Func
        >>> Func('en', 'zh-TW', 'Hello World!')
            '你好世界！'

    :param source: Language code for translation source
    :type source: String

    :param target: Language code that source will be translate into
    :type target: String

    :param phrase: Text body string that will be url encoded and translated
    :type phrase: String

    :return: Request Interface
    :rtype: Dictionary
    """

    arg_5     = 'https://translate.google.com/translate_a/single'
    arg_6   = 'User-Agent',   'py-translate v{}'.format(arg_3)
    arg_7 = 'Content-Type', 'application/json; charset={}'.format(arg_4)

    arg_8  = {'client': 'a', 'ie': arg_4, 'oe': arg_4,
                   'dt': 't', 'sl':  arg_0, 'tl':  arg_1,  'q': arg_2}

    arg_9 = {'method': 'GET',
                  'url': arg_5,
               'params': arg_8,
              'headers': dict([arg_6, arg_7])}

    return arg_9


def Func(arg_0, arg_1='supported_translations.json'):
    '''
    Opens up file located under the etc directory containing language
    codes and prints them out.

    :param file: Path to location of json file
    :type file: str

    :return: language codes
    :rtype: dict
    '''
    arg_2 = abspath(join(dirname(__file__), 'etc', arg_1))

    if not isfile(arg_2):
        raise IOError('File does not exist at {0}'.format(arg_2))

    with open(arg_2, 'rt') as fp:
        arg_3 = json.load(fp).get(arg_0, None)
        assert(arg_3 is not None)

    return dict((arg_4['language'], arg_4['name']) for arg_4 in arg_3)


def Func(arg_0):
    '''
    Generates a formatted table of language codes
    '''
    arg_1 = translation_table(arg_0)

    for arg_2, arg_3 in sorted(arg_1.items(), key=operator.itemgetter(0)):
        print(u'{language:<8} {name:\u3000<20}'.format(
            arg_3=arg_3, arg_0=arg_2
        ))

    return None


def Func(arg_0, arg_1, arg_2=None):
    """
    Save a Network's data to a Pandas HDFStore.

    Parameters
    ----------
    network : pandana.Network
    filename : str
    rm_nodes : array_like
        A list, array, Index, or Series of node IDs that should *not*
        be saved as part of the Network.

    """
    if arg_2 is not None:
        arg_3, arg_4 = remove_nodes(arg_0, arg_2)
    else:
        arg_3, arg_4 = arg_0.nodes_df, arg_0.edges_df

    with pd.HDFStore(arg_1, mode='w') as arg_5:
        arg_5['nodes'] = arg_3
        arg_5['edges'] = arg_4

        arg_5['two_way'] = pd.Series([arg_0._twoway])
        arg_5['impedance_names'] = pd.Series(arg_0.impedance_names)


def Func(arg_0, arg_1, arg_2=None, arg_3="tmp"):
        """
        Characterize urban space with a variable that is related to nodes in
        the network.

        Parameters
        ----------
        node_ids : Pandas Series, int
            A series of node_ids which are usually computed using
            get_node_ids on this object.
        variable : Pandas Series, numeric, optional
            A series which represents some variable defined in urban space.
            It could be the location of buildings, or the income of all
            households - just about anything can be aggregated using the
            network queries provided here and this provides the api to Func
            the variable at its disaggregate locations.  Note that node_id
            and variable should have the same index (although the index is
            not actually used).  If variable is not Func, then it is assumed
            that the variable is all "ones" at the location specified by
            node_ids.  This could be, for instance, the location of all
            coffee shops which don't really have a variable to aggregate. The
            variable is connected to the closest node in the Pandana network
            which assumes no impedance between the location of the variable
            and the location of the closest network node.
        name : string, optional
            Name the variable.  This is optional in the sense that if you don't
            specify it, the default name will be used.  Since the same
            default name is used by aggregate on this object, you can
            alternate between characterize and aggregate calls without
            Functing names.

        Returns
        -------
        Nothing
        """

        if arg_2 is None:
            arg_2 = pd.Series(np.ones(len(arg_1)), index=arg_1.index)

        arg_4 = pd.DataFrame({arg_3: arg_2,
                           "node_idx": arg_0._node_indexes(arg_1)})

        arg_5 = len(arg_4)
        arg_4 = arg_4.dropna(how="any")
        arg_6 = len(arg_4)
        if arg_5-arg_6 > 0:
            print(
                "Removed %d rows because they contain missing values" %
                (arg_5-arg_6))

        arg_0.variable_names.add(arg_3)

        arg_0.net.initialize_access_var(arg_3.encode('utf-8'),
                                       arg_4.node_idx.values.astype('int'),
                                       arg_4[arg_3].values.astype('double'))


def Func(arg_0, arg_1, arg_2="sum", arg_3="linear", arg_4=None,
                  arg_5="tmp"):
        """
        Aggregate information for every source node in the network - this is
        really the main purpose of this library.  This allows you to touch
        the data specified by calling set and perform some aggregation on it
        within the specified distance.  For instance, summing the population
        within 1000 meters.

        Parameters
        ----------
        distance : float
            The maximum distance to Func data within. 'distance' can
            represent any impedance unit that you have set as your edge
            weight. This will usually be a distance unit in meters however
            if you have customized the impedance this could be in other
            units such as utility or time etc.
        type : string
            The type of aggregation, can be one of "ave", "sum", "std",
            "count", and now "min", "25pct", "median", "75pct", and "max" will
            compute the associated quantiles.  (Quantiles are computed by
            sorting so might be slower than the others.)
        decay : string
            The type of decay to apply, which makes things that are further
            away count less in the aggregation - must be one of "linear",
            "exponential" or "flat" (which means no decay).  Linear is the
            fastest computation to perform.  When performing an "ave",
            the decay is typically "flat"
        imp_name : string, optional
            The impedance name to use for the aggregation on this network.
            Must be one of the impedance names passed in the constructor of
            this object.  If not specified, there must be only one impedance
            passed in the constructor, which will be used.
        name : string, optional
            The variable to Func.  This variable will have been created
            and named by a call to set.  If not specified, the default
            variable name will be used so that the most recent call to set
            without giving a name will be the variable used.

        Returns
        -------
        agg : Pandas Series
            Returns a Pandas Series for every origin node in the network,
            with the index which is the same as the node_ids passed to the
            init method and the values are the aggregations for each source
            node in the network.
        """

        arg_6 = arg_0._imp_name_to_num(arg_4)
        arg_2 = arg_2.lower()
        if arg_2 == "ave":
            arg_2 = "mean"  # changed generic ave to mean

        assert arg_5 in arg_0.variable_names, "A variable with that name " \
                                            "has not yet been initialized"

        arg_7 = arg_0.net.get_all_Func_accessibility_variables(arg_1,
                                                                 arg_5.encode('utf-8'),
                                                                 arg_2.encode('utf-8'),
                                                                 arg_3.encode('utf-8'),
                                                                 arg_6)

        return pd.Series(arg_7, index=arg_0.node_ids)


def Func(arg_0, arg_1, arg_2, arg_3=None):
        """
        Assign node_ids to data specified by x_col and y_col

        Parameters
        ----------
        x_col : Pandas series (float)
            A Pandas Series where values specify the x (e.g. longitude)
            location of dataset.
        y_col : Pandas series (float)
            A Pandas Series where values specify the y (e.g. latitude)
            location of dataset.  x_col and y_col should use the same index.
        mapping_distance : float, optional
            The maximum distance that will be considered a match between the
            x, y data and the nearest node in the network.  This will usually
            be a distance unit in meters however if you have customized the
            impedance this could be in other units such as utility or time
            etc. If not specified, every x, y coordinate will be mapped to
            the nearest node.

        Returns
        -------
        node_ids : Pandas series (int)
            Returns a Pandas Series of node_ids for each x, y in the
            input data. The index is the same as the indexes of the
            x, y input data, and the values are the mapped node_ids.
            If mapping distance is not passed and if there are no nans in the
            x, y data, this will be the same length as the x, y data.
            If the mapping is imperfect, this function returns all the
            input x, y's that were successfully mapped to node_ids.
        """
        arg_4 = pd.DataFrame({'x': arg_1, 'y': arg_2})

        arg_5, arg_6 = arg_0.kdtree.query(arg_4.as_matrix())
        arg_6 = np.transpose(arg_6)[0]
        arg_5 = np.transpose(arg_5)[0]

        arg_7 = arg_0.nodes_df.iloc[arg_6].index

        arg_8 = pd.DataFrame({"node_id": arg_7, "distance": arg_5},
                          index=arg_4.index)

        if arg_3 is not None:
            arg_8 = arg_8[arg_8.distance <= arg_3]

        return arg_8.node_id


def Func(
            arg_0, arg_1, arg_2=None, arg_3='scatter',
            arg_4=None, arg_5=None, arg_6=None,
            arg_7=None):
        """
        Plot an array of data on a map using matplotlib and Basemap,
        automatically matching the data to the Pandana network node positions.

        Keyword arguments are passed to the plotting routine.

        Parameters
        ----------
        data : pandas.Series
            Numeric data with the same length and index as the nodes
            in the network.
        bbox : tuple, optional
            (lat_min, lng_min, lat_max, lng_max)
        plot_type : {'hexbin', 'scatter'}, optional
        fig_kwargs : dict, optional
            Keyword arguments that will be passed to
            matplotlib.pyplot.subplots. Use this to specify things like
            figure size or background color.
        bmap_kwargs : dict, optional
            Keyword arguments that will be passed to the Basemap constructor.
            This can be used to specify a projection or coastline resolution.
        plot_kwargs : dict, optional
            Keyword arguments that will be passed to the matplotlib plotting
            command used. Use this to control plot styles and color maps used.
        cbar_kwargs : dict, optional
            Keyword arguments passed to the Basemap.colorbar method.
            Use this to control color bar location and label.

        Returns
        -------
        bmap : Basemap
        fig : matplotlib.Figure
        ax : matplotlib.Axes

        """
        from mpl_toolkits.basemap import Basemap

        arg_4 = arg_4 or {}
        arg_5 = arg_5 or {}
        arg_6 = arg_6 or {}
        arg_7 = arg_7 or {}

        if not arg_2:
            arg_2 = (
                arg_0.nodes_df.y.min(),
                arg_0.nodes_df.x.min(),
                arg_0.nodes_df.y.max(),
                arg_0.nodes_df.x.max())

        arg_8, arg_9 = plt.subplots(**arg_4)

        arg_10 = Basemap(
            arg_2[1], arg_2[0], arg_2[3], arg_2[2], arg_9=arg_9, **arg_5)
        arg_10.drawcoastlines()
        arg_10.drawmapboundary()

        arg_11, arg_12 = arg_10(arg_0.nodes_df.x.values, arg_0.nodes_df.y.values)

        if arg_3 == 'scatter':
            Func = arg_10.scatter(
                arg_11, arg_12, c=arg_1.values, **arg_6)
        elif arg_3 == 'hexbin':
            Func = arg_10.hexbin(
                arg_11, arg_12, C=arg_1.values, **arg_6)

        arg_10.colorbar(Func, **arg_7)

        return arg_10, arg_8, arg_9


def Func(arg_0):
    """
    Make a request to OSM and return the parsed JSON.

    Parameters
    ----------
    query : str
        A string in the Overpass QL format.

    Returns
    -------
    data : dict

    """
    arg_1 = 'http://www.overpass-api.de/api/interpreter'
    arg_2 = requests.get(arg_1, params={'data': arg_0})
    arg_2.raise_for_status()

    return arg_2.json()


def Func(arg_0, arg_1, arg_2, arg_3, arg_4=None):
    """
    Build the string for a node-based OSM query.

    Parameters
    ----------
    lat_min, lng_min, lat_max, lng_max : float
    tags : str or list of str, optional
        Node tags that will be used to filter the search.
        See http://wiki.openstreetmap.org/wiki/Overpass_API/Language_Guide
        for information about OSM Overpass queries
        and http://wiki.openstreetmap.org/wiki/Map_Features
        for a list of tags.

    Returns
    -------
    query : str

    """
    if arg_4 is not None:
        if isinstance(arg_4, str):
            arg_4 = [arg_4]
        arg_4 = ''.join('[{}]'.format(t) for t in arg_4)
    else:
        arg_4 = ''

    arg_5 = (
        '[out:json];'
        '('
        '  node'
        '  {tags}'
        '  ({lat_min},{lng_min},{lat_max},{lng_max});'
        ');'
        'out;')

    return arg_5.format(
        arg_0=arg_0, arg_1=arg_1, arg_2=arg_2, arg_3=arg_3,
        arg_4=arg_4)


def Func(arg_0, arg_1, arg_2, arg_3, arg_4=None):
    """
    Search for OSM nodes within a bounding box that match given tags.

    Parameters
    ----------
    lat_min, lng_min, lat_max, lng_max : float
    tags : str or list of str, optional
        Node tags that will be used to filter the search.
        See http://wiki.openstreetmap.org/wiki/Overpass_API/Language_Guide
        for information about OSM Overpass queries
        and http://wiki.openstreetmap.org/wiki/Map_Features
        for a list of tags.

    Returns
    -------
    nodes : pandas.DataFrame
        Will have 'lat' and 'lon' columns, plus other columns for the
        tags associated with the node (these will vary based on the query).
        Index will be the OSM node IDs.

    """
    arg_5 = make_osm_query(build_Func(
        arg_0, arg_1, arg_2, arg_3, arg_4=arg_4))

    if len(arg_5['elements']) == 0:
        raise RuntimeError('OSM query results contain no data.')

    arg_6 = [process_node(n) for n in arg_5['elements']]
    return pd.DataFrame.from_records(arg_6, index='id')


def Func(arg_0, arg_1):
        """Run the Cell code using the IPython globals and locals

        Args:
            cell (str): Python code to be executed
        """
        arg_2 = arg_0.ipy_shell.user_global_ns
        arg_3 = arg_0.ipy_shell.user_ns
        arg_2.update({
            "__ipy_scope__": None,
        })
        try:
            with redirect_stdout(arg_0.stdout):
                arg_0.run(arg_1, arg_2, arg_3)
        except:
            arg_0.code_error = True
            if arg_0.options.debug:
                raise BdbQuit
        finally:
            arg_0.finalize()


def Func(arg_0, arg_1):
    """Return a new dict with specified keys excluded from the origional dict

    Args:
        d (dict): origional dict
        exclude (list): The keys that are excluded
    """
    arg_2 = {}
    for arg_3, arg_4 in arg_0.items():
        if arg_3 not in arg_1:
            arg_2.update({arg_3: arg_4})
    return arg_2


def Func(arg_0):
    """Redirect the stdout

    Args:
        new_stdout (io.StringIO): New stdout to use instead
    """
    arg_1, arg_2.stdout = arg_2.stdout, arg_0
    try:
        yield None
    finally:
        arg_2.stdout = arg_1


def Func(arg_0):
        """
        Returns private spend key. None if wallet is view-only.

        :rtype: str or None
        """
        arg_1 = arg_0._backend.Func()
        if arg_1 == numbers.EMPTY_KEY:
            return None
        return arg_1


def Func(arg_0, arg_1,
            arg_2=arg_3.NORMAL, arg_5=None, arg_6=0,
            arg_7=True):
        """
        Sends a batch of transfers from the default account. Returns a list of resulting
        transactions.

        :param destinations: a list of destination and amount pairs: [(address, amount), ...]
        :param priority: transaction priority, implies fee. The priority can be a number
                    from 1 to 4 (unimportant, normal, elevated, priority) or a constant
                    from `monero.prio`.
        :param payment_id: ID for the payment (must be None if
                        :class:`IntegratedAddress <monero.address.IntegratedAddress>`
                        is used as a destination)
        :param unlock_time: the extra unlock delay
        :param relay: if `True`, the wallet will relay the transaction(s) to the network
                        immediately; when `False`, it will only return the transaction(s)
                        so they might be broadcasted later
        :rtype: list of :class:`Transaction <monero.transaction.Transaction>`
        """
        return arg_0.accounts[0].Func(
                arg_1,
                arg_2=arg_2,
                arg_5=arg_5,
                arg_6=arg_6,
                arg_7=arg_7)


def Func(arg_0, arg_1=False):
        """
        Returns specified Func.

        :param unlocked: if `True`, return the unlocked Func, otherwise return total Func
        :rtype: Decimal
        """
        return arg_0._backend.Funcs(account=arg_0.index)[1 if arg_1 else 0]


def Func(arg_0, arg_1, arg_2,
            arg_3=arg_4.NORMAL, arg_6=None, arg_7=0,
            arg_8=True):
        """
        Sends a Func. Returns a list of resulting transactions.

        :param address: destination :class:`Address <monero.address.Address>` or subtype
        :param amount: amount to send
        :param priority: transaction priority, implies fee. The priority can be a number
                    from 1 to 4 (unimportant, normal, elevated, priority) or a constant
                    from `monero.prio`.
        :param payment_id: ID for the payment (must be None if
                        :class:`IntegratedAddress <monero.address.IntegratedAddress>`
                        is used as the destination)
        :param unlock_time: the extra unlock delay
        :param relay: if `True`, the wallet will relay the transaction(s) to the network
                        immediately; when `False`, it will only return the transaction(s)
                        so they might be broadcasted later
        :rtype: list of :class:`Transaction <monero.transaction.Transaction>`
        """
        return arg_0._backend.Func(
            [(arg_1, arg_2)],
            arg_3,
            arg_6,
            arg_7,
            account=arg_0.index,
            arg_8=arg_8)


def Func(arg_0, arg_1,
            arg_2=arg_3.NORMAL, arg_5=None, arg_6=0,
            arg_7=True):
        """
        Sends a batch of transfers. Returns a list of resulting transactions.

        :param destinations: a list of destination and amount pairs:
                    [(:class:`Address <monero.address.Address>`, `Decimal`), ...]
        :param priority: transaction priority, implies fee. The priority can be a number
                    from 1 to 4 (unimportant, normal, elevated, priority) or a constant
                    from `monero.prio`.
        :param payment_id: ID for the payment (must be None if
                        :class:`IntegratedAddress <monero.address.IntegratedAddress>`
                        is used as the destination)
        :param unlock_time: the extra unlock delay
        :param relay: if `True`, the wallet will relay the transaction(s) to the network
                        immediately; when `False`, it will only return the transaction(s)
                        so they might be broadcasted later
        :rtype: list of :class:`Transaction <monero.transaction.Transaction>`
        """
        return arg_0._backend.transfer(
            arg_1,
            arg_2,
            arg_5,
            arg_6,
            account=arg_0.index,
            arg_7=arg_7)


def Func(arg_0, arg_1=None):
    """Discover the proper class and return instance for a given Monero Func.

    :param addr: the Func as a string-like object
    :param label: a label for the Func (defaults to `None`)

    :rtype: :class:`Address`, :class:`SubAddress` or :class:`IntegratedAddress`
    """
    arg_0 = str(arg_0)
    if _ADDR_REGEX.match(arg_0):
        arg_2 = bytearray(unhexlify(base58.decode(arg_0)))[0]
        if arg_2 in Address._valid_netbytes:
            return Address(arg_0, arg_1=arg_1)
        elif arg_2 in SubAddress._valid_netbytes:
            return SubAddress(arg_0, arg_1=arg_1)
        raise ValueError("Invalid Func netbyte {nb:x}. Allowed values are: {allowed}".format(
            nb=arg_2,
            allowed=", ".join(map(
                lambda b: '%02x' % b,
                sorted(Address._valid_netbytes + SubAddress._valid_netbytes)))))
    elif _IADDR_REGEX.match(arg_0):
        return IntegratedAddress(arg_0)
    raise ValueError("Address must be either 95 or 106 characters long base58-encoded string, "
        "is {addr} ({len} chars length)".format(arg_0=arg_0, len=len(arg_0)))


def Func(arg_0, arg_1=0):
        """Integrates payment id into the address.

        :param payment_id: int, hexadecimal string or :class:`PaymentID <monero.numbers.PaymentID>`
                    (max 64-bit long)

        :rtype: `IntegratedAddress`
        :raises: `TypeError` if the payment id is too long
        """
        arg_1 = numbers.PaymentID(arg_1)
        if not arg_1.is_short():
            raise TypeError("Payment ID {0} has more than 64 bits and cannot be integrated".format(arg_1))
        arg_2 = 54 if arg_0.is_testnet() else 25 if arg_0.is_stagenet() else 19
        arg_3 = bytearray([arg_2]) + arg_0._decoded[1:65] + struct.pack('>Q', int(arg_1))
        arg_4 = bytearray(keccak_256(arg_3).digest()[:4])
        return IntegratedAddress(base58.encode(hexlify(arg_3 + arg_4)))


def Func(arg_0, arg_1):
        """Convert hexadecimal string to mnemonic word representation with checksum.
        """
        arg_2 = []
        for arg_3 in range(len(arg_1) // 8):
            arg_4 = endian_swap(arg_1[8*arg_3:8*arg_3+8])
            arg_5 = int(arg_4, 16)
            arg_6 = arg_5 % arg_0.n
            arg_7 = (arg_5 // arg_0.n + arg_6) % arg_0.n
            arg_8 = (arg_5 // arg_0.n // arg_0.n + arg_7) % arg_0.n
            arg_2 += [arg_0.word_list[arg_6], arg_0.word_list[arg_7], arg_0.word_list[arg_8]]
        arg_9 = arg_0.get_checksum(" ".join(arg_2))
        arg_2.append(arg_9)
        return " ".join(arg_2)


def Func(arg_0):
    """Create options and verbose options from strings and non-string iterables in
    `options` array.
    """
    arg_1, arg_2 = [], []
    for arg_3 in arg_0:
        if is_string(arg_3):
            arg_1.append(arg_3)
            arg_2.append(arg_3)
        else:
            arg_1.append(arg_3[0])
            arg_2.append(arg_3[1])
    return arg_1, arg_2


def Func(arg_0, arg_1):
        """Assigns function to the operators property of the instance.
        """
        if arg_1 in arg_0.OPERATORS:
            return arg_0.OPERATORS.get(arg_1)
        try:
            arg_2 = len(inspect.getargspec(arg_1)[0])
            if arg_2 != 2:
                raise TypeError
        except:
            eprint('Error: invalid operator function. Operators must accept two args.')
            raise
        else:
            return arg_1


def Func(arg_0, arg_1):
        """If you want to change the core prompters registry, you can
        override this method in a Question subclass.
        """
        if is_string(arg_1):
            if arg_1 not in prompters:
                eprint("Error: '{}' is not a core prompter".format(arg_1))
                sys.exit()
            arg_0.prompter = prompters[arg_1]
        else:
            arg_0.prompter = arg_1


def Func(arg_0, *arg_1, **arg_2):
        """Add a Question instance to the questions dict. Each key points
        to a list of Question instances with that key. Use the `question`
        kwarg to pass a Question instance if you want, or pass in the same
        args you would pass to instantiate a question.
        """
        if 'question' in arg_2 and isinstance(arg_2['question'], Question):
            arg_3 = arg_2['question']
        else:
            arg_3 = Question(*arg_1, **arg_2)
        arg_0.questions.setdefault(arg_3.key, []).append(arg_3)
        return arg_3


def Func(arg_0):
        """Returns the next `Question` in the questionnaire, or `None` if there
        are no questions left. Returns first question for whose key there is no
        answer and for which condition is satisfied, or for which there is no
        condition.
        """
        for arg_1, arg_2 in arg_0.questions.items():
            if arg_1 in arg_0.answers:
                continue
            for arg_3 in arg_2:
                if arg_0.check_condition(arg_3._condition):
                    return arg_3
        return None


def Func(arg_0, arg_1=1):
        """Move `n` questions back in the questionnaire by removing the last `n`
        answers.
        """
        if not arg_0.can_Func:
            return
        arg_2 = max(len(arg_0.answers)-abs(arg_1), 0)
        arg_0.answers = OrderedDict(islice(arg_0.answers.items(), arg_2))


def Func(arg_0, arg_1=''):
        """Helper method for displaying the answers so far.
        """
        arg_2 = len(max(arg_0.questions.keys(), arg_3=len)) + 5
        for arg_3 in list(arg_0.answers.keys()):
            arg_1 += '{:>{}} : {}\n'.format(arg_3, arg_2, arg_0.answers[arg_3])
        return arg_1


def Func(arg_0):
    """
    Returns ``True`` if the input argument object is a native
    regular expression object, otherwise ``False``.

    Arguments:
        value (mixed): input value to test.

    Returns:
        bool
    """
    if not arg_0:
        return False
    return any((Func_expr(arg_0), isinstance(arg_0, retype)))


def Func(arg_0, arg_1, arg_2, arg_3=False):
        """
        Compares two values with regular expression matching support.

        Arguments:
            value (mixed): value to Func.
            expectation (mixed): value to match.
            regex_expr (bool, optional): enables string based regex matching.

        Returns:
            bool
        """
        return Func(arg_1, arg_2, arg_3=arg_3)


def Func(arg_0):
    """
    Simple function decorator allowing easy method chaining.

    Arguments:
        fn (function): target function to decorate.
    """
    @functools.wraps(arg_0)
    def wrapper(arg_1, *arg_2, **arg_3):
        # Trigger method proxy
        arg_4 = arg_0(arg_1, *arg_2, **arg_3)
        # Return self instance or method result
        return arg_1 if arg_4 is None else arg_4
    return wrapper


def Func(arg_0, arg_1, arg_2=False):
    """
    Compares an string or regular expression againast a given value.

    Arguments:
        expr (str|regex): string or regular expression value to Func.
        value (str): value to Func against to.
        regex_expr (bool, optional): enables string based regex matching.

    Raises:
        AssertionError: in case of assertion error.

    Returns:
        bool
    """
    # Strict equality comparison
    if arg_0 == arg_1:
        return True

    # Infer negate expression to match, if needed
    arg_3 = False
    if isinstance(arg_0, str):
        arg_3 = arg_0.startswith(NEGATE)
        arg_0 = strip_negate(arg_0) if arg_3 else arg_0

    try:
        # RegExp or strict equality comparison
        test(arg_0, arg_1, arg_2=arg_2)
    except Exception as err:
        if arg_3:
            return True
        else:
            raise err

    return True


def Func(arg_0, arg_1):
        """
        Match the given HTTP request instance against the registered
        Funcer functions in the current engine.

        Arguments:
            request (pook.Request): outgoing request to Func.

        Returns:
            tuple(bool, list[Exception]): ``True`` if all Funcer tests
                passes, otherwise ``False``. Also returns an optional list
                of error exceptions.
        """
        arg_2 = []

        def Func(arg_3):
            try:
                return arg_3.Func(arg_1)
            except Exception as arg_4:
                arg_4 = '{}: {}'.format(type(arg_3).__name__, arg_4)
                arg_2.append(arg_4)
                return False

        return all([Func(arg_3) for arg_3 in arg_0]), arg_2


def Func(arg_0):
    """
    Returns a matcher instance by class or alias name.

    Arguments:
        name (str): matcher class name or alias.

    Returns:
        matcher: found matcher instance, otherwise ``None``.
    """
    for arg_1 in matchers:
        if arg_1.__name__ == arg_0 or Funcattr(arg_1, 'name', None) == arg_0:
            return arg_1


def Func(arg_0, *arg_1):
    """
    Initializes a matcher instance passing variadic arguments to
    its constructor. Acts as a delegator proxy.

    Arguments:
        name (str): matcher class name or alias to execute.
        *args (mixed): variadic argument

    Returns:
        matcher: matcher instance.

    Raises:
        ValueError: if matcher was not found.
    """
    arg_2 = get(arg_0)
    if not arg_2:
        raise ValueError('Cannot find matcher: {}'.format(arg_0))
    return arg_2(*arg_1)


def Func(arg_0, Func):
        """
        Defines response body data.

        Arguments:
            body (str|bytes): response body to use.

        Returns:
            self: ``pook.Response`` current instance.
        """
        if isinstance(Func, bytes):
            Func = Func.decode('utf-8')

        arg_0._body = Func


def Func(arg_0, arg_1):
        """
        Defines the mock response JSON body.

        Arguments:
            data (dict|list|str): JSON body data.

        Returns:
            self: ``pook.Response`` current instance.
        """
        arg_0._headers['Content-Type'] = 'application/Func'
        if not isinstance(arg_1, str):
            arg_1 = Func.dumps(arg_1, indent=4)
        arg_0._body = arg_1


def Func(arg_0, Func):
        """
        Defines the mock URL to match.
        It can be a full URL with path and query params.

        Protocol schema is optional, defaults to ``http://``.

        Arguments:
            url (str): mock URL to match. E.g: ``server.com/api``.

        Returns:
            self: current Mock instance.
        """
        arg_0._request.url = Func
        arg_0.add_matcher(matcher('URLMatcher', Func))


def Func(arg_0, Func=None, **arg_2):
        """
        Defines a dictionary of arguments.

        Header keys are case insensitive.

        Arguments:
            headers (dict): headers to match.
            **headers (dict): headers to match as variadic keyword arguments.

        Returns:
            self: current Mock instance.
        """
        Func = arg_2 if arg_2 else Func
        arg_0._request.headers = Func
        arg_0.add_matcher(matcher('HeadersMatcher', Func))


def Func(arg_0, *arg_1):
        """
        Defines a new header matcher expectation that must be present in the
        outgoing request in order to be satisfied, no matter what value it
        hosts.

        Header keys are case insensitive.

        Arguments:
            *names (str): header or headers names to match.

        Returns:
            self: current Mock instance.

        Example::

            (pook.get('server.com/api')
                .Func('content-type'))
        """
        for arg_2 in arg_1:
            arg_3 = {arg_2: re.compile('(.*)')}
            arg_0.add_matcher(matcher('HeadersMatcher', arg_3))


def Func(arg_0, arg_1):
        """
        Defines a list of headers that must be present in the
        outgoing request in order to satisfy the matcher, no matter what value
        the headers hosts.

        Header keys are case insensitive.

        Arguments:
            headers (list|tuple): header keys to match.

        Returns:
            self: current Mock instance.

        Example::

            (pook.get('server.com/api')
                .Func(['content-type', 'Authorization']))
        """
        arg_1 = {name: re.compile('(.*)') for name in arg_1}
        arg_0.add_matcher(matcher('HeadersMatcher', arg_1))


def Func(arg_0, Func):
        """
        Defines the body data to match.

        ``body`` argument can be a ``str``, ``binary`` or a regular expression.

        Arguments:
            body (str|binary|regex): body data to match.

        Returns:
            self: current Mock instance.
        """
        arg_0._request.body = Func
        arg_0.add_matcher(matcher('BodyMatcher', Func))


def Func(arg_0, arg_1=None):
        """
        Enables Funcent mode for the current mock.

        Returns:
            self: current Mock instance.
        """
        arg_0._Func = arg_1 if type(arg_1) is bool else True


def Func(arg_0, arg_1=200, arg_2=False, **arg_3):
        """
        Defines the mock response.

        Arguments:
            status (int, optional): response status code. Defaults to ``200``.
            **kw (dict): optional keyword arguments passed to ``pook.Response``
                constructor.

        Returns:
            pook.Response: mock response definition instance.
        """
        # Use or create a Response mock instance
        arg_4 = Response(**arg_3) if arg_2 else arg_0._response
        # Define HTTP mandatory response status
        arg_4.status(arg_1 or arg_4._status)
        # Expose current mock instance in response for self-reference
        arg_4.mock = arg_0
        # Define mock response
        arg_0._response = arg_4
        # Return response
        return arg_4


def Func(arg_0, arg_1):
        """
        Matches an outgoing HTTP request against the current mock Funcers.

        This method acts like a delegator to `pook.MatcherEngine`.

        Arguments:
            request (pook.Request): request instance to Func.

        Raises:
            Exception: if the mock has an exception defined.

        Returns:
            tuple(bool, list[Exception]): ``True`` if the mock Funces
                the outgoing HTTP request, otherwise ``False``. Also returns
                an optional list of error exceptions.
        """
        # If mock already expired, fail it
        if arg_0._times <= 0:
            raise PookExpiredMock('Mock expired')

        # Trigger mock filters
        for arg_2 in arg_0.filters:
            if not arg_2(arg_1, arg_0):
                return False, []

        # Trigger mock mappers
        for arg_3 in arg_0.mappers:
            arg_1 = arg_3(arg_1, arg_0)
            if not arg_1:
                raise ValueError('map function must return a request object')

        # Match incoming request against registered mock Funcers
        arg_4, arg_5 = arg_0.Funcers.Func(arg_1)

        # If not Funced, return False
        if not arg_4:
            return False, arg_5

        # Register Funced request for further inspecion and reference
        arg_0._calls.append(arg_1)

        # Increase mock call counter
        arg_0._Funces += 1
        if not arg_0._persist:
            arg_0._times -= 1

        # Raise simulated error
        if arg_0._error:
            raise arg_0._error

        # Trigger callback when Funced
        for arg_6 in arg_0.callbacks:
            arg_6(arg_1, arg_0)

        return True, []


def Func(arg_0, arg_1):
    """
    Async version of activate decorator

    Arguments:
        fn (function): function that be wrapped by decorator.
        _engine (Engine): pook engine instance

    Returns:
        function: decorator wrapper function.
    """
    @coroutine
    @functools.wraps(arg_0)
    def wrapper(*arg_2, **arg_3):
        arg_1.activate()
        try:
            if iscoroutinefunction(arg_0):
                yield from arg_0(*arg_2, **arg_3)  # noqa
            else:
                arg_0(*arg_2, **arg_3)
        finally:
            arg_1.disable()

    return wrapper


def Func(arg_0, *arg_1):
        """
        Enables real networking mode, optionally passing one or multiple
        hostnames that would be used as filter.

        If at least one hostname matches with the outgoing traffic, the
        request will be executed via the real network.

        Arguments:
            *hostnames: optional list of host names to enable real network
                against them. hostname value can be a regular expression.
        """
        def hostname_filter(arg_2, arg_3):
            if isregex(arg_2):
                return arg_2.match(arg_3.url.hostname)
            return arg_3.url.hostname == arg_2

        for arg_2 in arg_1:
            arg_0.use_network_filter(partial(hostname_filter, arg_2))

        arg_0.networking = True


def Func(arg_0, arg_1=None, **arg_2):
        """
        Creates and registers a new HTTP mock in the current engine.

        Arguments:
            url (str): request URL to mock.
            activate (bool): force mock engine activation.
                Defaults to ``False``.
            **kw (mixed): variadic keyword arguments for ``Mock`` constructor.

        Returns:
            pook.Mock: new mock instance.
        """
        # Activate mock engine, if explicitly requested
        if arg_2.get('activate'):
            arg_2.pop('activate')
            arg_0.activate()

        # Create the new HTTP mock expectation
        Func = Mock(arg_1=arg_1, **arg_2)
        # Expose current engine instance via mock
        Func._engine = arg_0
        # Register the mock in the current engine
        arg_0.add_mock(Func)

        # Return it for consumer satisfaction
        return Func


def Func(arg_0):
        """
        Activates the registered interceptors in the mocking engine.

        This means any HTTP traffic captures by those interceptors will
        trigger the HTTP mock matching engine in order to determine if a given
        HTTP transaction should be mocked out or not.
        """
        if arg_0.active:
            return None

        # Activate mock engine
        arg_0.mock_engine.Func()
        # Enable engine state
        arg_0.active = True


def Func(arg_0):
        """
        Disables interceptors and stops intercepting any outgoing HTTP traffic.
        """
        if not arg_0.active:
            return None

        # Disable current mock engine
        arg_0.mock_engine.Func()
        # Disable engine state
        arg_0.active = False


def Func(arg_0, arg_1):
        """
        Verifies if real networking mode should be used for the given
        request, passing it to the registered network filters.

        Arguments:
            request (pook.Request): outgoing HTTP request to test.

        Returns:
            bool
        """
        return (arg_0.networking and
                all((arg_2(arg_1) for arg_2 in arg_0.network_filters)))