# Buggy code
def dict_learning(
    X,
    n_components,
    alpha,
    max_iter=100,
    tol=1e-8,
    method="lars",
    n_jobs=None,
    dict_init=None,
    code_init=None,
    callback=None,
    verbose=False,
    random_state=None,
    return_n_iter=False,
    positive_dict=False,
    positive_code=False,
):
    """Solves a dictionary learning matrix factorization problem.

    Finds the best dictionary and the corresponding sparse code for
    approximating the data matrix X by solving::

        (U^*, V^*) = argmin 0.5 || X - U V ||_2^2 + alpha * || U ||_1
                     (U,V)
                    with || V_k ||_2 = 1 for all  0 <= k < n_components

    where V is the dictionary and U is the sparse code.

    Read more in the :ref:`User Guide <DictionaryLearning>`.

    Parameters
    ----------
    X : array of shape (n_samples, n_features)
        Data matrix.

    n_components : int,
        Number of dictionary atoms to extract.

    alpha : int,
        Sparsity controlling parameter.

    max_iter : int,
        Maximum number of iterations to perform.

    tol : float,
        Tolerance for the stopping condition.

    method : {'lars', 'cd'}
        lars: uses the least angle regression method to solve the lasso problem
        (linear_model.lars_path)
        cd: uses the coordinate descent method to compute the
        Lasso solution (linear_model.Lasso). Lars will be faster if
        the estimated components are sparse.

    n_jobs : int,
        Number of parallel jobs to run, or -1 to autodetect.

    dict_init : array of shape (n_components, n_features),
        Initial value for the dictionary for warm restart scenarios.

    code_init : array of shape (n_samples, n_components),
        Initial value for the sparse code for warm restart scenarios.

    callback : callable or None, optional (default: None)
        Callable that gets invoked every five iterations

    verbose : bool, optional (default: False)
        To control the verbosity of the procedure.

    random_state : int, RandomState instance or None, optional (default=None)
        If int, random_state is the seed used by the random number generator;
        If RandomState instance, random_state is the random number generator;
        If None, the random number generator is the RandomState instance used
        by `np.random`.

    return_n_iter : bool
        Whether or not to return the number of iterations.

    positive_dict : bool
        Whether to enforce positivity when finding the dictionary.

        .. versionadded:: 0.20

    positive_code : bool
        Whether to enforce positivity when finding the code.

        .. versionadded:: 0.20

    Returns
    -------
    code : array of shape (n_samples, n_components)
        The sparse code factor in the matrix factorization.

    dictionary : array of shape (n_components, n_features),
        The dictionary factor in the matrix factorization.

    errors : array
        Vector of errors at each iteration.

    n_iter : int
        Number of iterations run. Returned only if `return_n_iter` is
        set to True.

    See also
    --------
    dict_learning_online
    DictionaryLearning
    MiniBatchDictionaryLearning
    SparsePCA
    MiniBatchSparsePCA
    """
    if method not in ("lars", "cd"):
        raise ValueError("Coding method %r not supported as a fit algorithm." % method)
    method = "lasso_" + method

    t0 = time.time()
    # Avoid integer division problems
    alpha = float(alpha)
    random_state = check_random_state(random_state)

    # Init the code and the dictionary with SVD of Y
    if code_init is not None and dict_init is not None:
        code = np.array(code_init, order="F")
        # Don't copy V, it will happen below
        dictionary = dict_init
    else:
        code, S, dictionary = linalg.svd(X, full_matrices=False)
        dictionary = S[:, np.newaxis] * dictionary
    r = len(dictionary)
    if n_components <= r:  # True even if n_components=None
        code = code[:, :n_components]
        dictionary = dictionary[:n_components, :]
    else:
        code = np.c_[code, np.zeros((len(code), n_components - r))]
        dictionary = np.r_[
            dictionary, np.zeros((n_components - r, dictionary.shape[1]))
        ]

    # Fortran-order dict, as we are going to access its row vectors
    dictionary = np.array(dictionary, order="F")

    residuals = 0

    errors = []
    current_cost = np.nan

    if verbose == 1:
        print("[dict_learning]", end=" ")

    # If max_iter is 0, number of iterations returned should be zero
    ii = -1

    for ii in range(max_iter):
        dt = time.time() - t0
        if verbose == 1:
            sys.stdout.write(".")
            sys.stdout.flush()
        elif verbose:
            print(
                "Iteration % 3i "
                "(elapsed time: % 3is, % 4.1fmn, current cost % 7.3f)"
                % (ii, dt, dt / 60, current_cost)
            )

        # Update code
        code = sparse_encode(
            X,
            dictionary,
            algorithm=method,
            alpha=alpha,
            init=code,
            n_jobs=n_jobs,
            positive=positive_code,
        )
        # Update dictionary
        dictionary, residuals = _update_dict(
            dictionary.T,
            X.T,
            code.T,
            verbose=verbose,
            return_r2=True,
            random_state=random_state,
            positive=positive_dict,
        )
        dictionary = dictionary.T

        # Cost function
        current_cost = 0.5 * residuals + alpha * np.sum(np.abs(code))
        errors.append(current_cost)

        if ii > 0:
            dE = errors[-2] - errors[-1]
            # assert(dE >= -tol * errors[-1])
            if dE < tol * errors[-1]:
                if verbose == 1:
                    # A line return
                    print("")
                elif verbose:
                    print("--- Convergence reached after %d iterations" % ii)
                break
        if ii % 5 == 0 and callback is not None:
            callback(locals())

    if return_n_iter:
        return code, dictionary, errors, ii + 1
    else:
        return code, dictionary, errors


# Traceback (ValueError)
Unexpected failing examples:
/home/circleci/project/examples/cluster/plot_feature_agglomeration_vs_univariate_selection.py failed leaving traceback:
Traceback (most recent call last):
File "/home/circleci/project/examples/cluster/plot_feature_agglomeration_vs_univariate_selection.py", line 75, in <module>
clf.fit(X, y)  # set the best parameters
File "/home/circleci/project/sklearn/model_selection/_search.py", line 663, in fit
cv.split(X, y, groups)))
File "/home/circleci/project/sklearn/externals/joblib/parallel.py", line 981, in __call__
if self.dispatch_one_batch(iterator):
File "/home/circleci/project/sklearn/externals/joblib/parallel.py", line 818, in dispatch_one_batch
self._pickle_cache)
File "/home/circleci/project/sklearn/externals/joblib/parallel.py", line 253, in __init__
self.items = list(iterator_slice)
File "/home/circleci/project/sklearn/model_selection/_search.py", line 662, in <genexpr>
for parameters, (train, test) in product(candidate_params,
File "/home/circleci/project/sklearn/base.py", line 62, in clone
new_object_params[name] = clone(param, safe=False)
File "/home/circleci/project/sklearn/base.py", line 50, in clone
return estimator_type([clone(e, safe=safe) for e in estimator])
File "/home/circleci/project/sklearn/base.py", line 50, in <listcomp>
return estimator_type([clone(e, safe=safe) for e in estimator])
File "/home/circleci/project/sklearn/base.py", line 50, in clone
return estimator_type([clone(e, safe=safe) for e in estimator])
File "/home/circleci/project/sklearn/base.py", line 50, in <listcomp>
return estimator_type([clone(e, safe=safe) for e in estimator])
File "/home/circleci/project/sklearn/base.py", line 62, in clone
new_object_params[name] = clone(param, safe=False)
File "/home/circleci/project/sklearn/base.py", line 53, in clone
return copy.deepcopy(estimator)
File "/home/circleci/miniconda/envs/testenv/lib/python3.6/copy.py", line 180, in deepcopy
y = _reconstruct(x, memo, *rv)
File "/home/circleci/miniconda/envs/testenv/lib/python3.6/copy.py", line 274, in _reconstruct
y = func(*args)
File "/home/circleci/project/sklearn/externals/joblib/memory.py", line 830, in __init__
location, cachedir))
ValueError: You set both "location='/tmp/tmp1v2mgts1' and "cachedir=False". 'cachedir' has been deprecated in version 0.12 and will be removed in version 0.14.
Please only set "location='/tmp/tmp1v2mgts1'"


/home/circleci/project/examples/compose/plot_compare_reduction.py failed leaving traceback:
Traceback (most recent call last):
File "/home/circleci/project/examples/compose/plot_compare_reduction.py", line 119, in <module>
grid.fit(digits.data, digits.target)
File "/home/circleci/project/sklearn/model_selection/_search.py", line 663, in fit
cv.split(X, y, groups)))
File "/home/circleci/project/sklearn/externals/joblib/parallel.py", line 981, in __call__
if self.dispatch_one_batch(iterator):
File "/home/circleci/project/sklearn/externals/joblib/parallel.py", line 818, in dispatch_one_batch
self._pickle_cache)
File "/home/circleci/project/sklearn/externals/joblib/parallel.py", line 253, in __init__
self.items = list(iterator_slice)
File "/home/circleci/project/sklearn/model_selection/_search.py", line 662, in <genexpr>
for parameters, (train, test) in product(candidate_params,
File "/home/circleci/project/sklearn/base.py", line 62, in clone
new_object_params[name] = clone(param, safe=False)
File "/home/circleci/project/sklearn/base.py", line 53, in clone
return copy.deepcopy(estimator)
File "/home/circleci/miniconda/envs/testenv/lib/python3.6/copy.py", line 180, in deepcopy
y = _reconstruct(x, memo, *rv)
File "/home/circleci/miniconda/envs/testenv/lib/python3.6/copy.py", line 274, in _reconstruct
y = func(*args)
File "/home/circleci/project/sklearn/externals/joblib/memory.py", line 830, in __init__
location, cachedir))
ValueError: You set both "location='/tmp/tmpa408j1cz' and "cachedir=False". 'cachedir' has been deprecated in version 0.12 and will be removed in version 0.14.
Please only set "location='/tmp/tmpa408j1cz'"

# Fixed code
def dict_learning(
    X,
    n_components,
    alpha,
    max_iter=100,
    tol=1e-8,
    method="lars",
    n_jobs=None,
    dict_init=None,
    code_init=None,
    callback=None,
    verbose=False,
    random_state=None,
    return_n_iter=False,
    positive_dict=False,
    positive_code=False,
):
    """Solves a dictionary learning matrix factorization problem.

    Finds the best dictionary and the corresponding sparse code for
    approximating the data matrix X by solving::

        (U^*, V^*) = argmin 0.5 || X - U V ||_2^2 + alpha * || U ||_1
                     (U,V)
                    with || V_k ||_2 = 1 for all  0 <= k < n_components

    where V is the dictionary and U is the sparse code.

    Read more in the :ref:`User Guide <DictionaryLearning>`.

    Parameters
    ----------
    X : array of shape (n_samples, n_features)
        Data matrix.

    n_components : int,
        Number of dictionary atoms to extract.

    alpha : int,
        Sparsity controlling parameter.

    max_iter : int,
        Maximum number of iterations to perform.

    tol : float,
        Tolerance for the stopping condition.

    method : {'lars', 'cd'}
        lars: uses the least angle regression method to solve the lasso problem
        (linear_model.lars_path)
        cd: uses the coordinate descent method to compute the
        Lasso solution (linear_model.Lasso). Lars will be faster if
        the estimated components are sparse.

    n_jobs : int or None, optional (default=None)
        Number of parallel jobs to run.
        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
        ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
        for more details.

    dict_init : array of shape (n_components, n_features),
        Initial value for the dictionary for warm restart scenarios.

    code_init : array of shape (n_samples, n_components),
        Initial value for the sparse code for warm restart scenarios.

    callback : callable or None, optional (default: None)
        Callable that gets invoked every five iterations

    verbose : bool, optional (default: False)
        To control the verbosity of the procedure.

    random_state : int, RandomState instance or None, optional (default=None)
        If int, random_state is the seed used by the random number generator;
        If RandomState instance, random_state is the random number generator;
        If None, the random number generator is the RandomState instance used
        by `np.random`.

    return_n_iter : bool
        Whether or not to return the number of iterations.

    positive_dict : bool
        Whether to enforce positivity when finding the dictionary.

        .. versionadded:: 0.20

    positive_code : bool
        Whether to enforce positivity when finding the code.

        .. versionadded:: 0.20

    Returns
    -------
    code : array of shape (n_samples, n_components)
        The sparse code factor in the matrix factorization.

    dictionary : array of shape (n_components, n_features),
        The dictionary factor in the matrix factorization.

    errors : array
        Vector of errors at each iteration.

    n_iter : int
        Number of iterations run. Returned only if `return_n_iter` is
        set to True.

    See also
    --------
    dict_learning_online
    DictionaryLearning
    MiniBatchDictionaryLearning
    SparsePCA
    MiniBatchSparsePCA
    """
    if method not in ("lars", "cd"):
        raise ValueError("Coding method %r not supported as a fit algorithm." % method)
    method = "lasso_" + method

    t0 = time.time()
    # Avoid integer division problems
    alpha = float(alpha)
    random_state = check_random_state(random_state)

    # Init the code and the dictionary with SVD of Y
    if code_init is not None and dict_init is not None:
        code = np.array(code_init, order="F")
        # Don't copy V, it will happen below
        dictionary = dict_init
    else:
        code, S, dictionary = linalg.svd(X, full_matrices=False)
        dictionary = S[:, np.newaxis] * dictionary
    r = len(dictionary)
    if n_components <= r:  # True even if n_components=None
        code = code[:, :n_components]
        dictionary = dictionary[:n_components, :]
    else:
        code = np.c_[code, np.zeros((len(code), n_components - r))]
        dictionary = np.r_[
            dictionary, np.zeros((n_components - r, dictionary.shape[1]))
        ]

    # Fortran-order dict, as we are going to access its row vectors
    dictionary = np.array(dictionary, order="F")

    residuals = 0

    errors = []
    current_cost = np.nan

    if verbose == 1:
        print("[dict_learning]", end=" ")

    # If max_iter is 0, number of iterations returned should be zero
    ii = -1

    for ii in range(max_iter):
        dt = time.time() - t0
        if verbose == 1:
            sys.stdout.write(".")
            sys.stdout.flush()
        elif verbose:
            print(
                "Iteration % 3i "
                "(elapsed time: % 3is, % 4.1fmn, current cost % 7.3f)"
                % (ii, dt, dt / 60, current_cost)
            )

        # Update code
        code = sparse_encode(
            X,
            dictionary,
            algorithm=method,
            alpha=alpha,
            init=code,
            n_jobs=n_jobs,
            positive=positive_code,
        )
        # Update dictionary
        dictionary, residuals = _update_dict(
            dictionary.T,
            X.T,
            code.T,
            verbose=verbose,
            return_r2=True,
            random_state=random_state,
            positive=positive_dict,
        )
        dictionary = dictionary.T

        # Cost function
        current_cost = 0.5 * residuals + alpha * np.sum(np.abs(code))
        errors.append(current_cost)

        if ii > 0:
            dE = errors[-2] - errors[-1]
            # assert(dE >= -tol * errors[-1])
            if dE < tol * errors[-1]:
                if verbose == 1:
                    # A line return
                    print("")
                elif verbose:
                    print("--- Convergence reached after %d iterations" % ii)
                break
        if ii % 5 == 0 and callback is not None:
            callback(locals())

    if return_n_iter:
        return code, dictionary, errors, ii + 1
    else:
        return code, dictionary, errors