gurudesh/pytracebugs huggingface dataset:
# Buggy code
def diagonal(self, k=0):
    rows, cols = self.shape
    if k <= -rows or k >= cols:
        raise ValueError("k exceeds matrix dimensions")
    (idx,) = np.nonzero(self.offsets == k)
    first_col, last_col = max(0, k), min(rows + k, cols)
    if idx.size == 0:
        return np.zeros(last_col - first_col, dtype=self.data.dtype)
    return self.data[idx[0], first_col:last_col]


# Traceback (ValueError)
(0,)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-44-106e34b7d64c> in <module>
2 print(np.diag(m.todense()).shape)
3
----> 4 m.diagonal()

~/.pyenv/versions/3.6.9/lib/python3.6/site-packages/scipy/sparse/compressed.py in diagonal(self, k)
531         rows, cols = self.shape
532         if k <= -rows or k >= cols:
--> 533             raise ValueError("k exceeds matrix dimensions")
534         fn = getattr(_sparsetools, self.format + "_diagonal")
535         y = np.empty(min(rows + min(k, 0), cols - max(k, 0)),

ValueError: k exceeds matrix dimensions

# Fixed code
def diagonal(self, k=0):
    rows, cols = self.shape
    if k <= -rows or k >= cols:
        return np.empty(0, dtype=self.data.dtype)
    (idx,) = np.nonzero(self.offsets == k)
    first_col, last_col = max(0, k), min(rows + k, cols)
    if idx.size == 0:
        return np.zeros(last_col - first_col, dtype=self.data.dtype)
    return self.data[idx[0], first_col:last_col]
# Buggy code
def check_tolerance(ftol, xtol, gtol):
    def check(tol, name):
        if tol is None:
            tol = 0
        elif tol < EPS:
            warn(
                "Setting `{}` below the machine epsilon ({:.2e}) effectively "
                "disables the corresponding termination condition.".format(name, EPS)
            )
        return tol

    ftol = check(ftol, "ftol")
    xtol = check(xtol, "xtol")
    gtol = check(gtol, "gtol")

    if ftol < EPS and xtol < EPS and gtol < EPS:
        raise ValueError(
            "At least one of the tolerances must be higher than "
            "machine epsilon ({:.2e}).".format(EPS)
        )

    return ftol, xtol, gtol


# Traceback (KeyError)
KeyError                                  Traceback (most recent call last)
~/Documents/prog/yalsi/scipybug.py in <module>
27 try_fit(y, H, p0, xtol=1e-13, method='trf')
28 try_fit(y, H, p0, xtol=1e-16, method='lm')
---> 29 try_fit(y, H, p0, xtol=1e-13, method='lm')

~/Documents/prog/yalsi/scipybug.py in try_fit(y, H, p0, **kwargs)
6         return y - H @ p
7     try:
----> 8         result = optimize.least_squares(res, p0, ftol=0, gtol=0, **kwargs)
9     except ValueError:
10         pass # "at least one of the tolerances must be > 2e-16"

~/Documents/Programmi/python3_virtualenv/lib/python3.6/site-packages/scipy/optimize/_lsq/least_squares.py in least_squares(fun, x0, jac, bounds, method, ftol, xtol, gtol, x_scale, loss, f_scale, diff_step, tr_solver, tr_options, jac_sparsity, max_nfev, verbose, args, kwargs)
910     if method == 'lm':
911         result = call_minpack(fun_wrapped, x0, jac_wrapped, ftol, xtol, gtol,
--> 912                               max_nfev, x_scale, diff_step)
913
914     elif method == 'trf':

~/Documents/Programmi/python3_virtualenv/lib/python3.6/site-packages/scipy/optimize/_lsq/least_squares.py in call_minpack(fun, x0, jac, ftol, xtol, gtol, max_nfev, x_scale, diff_step)
87     njev = info.get('njev', None)
88
---> 89     status = FROM_MINPACK_TO_COMMON[status]
90     active_mask = np.zeros_like(x0, dtype=int)
91

KeyError: 6

# Fixed code
def check_tolerance(ftol, xtol, gtol, method):
    def check(tol, name):
        if tol is None:
            tol = 0
        elif tol < EPS:
            warn(
                "Setting `{}` below the machine epsilon ({:.2e}) effectively "
                "disables the corresponding termination condition.".format(name, EPS)
            )
        return tol

    ftol = check(ftol, "ftol")
    xtol = check(xtol, "xtol")
    gtol = check(gtol, "gtol")

    if method == "lm" and (ftol < EPS or xtol < EPS or gtol < EPS):
        raise ValueError(
            "All tolerances must be higher than machine epsilon "
            "({:.2e}) for method 'lm'.".format(EPS)
        )
    elif ftol < EPS and xtol < EPS and gtol < EPS:
        raise ValueError(
            "At least one of the tolerances must be higher than "
            "machine epsilon ({:.2e}).".format(EPS)
        )

    return ftol, xtol, gtol
# Buggy code
def _winsorize1D(a, low_limit, up_limit, low_include, up_include):
    n = a.count()
    idx = a.argsort()
    if low_limit:
        if low_include:
            lowidx = int(low_limit * n)
        else:
            lowidx = np.round(low_limit * n)
        a[idx[:lowidx]] = a[idx[lowidx]]
    if up_limit is not None:
        if up_include:
            upidx = n - int(n * up_limit)
        else:
            upidx = n - np.round(n * up_limit)
        a[idx[upidx:]] = a[idx[upidx - 1]]
    return a


# Traceback (IndexError)
Traceback (most recent call last):
File "/home/tk3mh/pyspimp/spi-multi-premia/calculation/cwinsorize.py", line 14, in <module>
terrerst()
File "/home/tk3mh/pyspimp/spi-multi-premia/calculation/cwinsorize.py", line 10, in terrerst
aa=winsorize(a, limits=[0.05, 0.05], inclusive=(False, False))
File "/home/tk3mh/pyspimp/lib64/python3.4/site-packages/scipy/stats/mstats_basic.py", line 1848, in winsorize
return _winsorize1D(a.ravel(), lolim, uplim, loinc, upinc).reshape(shp)
File "/home/tk3mh/pyspimp/lib64/python3.4/site-packages/scipy/stats/mstats_basic.py", line 1817, in _winsorize1D
a[idx[:lowidx]] = a[idx[lowidx]]
IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

Process finished with exit code 1

# Fixed code
def _winsorize1D(a, low_limit, up_limit, low_include, up_include):
    n = a.count()
    idx = a.argsort()
    if low_limit:
        if low_include:
            lowidx = int(low_limit * n)
        else:
            lowidx = np.round(low_limit * n).astype(int)
        a[idx[:lowidx]] = a[idx[lowidx]]
    if up_limit is not None:
        if up_include:
            upidx = n - int(n * up_limit)
        else:
            upidx = n - np.round(n * up_limit).astype(int)
        a[idx[upidx:]] = a[idx[upidx - 1]]
    return a
# Buggy code
def _normalize_sequence(input, rank):
    """If input is a scalar, create a sequence of length equal to the
    rank by duplicating the input. If input is a sequence,
    check if its length is equal to the length of array.
    """
    is_str = isinstance(input, str)
    if hasattr(input, "__iter__") and not is_str:
        normalized = list(input)
        if len(normalized) != rank:
            err = "sequence argument must have length equal to input rank"
            raise RuntimeError(err)
    else:
        normalized = [input] * rank
    return normalized


# Traceback (RuntimeError)
Traceback (most recent call last):
File "C:\Users\Sonicrs\Desktop\scipy_bug_tester.py", line 31, in <module>
mode=('constant', 'constant'))
File "C:\Users\Sonicrs\AppData\Local\Programs\Python\Python37\lib\site-packages\scipy\ndimage\filters.py", line 1097, in maximum_filter
cval, origin, 0)
File "C:\Users\Sonicrs\AppData\Local\Programs\Python\Python37\lib\site-packages\scipy\ndimage\filters.py", line 1020, in _min_or_max_filter
mode = _ni_support._extend_mode_to_code(mode)
File "C:\Users\Sonicrs\AppData\Local\Programs\Python\Python37\lib\site-packages\scipy\ndimage\_ni_support.py", line 52, in _extend_mode_to_code
raise RuntimeError('boundary mode not supported')
RuntimeError: boundary mode not supported

# Fixed code
def _normalize_sequence(input, rank):
    """If input is a scalar, create a sequence of length equal to the
    rank by duplicating the input. If input is a sequence,
    check if its length is equal to the length of array.
    """
    is_str = isinstance(input, str)
    if not is_str and isinstance(input, Iterable):
        normalized = list(input)
        if len(normalized) != rank:
            err = "sequence argument must have length equal to input rank"
            raise RuntimeError(err)
    else:
        normalized = [input] * rank
    return normalized
# Buggy code
def correlate(input, weights, output=None, mode="reflect", cval=0.0, origin=0):
    """
    Multidimensional correlation.

    The array is correlated with the given kernel.

    Parameters
    ----------
    %(input)s
    weights : ndarray
        array of weights, same number of dimensions as input
    %(output)s
    %(mode_multiple)s
    %(cval)s
    %(origin_multiple)s

    See Also
    --------
    convolve : Convolve an image with a kernel.
    """
    return _correlate_or_convolve(input, weights, output, mode, cval, origin, False)


# Traceback (RuntimeError)
Traceback (most recent call last):
File "C:\Users\Sonicrs\Desktop\scipy_bug_tester.py", line 31, in <module>
mode=('constant', 'constant'))
File "C:\Users\Sonicrs\AppData\Local\Programs\Python\Python37\lib\site-packages\scipy\ndimage\filters.py", line 1097, in maximum_filter
cval, origin, 0)
File "C:\Users\Sonicrs\AppData\Local\Programs\Python\Python37\lib\site-packages\scipy\ndimage\filters.py", line 1020, in _min_or_max_filter
mode = _ni_support._extend_mode_to_code(mode)
File "C:\Users\Sonicrs\AppData\Local\Programs\Python\Python37\lib\site-packages\scipy\ndimage\_ni_support.py", line 52, in _extend_mode_to_code
raise RuntimeError('boundary mode not supported')
RuntimeError: boundary mode not supported

# Fixed code
def correlate(input, weights, output=None, mode="reflect", cval=0.0, origin=0):
    """
    Multidimensional correlation.

    The array is correlated with the given kernel.

    Parameters
    ----------
    %(input)s
    weights : ndarray
        array of weights, same number of dimensions as input
    %(output)s
    %(mode)s
    %(cval)s
    %(origin_multiple)s

    See Also
    --------
    convolve : Convolve an image with a kernel.
    """
    return _correlate_or_convolve(input, weights, output, mode, cval, origin, False)
# Buggy code
def minimum_filter(
    input, size=None, footprint=None, output=None, mode="reflect", cval=0.0, origin=0
):
    """Calculate a multidimensional minimum filter.

    Parameters
    ----------
    %(input)s
    %(size_foot)s
    %(output)s
    %(mode_multiple)s
    %(cval)s
    %(origin_multiple)s

    Returns
    -------
    minimum_filter : ndarray
        Filtered array. Has the same shape as `input`.

    Examples
    --------
    >>> from scipy import ndimage, misc
    >>> import matplotlib.pyplot as plt
    >>> fig = plt.figure()
    >>> plt.gray()  # show the filtered result in grayscale
    >>> ax1 = fig.add_subplot(121)  # left side
    >>> ax2 = fig.add_subplot(122)  # right side
    >>> ascent = misc.ascent()
    >>> result = ndimage.minimum_filter(ascent, size=20)
    >>> ax1.imshow(ascent)
    >>> ax2.imshow(result)
    >>> plt.show()
    """
    return _min_or_max_filter(
        input, size, footprint, None, output, mode, cval, origin, 1
    )


# Traceback (RuntimeError)
Traceback (most recent call last):
File "C:\Users\Sonicrs\Desktop\scipy_bug_tester.py", line 31, in <module>
mode=('constant', 'constant'))
File "C:\Users\Sonicrs\AppData\Local\Programs\Python\Python37\lib\site-packages\scipy\ndimage\filters.py", line 1097, in maximum_filter
cval, origin, 0)
File "C:\Users\Sonicrs\AppData\Local\Programs\Python\Python37\lib\site-packages\scipy\ndimage\filters.py", line 1020, in _min_or_max_filter
mode = _ni_support._extend_mode_to_code(mode)
File "C:\Users\Sonicrs\AppData\Local\Programs\Python\Python37\lib\site-packages\scipy\ndimage\_ni_support.py", line 52, in _extend_mode_to_code
raise RuntimeError('boundary mode not supported')
RuntimeError: boundary mode not supported

# Fixed code
def minimum_filter(
    input, size=None, footprint=None, output=None, mode="reflect", cval=0.0, origin=0
):
    """Calculate a multidimensional minimum filter.

    Parameters
    ----------
    %(input)s
    %(size_foot)s
    %(output)s
    %(mode_multiple)s
    %(cval)s
    %(origin_multiple)s

    Returns
    -------
    minimum_filter : ndarray
        Filtered array. Has the same shape as `input`.

    Notes
    -----
    A sequence of modes (one per axis) is only supported when the footprint is
    separable. Otherwise, a single mode string must be provided.

    Examples
    --------
    >>> from scipy import ndimage, misc
    >>> import matplotlib.pyplot as plt
    >>> fig = plt.figure()
    >>> plt.gray()  # show the filtered result in grayscale
    >>> ax1 = fig.add_subplot(121)  # left side
    >>> ax2 = fig.add_subplot(122)  # right side
    >>> ascent = misc.ascent()
    >>> result = ndimage.minimum_filter(ascent, size=20)
    >>> ax1.imshow(ascent)
    >>> ax2.imshow(result)
    >>> plt.show()
    """
    return _min_or_max_filter(
        input, size, footprint, None, output, mode, cval, origin, 1
    )
# Buggy code
def maximum_filter(
    input, size=None, footprint=None, output=None, mode="reflect", cval=0.0, origin=0
):
    """Calculate a multidimensional maximum filter.

    Parameters
    ----------
    %(input)s
    %(size_foot)s
    %(output)s
    %(mode_multiple)s
    %(cval)s
    %(origin_multiple)s

    Returns
    -------
    maximum_filter : ndarray
        Filtered array. Has the same shape as `input`.

    Examples
    --------
    >>> from scipy import ndimage, misc
    >>> import matplotlib.pyplot as plt
    >>> fig = plt.figure()
    >>> plt.gray()  # show the filtered result in grayscale
    >>> ax1 = fig.add_subplot(121)  # left side
    >>> ax2 = fig.add_subplot(122)  # right side
    >>> ascent = misc.ascent()
    >>> result = ndimage.maximum_filter(ascent, size=20)
    >>> ax1.imshow(ascent)
    >>> ax2.imshow(result)
    >>> plt.show()
    """
    return _min_or_max_filter(
        input, size, footprint, None, output, mode, cval, origin, 0
    )


# Traceback (RuntimeError)
Traceback (most recent call last):
File "C:\Users\Sonicrs\Desktop\scipy_bug_tester.py", line 31, in <module>
mode=('constant', 'constant'))
File "C:\Users\Sonicrs\AppData\Local\Programs\Python\Python37\lib\site-packages\scipy\ndimage\filters.py", line 1097, in maximum_filter
cval, origin, 0)
File "C:\Users\Sonicrs\AppData\Local\Programs\Python\Python37\lib\site-packages\scipy\ndimage\filters.py", line 1020, in _min_or_max_filter
mode = _ni_support._extend_mode_to_code(mode)
File "C:\Users\Sonicrs\AppData\Local\Programs\Python\Python37\lib\site-packages\scipy\ndimage\_ni_support.py", line 52, in _extend_mode_to_code
raise RuntimeError('boundary mode not supported')
RuntimeError: boundary mode not supported

# Fixed code
def maximum_filter(
    input, size=None, footprint=None, output=None, mode="reflect", cval=0.0, origin=0
):
    """Calculate a multidimensional maximum filter.

    Parameters
    ----------
    %(input)s
    %(size_foot)s
    %(output)s
    %(mode_multiple)s
    %(cval)s
    %(origin_multiple)s

    Returns
    -------
    maximum_filter : ndarray
        Filtered array. Has the same shape as `input`.

    Notes
    -----
    A sequence of modes (one per axis) is only supported when the footprint is
    separable. Otherwise, a single mode string must be provided.

    Examples
    --------
    >>> from scipy import ndimage, misc
    >>> import matplotlib.pyplot as plt
    >>> fig = plt.figure()
    >>> plt.gray()  # show the filtered result in grayscale
    >>> ax1 = fig.add_subplot(121)  # left side
    >>> ax2 = fig.add_subplot(122)  # right side
    >>> ascent = misc.ascent()
    >>> result = ndimage.maximum_filter(ascent, size=20)
    >>> ax1.imshow(ascent)
    >>> ax2.imshow(result)
    >>> plt.show()
    """
    return _min_or_max_filter(
        input, size, footprint, None, output, mode, cval, origin, 0
    )
# Buggy code
def rank_filter(
    input,
    rank,
    size=None,
    footprint=None,
    output=None,
    mode="reflect",
    cval=0.0,
    origin=0,
):
    """Calculate a multidimensional rank filter.

    Parameters
    ----------
    %(input)s
    rank : int
        The rank parameter may be less then zero, i.e., rank = -1
        indicates the largest element.
    %(size_foot)s
    %(output)s
    %(mode_multiple)s
    %(cval)s
    %(origin_multiple)s

    Returns
    -------
    rank_filter : ndarray
        Filtered array. Has the same shape as `input`.

    Examples
    --------
    >>> from scipy import ndimage, misc
    >>> import matplotlib.pyplot as plt
    >>> fig = plt.figure()
    >>> plt.gray()  # show the filtered result in grayscale
    >>> ax1 = fig.add_subplot(121)  # left side
    >>> ax2 = fig.add_subplot(122)  # right side
    >>> ascent = misc.ascent()
    >>> result = ndimage.rank_filter(ascent, rank=42, size=20)
    >>> ax1.imshow(ascent)
    >>> ax2.imshow(result)
    >>> plt.show()
    """
    rank = operator.index(rank)
    return _rank_filter(
        input, rank, size, footprint, output, mode, cval, origin, "rank"
    )


# Traceback (RuntimeError)
Traceback (most recent call last):
File "C:\Users\Sonicrs\Desktop\scipy_bug_tester.py", line 31, in <module>
mode=('constant', 'constant'))
File "C:\Users\Sonicrs\AppData\Local\Programs\Python\Python37\lib\site-packages\scipy\ndimage\filters.py", line 1097, in maximum_filter
cval, origin, 0)
File "C:\Users\Sonicrs\AppData\Local\Programs\Python\Python37\lib\site-packages\scipy\ndimage\filters.py", line 1020, in _min_or_max_filter
mode = _ni_support._extend_mode_to_code(mode)
File "C:\Users\Sonicrs\AppData\Local\Programs\Python\Python37\lib\site-packages\scipy\ndimage\_ni_support.py", line 52, in _extend_mode_to_code
raise RuntimeError('boundary mode not supported')
RuntimeError: boundary mode not supported

# Fixed code
def rank_filter(
    input,
    rank,
    size=None,
    footprint=None,
    output=None,
    mode="reflect",
    cval=0.0,
    origin=0,
):
    """Calculate a multidimensional rank filter.

    Parameters
    ----------
    %(input)s
    rank : int
        The rank parameter may be less then zero, i.e., rank = -1
        indicates the largest element.
    %(size_foot)s
    %(output)s
    %(mode)s
    %(cval)s
    %(origin_multiple)s

    Returns
    -------
    rank_filter : ndarray
        Filtered array. Has the same shape as `input`.

    Examples
    --------
    >>> from scipy import ndimage, misc
    >>> import matplotlib.pyplot as plt
    >>> fig = plt.figure()
    >>> plt.gray()  # show the filtered result in grayscale
    >>> ax1 = fig.add_subplot(121)  # left side
    >>> ax2 = fig.add_subplot(122)  # right side
    >>> ascent = misc.ascent()
    >>> result = ndimage.rank_filter(ascent, rank=42, size=20)
    >>> ax1.imshow(ascent)
    >>> ax2.imshow(result)
    >>> plt.show()
    """
    rank = operator.index(rank)
    return _rank_filter(
        input, rank, size, footprint, output, mode, cval, origin, "rank"
    )
# Buggy code
def median_filter(
    input, size=None, footprint=None, output=None, mode="reflect", cval=0.0, origin=0
):
    """
    Calculate a multidimensional median filter.

    Parameters
    ----------
    %(input)s
    %(size_foot)s
    %(output)s
    %(mode_multiple)s
    %(cval)s
    %(origin_multiple)s

    Returns
    -------
    median_filter : ndarray
        Filtered array. Has the same shape as `input`.

    Examples
    --------
    >>> from scipy import ndimage, misc
    >>> import matplotlib.pyplot as plt
    >>> fig = plt.figure()
    >>> plt.gray()  # show the filtered result in grayscale
    >>> ax1 = fig.add_subplot(121)  # left side
    >>> ax2 = fig.add_subplot(122)  # right side
    >>> ascent = misc.ascent()
    >>> result = ndimage.median_filter(ascent, size=20)
    >>> ax1.imshow(ascent)
    >>> ax2.imshow(result)
    >>> plt.show()
    """
    return _rank_filter(input, 0, size, footprint, output, mode, cval, origin, "median")


# Traceback (RuntimeError)
Traceback (most recent call last):
File "C:\Users\Sonicrs\Desktop\scipy_bug_tester.py", line 31, in <module>
mode=('constant', 'constant'))
File "C:\Users\Sonicrs\AppData\Local\Programs\Python\Python37\lib\site-packages\scipy\ndimage\filters.py", line 1097, in maximum_filter
cval, origin, 0)
File "C:\Users\Sonicrs\AppData\Local\Programs\Python\Python37\lib\site-packages\scipy\ndimage\filters.py", line 1020, in _min_or_max_filter
mode = _ni_support._extend_mode_to_code(mode)
File "C:\Users\Sonicrs\AppData\Local\Programs\Python\Python37\lib\site-packages\scipy\ndimage\_ni_support.py", line 52, in _extend_mode_to_code
raise RuntimeError('boundary mode not supported')
RuntimeError: boundary mode not supported

# Fixed code
def median_filter(
    input, size=None, footprint=None, output=None, mode="reflect", cval=0.0, origin=0
):
    """
    Calculate a multidimensional median filter.

    Parameters
    ----------
    %(input)s
    %(size_foot)s
    %(output)s
    %(mode)s
    %(cval)s
    %(origin_multiple)s

    Returns
    -------
    median_filter : ndarray
        Filtered array. Has the same shape as `input`.

    Examples
    --------
    >>> from scipy import ndimage, misc
    >>> import matplotlib.pyplot as plt
    >>> fig = plt.figure()
    >>> plt.gray()  # show the filtered result in grayscale
    >>> ax1 = fig.add_subplot(121)  # left side
    >>> ax2 = fig.add_subplot(122)  # right side
    >>> ascent = misc.ascent()
    >>> result = ndimage.median_filter(ascent, size=20)
    >>> ax1.imshow(ascent)
    >>> ax2.imshow(result)
    >>> plt.show()
    """
    return _rank_filter(input, 0, size, footprint, output, mode, cval, origin, "median")
# Buggy code
def percentile_filter(
    input,
    percentile,
    size=None,
    footprint=None,
    output=None,
    mode="reflect",
    cval=0.0,
    origin=0,
):
    """Calculate a multidimensional percentile filter.

    Parameters
    ----------
    %(input)s
    percentile : scalar
        The percentile parameter may be less then zero, i.e.,
        percentile = -20 equals percentile = 80
    %(size_foot)s
    %(output)s
    %(mode_multiple)s
    %(cval)s
    %(origin_multiple)s

    Returns
    -------
    percentile_filter : ndarray
        Filtered array. Has the same shape as `input`.

    Examples
    --------
    >>> from scipy import ndimage, misc
    >>> import matplotlib.pyplot as plt
    >>> fig = plt.figure()
    >>> plt.gray()  # show the filtered result in grayscale
    >>> ax1 = fig.add_subplot(121)  # left side
    >>> ax2 = fig.add_subplot(122)  # right side
    >>> ascent = misc.ascent()
    >>> result = ndimage.percentile_filter(ascent, percentile=20, size=20)
    >>> ax1.imshow(ascent)
    >>> ax2.imshow(result)
    >>> plt.show()
    """
    return _rank_filter(
        input, percentile, size, footprint, output, mode, cval, origin, "percentile"
    )


# Traceback (RuntimeError)
Traceback (most recent call last):
File "C:\Users\Sonicrs\Desktop\scipy_bug_tester.py", line 31, in <module>
mode=('constant', 'constant'))
File "C:\Users\Sonicrs\AppData\Local\Programs\Python\Python37\lib\site-packages\scipy\ndimage\filters.py", line 1097, in maximum_filter
cval, origin, 0)
File "C:\Users\Sonicrs\AppData\Local\Programs\Python\Python37\lib\site-packages\scipy\ndimage\filters.py", line 1020, in _min_or_max_filter
mode = _ni_support._extend_mode_to_code(mode)
File "C:\Users\Sonicrs\AppData\Local\Programs\Python\Python37\lib\site-packages\scipy\ndimage\_ni_support.py", line 52, in _extend_mode_to_code
raise RuntimeError('boundary mode not supported')
RuntimeError: boundary mode not supported

# Fixed code
def percentile_filter(
    input,
    percentile,
    size=None,
    footprint=None,
    output=None,
    mode="reflect",
    cval=0.0,
    origin=0,
):
    """Calculate a multidimensional percentile filter.

    Parameters
    ----------
    %(input)s
    percentile : scalar
        The percentile parameter may be less then zero, i.e.,
        percentile = -20 equals percentile = 80
    %(size_foot)s
    %(output)s
    %(mode)s
    %(cval)s
    %(origin_multiple)s

    Returns
    -------
    percentile_filter : ndarray
        Filtered array. Has the same shape as `input`.

    Examples
    --------
    >>> from scipy import ndimage, misc
    >>> import matplotlib.pyplot as plt
    >>> fig = plt.figure()
    >>> plt.gray()  # show the filtered result in grayscale
    >>> ax1 = fig.add_subplot(121)  # left side
    >>> ax2 = fig.add_subplot(122)  # right side
    >>> ascent = misc.ascent()
    >>> result = ndimage.percentile_filter(ascent, percentile=20, size=20)
    >>> ax1.imshow(ascent)
    >>> ax2.imshow(result)
    >>> plt.show()
    """
    return _rank_filter(
        input, percentile, size, footprint, output, mode, cval, origin, "percentile"
    )
# Buggy code
def new_bounds_to_old(lb, ub, n):
    """Convert the new bounds representation to the old one.

    The new representation is a tuple (lb, ub) and the old one is a list
    containing n tuples, ith containing lower and upper bound on a ith
    variable.
    """
    lb = np.asarray(lb)
    ub = np.asarray(ub)
    if lb.ndim == 0:
        lb = np.resize(lb, n)
    if ub.ndim == 0:
        ub = np.resize(ub, n)

    lb = [x if x > -np.inf else None for x in lb]
    ub = [x if x < np.inf else None for x in ub]

    return list(zip(lb, ub))


# Traceback (ValueError)
In [158]: minimize(func, [1.1, 1.2], method='Newton-CG', jac=False)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-158-94c7580e9508> in <module>()
----> 1 minimize(func, [1.1, 1.2], method='Newton-CG', jac=False)

~/miniconda3scipy/lib/python3.5/site-packages/scipy-1.2.0.dev0+6d455f3-py3.5-macosx-10.6-x86_64.egg/scipy/optimize/_minimize.py in minimize(fun, x0, args, method, jac, hess, hessp, bounds, constraints, tol, callback, options)
600     elif meth == 'newton-cg':
601         return _minimize_newtoncg(fun, x0, args, jac, hess, hessp, callback,
--> 602                                   **options)
603     elif meth == 'l-bfgs-b':
604         return _minimize_lbfgsb(fun, x0, args, jac, bounds,

~/miniconda3scipy/lib/python3.5/site-packages/scipy-1.2.0.dev0+6d455f3-py3.5-macosx-10.6-x86_64.egg/scipy/optimize/optimize.py in _minimize_newtoncg(fun, x0, args, jac, hess, hessp, callback, xtol, eps, maxiter, disp, return_all, **unknown_options)
1494     _check_unknown_options(unknown_options)
1495     if jac is None:
-> 1496         raise ValueError('Jacobian is required for Newton-CG method')
1497     f = fun
1498     fprime = jac

ValueError: Jacobian is required for Newton-CG method

# Fixed code
def new_bounds_to_old(lb, ub, n):
    """Convert the new bounds representation to the old one.

    The new representation is a tuple (lb, ub) and the old one is a list
    containing n tuples, ith containing lower and upper bound on a ith
    variable.
    If any of the entries in lb/ub are -np.inf/np.inf they are replaced by
    None.
    """
    lb = np.asarray(lb)
    ub = np.asarray(ub)
    if lb.ndim == 0:
        lb = np.resize(lb, n)
    if ub.ndim == 0:
        ub = np.resize(ub, n)

    lb = [x if x > -np.inf else None for x in lb]
    ub = [x if x < np.inf else None for x in ub]

    return list(zip(lb, ub))
# Buggy code
def old_bound_to_new(bounds):
    """Convert the old bounds representation to the new one.

    The new representation is a tuple (lb, ub) and the old one is a list
    containing n tuples, ith containing lower and upper bound on a ith
    variable.
    """
    lb, ub = zip(*bounds)
    lb = np.array([x if x is not None else -np.inf for x in lb])
    ub = np.array([x if x is not None else np.inf for x in ub])
    return lb, ub


# Traceback (ValueError)
In [158]: minimize(func, [1.1, 1.2], method='Newton-CG', jac=False)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-158-94c7580e9508> in <module>()
----> 1 minimize(func, [1.1, 1.2], method='Newton-CG', jac=False)

~/miniconda3scipy/lib/python3.5/site-packages/scipy-1.2.0.dev0+6d455f3-py3.5-macosx-10.6-x86_64.egg/scipy/optimize/_minimize.py in minimize(fun, x0, args, method, jac, hess, hessp, bounds, constraints, tol, callback, options)
600     elif meth == 'newton-cg':
601         return _minimize_newtoncg(fun, x0, args, jac, hess, hessp, callback,
--> 602                                   **options)
603     elif meth == 'l-bfgs-b':
604         return _minimize_lbfgsb(fun, x0, args, jac, bounds,

~/miniconda3scipy/lib/python3.5/site-packages/scipy-1.2.0.dev0+6d455f3-py3.5-macosx-10.6-x86_64.egg/scipy/optimize/optimize.py in _minimize_newtoncg(fun, x0, args, jac, hess, hessp, callback, xtol, eps, maxiter, disp, return_all, **unknown_options)
1494     _check_unknown_options(unknown_options)
1495     if jac is None:
-> 1496         raise ValueError('Jacobian is required for Newton-CG method')
1497     f = fun
1498     fprime = jac

ValueError: Jacobian is required for Newton-CG method

# Fixed code
def old_bound_to_new(bounds):
    """Convert the old bounds representation to the new one.

    The new representation is a tuple (lb, ub) and the old one is a list
    containing n tuples, ith containing lower and upper bound on a ith
    variable.
    If any of the entries in lb/ub are None they are replaced by
    -np.inf/np.inf.
    """
    lb, ub = zip(*bounds)
    lb = np.array([x if x is not None else -np.inf for x in lb])
    ub = np.array([x if x is not None else np.inf for x in ub])
    return lb, ub
# Buggy code
def update_grad():
    self._update_fun()
    self.g = approx_derivative(fun_wrapped, self.x, f0=self.f, **finite_diff_options)


# Traceback (ValueError)
In [158]: minimize(func, [1.1, 1.2], method='Newton-CG', jac=False)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-158-94c7580e9508> in <module>()
----> 1 minimize(func, [1.1, 1.2], method='Newton-CG', jac=False)

~/miniconda3scipy/lib/python3.5/site-packages/scipy-1.2.0.dev0+6d455f3-py3.5-macosx-10.6-x86_64.egg/scipy/optimize/_minimize.py in minimize(fun, x0, args, method, jac, hess, hessp, bounds, constraints, tol, callback, options)
600     elif meth == 'newton-cg':
601         return _minimize_newtoncg(fun, x0, args, jac, hess, hessp, callback,
--> 602                                   **options)
603     elif meth == 'l-bfgs-b':
604         return _minimize_lbfgsb(fun, x0, args, jac, bounds,

~/miniconda3scipy/lib/python3.5/site-packages/scipy-1.2.0.dev0+6d455f3-py3.5-macosx-10.6-x86_64.egg/scipy/optimize/optimize.py in _minimize_newtoncg(fun, x0, args, jac, hess, hessp, callback, xtol, eps, maxiter, disp, return_all, **unknown_options)
1494     _check_unknown_options(unknown_options)
1495     if jac is None:
-> 1496         raise ValueError('Jacobian is required for Newton-CG method')
1497     f = fun
1498     fprime = jac

ValueError: Jacobian is required for Newton-CG method

# Fixed code
def update_grad():
    self._update_fun()
    self.ngev += 1
    self.g = approx_derivative(fun_wrapped, self.x, f0=self.f, **finite_diff_options)
# Buggy code
def _compute_absolute_step(rel_step, x0, method):
    if rel_step is None:
        rel_step = relative_step[method]
    sign_x0 = (x0 >= 0).astype(float) * 2 - 1
    return rel_step * sign_x0 * np.maximum(1.0, np.abs(x0))


# Traceback (ValueError)
In [158]: minimize(func, [1.1, 1.2], method='Newton-CG', jac=False)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-158-94c7580e9508> in <module>()
----> 1 minimize(func, [1.1, 1.2], method='Newton-CG', jac=False)

~/miniconda3scipy/lib/python3.5/site-packages/scipy-1.2.0.dev0+6d455f3-py3.5-macosx-10.6-x86_64.egg/scipy/optimize/_minimize.py in minimize(fun, x0, args, method, jac, hess, hessp, bounds, constraints, tol, callback, options)
600     elif meth == 'newton-cg':
601         return _minimize_newtoncg(fun, x0, args, jac, hess, hessp, callback,
--> 602                                   **options)
603     elif meth == 'l-bfgs-b':
604         return _minimize_lbfgsb(fun, x0, args, jac, bounds,

~/miniconda3scipy/lib/python3.5/site-packages/scipy-1.2.0.dev0+6d455f3-py3.5-macosx-10.6-x86_64.egg/scipy/optimize/optimize.py in _minimize_newtoncg(fun, x0, args, jac, hess, hessp, callback, xtol, eps, maxiter, disp, return_all, **unknown_options)
1494     _check_unknown_options(unknown_options)
1495     if jac is None:
-> 1496         raise ValueError('Jacobian is required for Newton-CG method')
1497     f = fun
1498     fprime = jac

ValueError: Jacobian is required for Newton-CG method

# Fixed code
def _compute_absolute_step(rel_step, x0, method):
    """
    Computes an absolute step from a relative step for finite difference
    calculation.

    Parameters
    ----------
    rel_step: None or array-like
        Relative step for the finite difference calculation
    x0 : np.ndarray
        Parameter vector
    method : {'2-point', '3-point', 'cs'}
    """
    if rel_step is None:
        rel_step = relative_step[method]
    sign_x0 = (x0 >= 0).astype(float) * 2 - 1
    return rel_step * sign_x0 * np.maximum(1.0, np.abs(x0))
# Buggy code
def _prepare_bounds(bounds, x0):
    lb, ub = [np.asarray(b, dtype=float) for b in bounds]
    if lb.ndim == 0:
        lb = np.resize(lb, x0.shape)

    if ub.ndim == 0:
        ub = np.resize(ub, x0.shape)

    return lb, ub


# Traceback (ValueError)
In [158]: minimize(func, [1.1, 1.2], method='Newton-CG', jac=False)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-158-94c7580e9508> in <module>()
----> 1 minimize(func, [1.1, 1.2], method='Newton-CG', jac=False)

~/miniconda3scipy/lib/python3.5/site-packages/scipy-1.2.0.dev0+6d455f3-py3.5-macosx-10.6-x86_64.egg/scipy/optimize/_minimize.py in minimize(fun, x0, args, method, jac, hess, hessp, bounds, constraints, tol, callback, options)
600     elif meth == 'newton-cg':
601         return _minimize_newtoncg(fun, x0, args, jac, hess, hessp, callback,
--> 602                                   **options)
603     elif meth == 'l-bfgs-b':
604         return _minimize_lbfgsb(fun, x0, args, jac, bounds,

~/miniconda3scipy/lib/python3.5/site-packages/scipy-1.2.0.dev0+6d455f3-py3.5-macosx-10.6-x86_64.egg/scipy/optimize/optimize.py in _minimize_newtoncg(fun, x0, args, jac, hess, hessp, callback, xtol, eps, maxiter, disp, return_all, **unknown_options)
1494     _check_unknown_options(unknown_options)
1495     if jac is None:
-> 1496         raise ValueError('Jacobian is required for Newton-CG method')
1497     f = fun
1498     fprime = jac

ValueError: Jacobian is required for Newton-CG method

# Fixed code
def _prepare_bounds(bounds, x0):
    """
    Prepares new-style bounds from a two-tuple specifying the lower and upper
    limits for values in x0. If a value is not bound then the lower/upper bound
    will be expected to be -np.inf/np.inf.

    Examples
    --------
    >>> _prepare_bounds([(0, 1, 2), (1, 2, np.inf)], [0.5, 1.5, 2.5])
    (array([0., 1., 2.]), array([ 1.,  2., inf]))
    """
    lb, ub = [np.asarray(b, dtype=float) for b in bounds]
    if lb.ndim == 0:
        lb = np.resize(lb, x0.shape)

    if ub.ndim == 0:
        ub = np.resize(ub, x0.shape)

    return lb, ub
# Buggy code
def jac_mag(self):
    """Magniture of Jacobian of objective function at current iteration."""
    if self._g_mag is None:
        self._g_mag = scipy.linalg.norm(self.jac)
    return self._g_mag


# Traceback (ValueError)
In [158]: minimize(func, [1.1, 1.2], method='Newton-CG', jac=False)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-158-94c7580e9508> in <module>()
----> 1 minimize(func, [1.1, 1.2], method='Newton-CG', jac=False)

~/miniconda3scipy/lib/python3.5/site-packages/scipy-1.2.0.dev0+6d455f3-py3.5-macosx-10.6-x86_64.egg/scipy/optimize/_minimize.py in minimize(fun, x0, args, method, jac, hess, hessp, bounds, constraints, tol, callback, options)
600     elif meth == 'newton-cg':
601         return _minimize_newtoncg(fun, x0, args, jac, hess, hessp, callback,
--> 602                                   **options)
603     elif meth == 'l-bfgs-b':
604         return _minimize_lbfgsb(fun, x0, args, jac, bounds,

~/miniconda3scipy/lib/python3.5/site-packages/scipy-1.2.0.dev0+6d455f3-py3.5-macosx-10.6-x86_64.egg/scipy/optimize/optimize.py in _minimize_newtoncg(fun, x0, args, jac, hess, hessp, callback, xtol, eps, maxiter, disp, return_all, **unknown_options)
1494     _check_unknown_options(unknown_options)
1495     if jac is None:
-> 1496         raise ValueError('Jacobian is required for Newton-CG method')
1497     f = fun
1498     fprime = jac

ValueError: Jacobian is required for Newton-CG method

# Fixed code
def jac_mag(self):
    """Magnitude of jacobian of objective function at current iteration."""
    if self._g_mag is None:
        self._g_mag = scipy.linalg.norm(self.jac)
    return self._g_mag
# Buggy code
def approx_fhess_p(x0, p, fprime, epsilon, *args):
    f2 = fprime(*((x0 + epsilon * p,) + args))
    f1 = fprime(*((x0,) + args))
    return (f2 - f1) / epsilon


# Traceback (ValueError)
In [158]: minimize(func, [1.1, 1.2], method='Newton-CG', jac=False)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-158-94c7580e9508> in <module>()
----> 1 minimize(func, [1.1, 1.2], method='Newton-CG', jac=False)

~/miniconda3scipy/lib/python3.5/site-packages/scipy-1.2.0.dev0+6d455f3-py3.5-macosx-10.6-x86_64.egg/scipy/optimize/_minimize.py in minimize(fun, x0, args, method, jac, hess, hessp, bounds, constraints, tol, callback, options)
600     elif meth == 'newton-cg':
601         return _minimize_newtoncg(fun, x0, args, jac, hess, hessp, callback,
--> 602                                   **options)
603     elif meth == 'l-bfgs-b':
604         return _minimize_lbfgsb(fun, x0, args, jac, bounds,

~/miniconda3scipy/lib/python3.5/site-packages/scipy-1.2.0.dev0+6d455f3-py3.5-macosx-10.6-x86_64.egg/scipy/optimize/optimize.py in _minimize_newtoncg(fun, x0, args, jac, hess, hessp, callback, xtol, eps, maxiter, disp, return_all, **unknown_options)
1494     _check_unknown_options(unknown_options)
1495     if jac is None:
-> 1496         raise ValueError('Jacobian is required for Newton-CG method')
1497     f = fun
1498     fprime = jac

ValueError: Jacobian is required for Newton-CG method

# Fixed code
def approx_fhess_p(x0, p, fprime, epsilon, *args):
    # calculate fprime(x0) first, as this may be cached by ScalarFunction
    f1 = fprime(*((x0,) + args))
    f2 = fprime(*((x0 + epsilon * p,) + args))
    return (f2 - f1) / epsilon
# Buggy code
def terminate(warnflag, msg):
    if disp:
        print(msg)
        print("         Current function value: %f" % old_fval)
        print("         Iterations: %d" % k)
        print("         Function evaluations: %d" % fcalls[0])
        print("         Gradient evaluations: %d" % gcalls[0])
        print("         Hessian evaluations: %d" % hcalls)
    fval = old_fval
    result = OptimizeResult(
        fun=fval,
        jac=gfk,
        nfev=fcalls[0],
        njev=gcalls[0],
        nhev=hcalls,
        status=warnflag,
        success=(warnflag == 0),
        message=msg,
        x=xk,
        nit=k,
    )
    if retall:
        result["allvecs"] = allvecs
    return result


# Traceback (ValueError)
In [158]: minimize(func, [1.1, 1.2], method='Newton-CG', jac=False)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-158-94c7580e9508> in <module>()
----> 1 minimize(func, [1.1, 1.2], method='Newton-CG', jac=False)

~/miniconda3scipy/lib/python3.5/site-packages/scipy-1.2.0.dev0+6d455f3-py3.5-macosx-10.6-x86_64.egg/scipy/optimize/_minimize.py in minimize(fun, x0, args, method, jac, hess, hessp, bounds, constraints, tol, callback, options)
600     elif meth == 'newton-cg':
601         return _minimize_newtoncg(fun, x0, args, jac, hess, hessp, callback,
--> 602                                   **options)
603     elif meth == 'l-bfgs-b':
604         return _minimize_lbfgsb(fun, x0, args, jac, bounds,

~/miniconda3scipy/lib/python3.5/site-packages/scipy-1.2.0.dev0+6d455f3-py3.5-macosx-10.6-x86_64.egg/scipy/optimize/optimize.py in _minimize_newtoncg(fun, x0, args, jac, hess, hessp, callback, xtol, eps, maxiter, disp, return_all, **unknown_options)
1494     _check_unknown_options(unknown_options)
1495     if jac is None:
-> 1496         raise ValueError('Jacobian is required for Newton-CG method')
1497     f = fun
1498     fprime = jac

ValueError: Jacobian is required for Newton-CG method

# Fixed code
def terminate(warnflag, msg):
    if disp:
        print(msg)
        print("         Current function value: %f" % old_fval)
        print("         Iterations: %d" % k)
        print("         Function evaluations: %d" % sf.nfev)
        print("         Gradient evaluations: %d" % sf.ngev)
        print("         Hessian evaluations: %d" % hcalls)
    fval = old_fval
    result = OptimizeResult(
        fun=fval,
        jac=gfk,
        nfev=sf.nfev,
        njev=sf.ngev,
        nhev=hcalls,
        status=warnflag,
        success=(warnflag == 0),
        message=msg,
        x=xk,
        nit=k,
    )
    if retall:
        result["allvecs"] = allvecs
    return result
# Buggy code
def cjac_factory(fun):
    def cjac(x, *args):
        return approx_jacobian(x, fun, epsilon, *args)

    return cjac


# Traceback (ValueError)
In [158]: minimize(func, [1.1, 1.2], method='Newton-CG', jac=False)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-158-94c7580e9508> in <module>()
----> 1 minimize(func, [1.1, 1.2], method='Newton-CG', jac=False)

~/miniconda3scipy/lib/python3.5/site-packages/scipy-1.2.0.dev0+6d455f3-py3.5-macosx-10.6-x86_64.egg/scipy/optimize/_minimize.py in minimize(fun, x0, args, method, jac, hess, hessp, bounds, constraints, tol, callback, options)
600     elif meth == 'newton-cg':
601         return _minimize_newtoncg(fun, x0, args, jac, hess, hessp, callback,
--> 602                                   **options)
603     elif meth == 'l-bfgs-b':
604         return _minimize_lbfgsb(fun, x0, args, jac, bounds,

~/miniconda3scipy/lib/python3.5/site-packages/scipy-1.2.0.dev0+6d455f3-py3.5-macosx-10.6-x86_64.egg/scipy/optimize/optimize.py in _minimize_newtoncg(fun, x0, args, jac, hess, hessp, callback, xtol, eps, maxiter, disp, return_all, **unknown_options)
1494     _check_unknown_options(unknown_options)
1495     if jac is None:
-> 1496         raise ValueError('Jacobian is required for Newton-CG method')
1497     f = fun
1498     fprime = jac

ValueError: Jacobian is required for Newton-CG method

# Fixed code
def cjac_factory(fun):
    def cjac(x, *args):
        if jac in ["2-point", "3-point", "cs"]:
            return approx_derivative(
                fun, x, method=jac, args=args, rel_step=finite_diff_rel_step
            )
        else:
            return approx_derivative(
                fun, x, method="2-point", abs_step=epsilon, args=args
            )

    return cjac
# Buggy code
def cjac(x, *args):
    return approx_jacobian(x, fun, epsilon, *args)


# Traceback (ValueError)
In [158]: minimize(func, [1.1, 1.2], method='Newton-CG', jac=False)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-158-94c7580e9508> in <module>()
----> 1 minimize(func, [1.1, 1.2], method='Newton-CG', jac=False)

~/miniconda3scipy/lib/python3.5/site-packages/scipy-1.2.0.dev0+6d455f3-py3.5-macosx-10.6-x86_64.egg/scipy/optimize/_minimize.py in minimize(fun, x0, args, method, jac, hess, hessp, bounds, constraints, tol, callback, options)
600     elif meth == 'newton-cg':
601         return _minimize_newtoncg(fun, x0, args, jac, hess, hessp, callback,
--> 602                                   **options)
603     elif meth == 'l-bfgs-b':
604         return _minimize_lbfgsb(fun, x0, args, jac, bounds,

~/miniconda3scipy/lib/python3.5/site-packages/scipy-1.2.0.dev0+6d455f3-py3.5-macosx-10.6-x86_64.egg/scipy/optimize/optimize.py in _minimize_newtoncg(fun, x0, args, jac, hess, hessp, callback, xtol, eps, maxiter, disp, return_all, **unknown_options)
1494     _check_unknown_options(unknown_options)
1495     if jac is None:
-> 1496         raise ValueError('Jacobian is required for Newton-CG method')
1497     f = fun
1498     fprime = jac

ValueError: Jacobian is required for Newton-CG method

# Fixed code
def cjac(x, *args):
    if jac in ["2-point", "3-point", "cs"]:
        return approx_derivative(
            fun, x, method=jac, args=args, rel_step=finite_diff_rel_step
        )
    else:
        return approx_derivative(fun, x, method="2-point", abs_step=epsilon, args=args)
# Buggy code
def apply_filter(self, x, axis=-1, mode="constant", cval=0):
    """Apply the prepared filter to the specified axis of a N-D signal x"""
    output_len = _output_len(
        len(self._h_trans_flip), x.shape[axis], self._up, self._down
    )
    output_shape = np.asarray(x.shape)
    output_shape[axis] = output_len
    out = np.zeros(output_shape, dtype=self._output_type, order="C")
    axis = axis % x.ndim
    mode = _check_mode(mode)
    _apply(
        np.asarray(x, self._output_type),
        self._h_trans_flip,
        out,
        self._up,
        self._down,
        axis,
        mode,
        cval,
    )
    return out


# Traceback (OverflowError)
Traceback (most recent call last):

File "<ipython-input-1-ac5d2b0a1632>", line 11, in <module>
yy = resample_poly(y, 128, 1)

File "F:\Programs\Miniconda3\lib\site-packages\scipy\signal\signaltools.py", line 2424, in resample_poly
y = upfirdn(h, x, up, down, axis=axis)

File "F:\Programs\Miniconda3\lib\site-packages\scipy\signal\_upfirdn.py", line 183, in upfirdn
return ufd.apply_filter(x, axis)

File "F:\Programs\Miniconda3\lib\site-packages\scipy\signal\_upfirdn.py", line 82, in apply_filter
output_shape[axis] = output_len

OverflowError: Python int too large to convert to C long

# Fixed code
def apply_filter(self, x, axis=-1, mode="constant", cval=0):
    """Apply the prepared filter to the specified axis of a N-D signal x"""
    output_len = _output_len(
        len(self._h_trans_flip), x.shape[axis], self._up, self._down
    )
    # Explicit use of np.int64 for output_shape dtype avoids OverflowError
    # when allocating large array on platforms where np.int_ is 32 bits
    output_shape = np.asarray(x.shape, dtype=np.int64)
    output_shape[axis] = output_len
    out = np.zeros(output_shape, dtype=self._output_type, order="C")
    axis = axis % x.ndim
    mode = _check_mode(mode)
    _apply(
        np.asarray(x, self._output_type),
        self._h_trans_flip,
        out,
        self._up,
        self._down,
        axis,
        mode,
        cval,
    )
    return out