gurudesh/pytracebugs huggingface dataset:
# Buggy code
def _select_sigma(X):
    """
    Returns the smaller of std(X, ddof=1) or normalized IQR(X) over axis 0.

    References
    ----------
    Silverman (1986) p.47
    """
    #    normalize = norm.ppf(.75) - norm.ppf(.25)
    normalize = 1.349
    #    IQR = np.subtract.reduce(percentile(X, [75,25],
    #                             axis=axis), axis=axis)/normalize
    IQR = (sap(X, 75) - sap(X, 25)) / normalize
    return np.minimum(np.std(X, axis=0, ddof=1), IQR)


# Traceback (ValueError)
Numpy: 1.18.3
Statsmodels: 0.11.1

Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/statsmodels/nonparametric/kde.py", line 451, in kdensityfft
bw = float(bw)
ValueError: could not convert string to float: 'normal_reference'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "repr.py", line 11, in <module>
kde.fit()
File "/usr/local/lib/python3.7/site-packages/statsmodels/nonparametric/kde.py", line 140, in fit
clip=clip, cut=cut)
File "/usr/local/lib/python3.7/site-packages/statsmodels/nonparametric/kde.py", line 453, in kdensityfft
bw = bandwidths.select_bandwidth(X, bw, kern) # will cross-val fit this pattern?
File "/usr/local/lib/python3.7/site-packages/statsmodels/nonparametric/bandwidths.py", line 174, in select_bandwidth
raise RuntimeError(err)
RuntimeError: Selected KDE bandwidth is 0. Cannot estimate density.

# Fixed code
def _select_sigma(x, percentile=25):
    """
    Returns the smaller of std(X, ddof=1) or normalized IQR(X) over axis 0.

    References
    ----------
    Silverman (1986) p.47
    """
    # normalize = norm.ppf(.75) - norm.ppf(.25)
    normalize = 1.349
    IQR = (scoreatpercentile(x, 75) - scoreatpercentile(x, 25)) / normalize
    std_dev = np.std(x, axis=0, ddof=1)
    if IQR > 0:
        return np.minimum(std_dev, IQR)
    else:
        return std_dev
# Buggy code
def select_bandwidth(x, bw, kernel):
    """
    Selects bandwidth for a selection rule bw

    this is a wrapper around existing bandwidth selection rules

    Parameters
    ----------
    x : array_like
        Array for which to get the bandwidth
    bw : str
        name of bandwidth selection rule, currently supported are:
        %s
    kernel : not used yet

    Returns
    -------
    bw : float
        The estimate of the bandwidth
    """
    bw = bw.lower()
    if bw not in bandwidth_funcs:
        raise ValueError("Bandwidth %s not understood" % bw)
    bandwidth = bandwidth_funcs[bw](x, kernel)
    if np.any(bandwidth == 0):
        # eventually this can fall back on another selection criterion.
        err = "Selected KDE bandwidth is 0. Cannot estimate density."
        raise RuntimeError(err)
    else:
        return bandwidth


# Traceback (ValueError)
Numpy: 1.18.3
Statsmodels: 0.11.1

Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/statsmodels/nonparametric/kde.py", line 451, in kdensityfft
bw = float(bw)
ValueError: could not convert string to float: 'normal_reference'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "repr.py", line 11, in <module>
kde.fit()
File "/usr/local/lib/python3.7/site-packages/statsmodels/nonparametric/kde.py", line 140, in fit
clip=clip, cut=cut)
File "/usr/local/lib/python3.7/site-packages/statsmodels/nonparametric/kde.py", line 453, in kdensityfft
bw = bandwidths.select_bandwidth(X, bw, kern) # will cross-val fit this pattern?
File "/usr/local/lib/python3.7/site-packages/statsmodels/nonparametric/bandwidths.py", line 174, in select_bandwidth
raise RuntimeError(err)
RuntimeError: Selected KDE bandwidth is 0. Cannot estimate density.

# Fixed code
def select_bandwidth(x, bw, kernel):
    """
    Selects bandwidth for a selection rule bw

    this is a wrapper around existing bandwidth selection rules

    Parameters
    ----------
    x : array_like
        Array for which to get the bandwidth
    bw : str
        name of bandwidth selection rule, currently supported are:
        %s
    kernel : not used yet

    Returns
    -------
    bw : float
        The estimate of the bandwidth
    """
    bw = bw.lower()
    if bw not in bandwidth_funcs:
        raise ValueError("Bandwidth %s not understood" % bw)
    bandwidth = bandwidth_funcs[bw](x, kernel)
    if np.any(bandwidth == 0):
        # eventually this can fall back on another selection criterion.
        err = (
            "Selected KDE bandwidth is 0. Cannot estimate density. "
            "Either provide the bandwidth during initialization or use "
            "an alternative method."
        )
        raise RuntimeError(err)
    else:
        return bandwidth
# Buggy code
def __init__(self, endog):
    self.endog = np.asarray(endog)


# Traceback (ValueError)
Traceback (most recent call last):
File "./statsmodels_01.py", line 40, in <module>
kde_.fit()
File "/home/kian/.local/lib/python2.7/site-packages/statsmodels/nonparametric/kde.py", line 142, in fit
clip=clip, cut=cut)
File "/home/kian/.local/lib/python2.7/site-packages/statsmodels/nonparametric/kde.py", line 484, in kdensityfft
binned = fast_linbin(X,a,b,gridsize)/(delta*nobs)
File "linbin.pyx", line 17, in statsmodels.nonparametric.linbin.fast_linbin (statsmodels/nonparametric/linbin.c:1246)
ValueError: Buffer dtype mismatch, expected 'DOUBLE' but got 'long'

# Fixed code
def __init__(self, endog):
    self.endog = array_like(endog, "endog", ndim=1, contiguous=True)
# Buggy code
def __init__(self, x, kernel=None):
    x = np.asarray(x)
    if x.ndim == 1:
        x = x[:, None]

    nobs, n_series = x.shape

    if kernel is None:
        kernel = kernels.Gaussian()  # no meaningful bandwidth yet

    if n_series > 1:
        if isinstance(kernel, kernels.CustomKernel):
            kernel = kernels.NdKernel(n_series, kernels=kernel)

    self.kernel = kernel
    self.n = n_series  # TODO change attribute
    self.x = x


# Traceback (ValueError)
Traceback (most recent call last):
File "./statsmodels_01.py", line 40, in <module>
kde_.fit()
File "/home/kian/.local/lib/python2.7/site-packages/statsmodels/nonparametric/kde.py", line 142, in fit
clip=clip, cut=cut)
File "/home/kian/.local/lib/python2.7/site-packages/statsmodels/nonparametric/kde.py", line 484, in kdensityfft
binned = fast_linbin(X,a,b,gridsize)/(delta*nobs)
File "linbin.pyx", line 17, in statsmodels.nonparametric.linbin.fast_linbin (statsmodels/nonparametric/linbin.c:1246)
ValueError: Buffer dtype mismatch, expected 'DOUBLE' but got 'long'

# Fixed code
def __init__(self, x, kernel=None):
    x = array_like(x, "x", maxdim=2, contiguous=True)
    if x.ndim == 1:
        x = x[:, None]

    nobs, n_series = x.shape

    if kernel is None:
        kernel = kernels.Gaussian()  # no meaningful bandwidth yet

    if n_series > 1:
        if isinstance(kernel, kernels.CustomKernel):
            kernel = kernels.NdKernel(n_series, kernels=kernel)

    self.kernel = kernel
    self.n = n_series  # TODO change attribute
    self.x = x
# Buggy code
def conf_int(self, method="endpoint", alpha=0.05, **kwds):
    # TODO: this performs metadata wrapping, and that should be handled
    #       by attach_* methods. However, they do not currently support
    #       this use case.
    conf_int = super(PredictionResults, self).conf_int(method, alpha, **kwds)

    # Create a dataframe
    if self.row_labels is not None:
        conf_int = pd.DataFrame(conf_int, index=self.row_labels)

        # Attach the endog names
        ynames = self.model.data.ynames
        if not type(ynames) == list:
            ynames = [ynames]
        names = ["lower %s" % name for name in ynames] + [
            "upper %s" % name for name in ynames
        ]
        conf_int.columns = names

    return conf_int


# Traceback (TypeError)
Traceback (most recent call last):
File "/home/user/Projects/subfolder/my_project/test1.py", line 42, in <module>
pred_ci = pred_res.conf_int(alpha=0.01)
File "/home/user/Programs/anaconda3/envs/vision/lib/python3.7/site-packages/statsmodels/tsa/statespace/mlemodel.py", line 3707, in conf_int
names = (['lower %s' % name for name in ynames] +
File "/home/user/Programs/anaconda3/envs/vision/lib/python3.7/site-packages/statsmodels/tsa/statespace/mlemodel.py", line 3707, in <listcomp>
names = (['lower %s' % name for name in ynames] +
TypeError: not all arguments converted during string formatting

# Fixed code
def conf_int(self, method="endpoint", alpha=0.05, **kwds):
    # TODO: this performs metadata wrapping, and that should be handled
    #       by attach_* methods. However, they do not currently support
    #       this use case.
    conf_int = super(PredictionResults, self).conf_int(method, alpha, **kwds)

    # Create a dataframe
    if self.row_labels is not None:
        conf_int = pd.DataFrame(conf_int, index=self.row_labels)

        # Attach the endog names
        ynames = self.model.data.ynames
        if not type(ynames) == list:
            ynames = [ynames]
        names = ["lower {0}".format(name) for name in ynames] + [
            "upper {0}".format(name) for name in ynames
        ]
        conf_int.columns = names

    return conf_int
# Buggy code
def attach_cov(self, result):
    return DataFrame(result, index=self.param_names, columns=self.param_names)


# Traceback (ValueError)
In [34]: results._results.cov_params.shape
Out[34]: (36, 36)

In [37]: results.cov_params

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-37-14357748fa96> in <module>()

<snip>
ValueError: Shape of passed values is (36, 36), indices imply (12, 12)

# Fixed code
def attach_cov(self, result):
    return DataFrame(result, index=self.cov_names, columns=self.cov_names)
# Buggy code
def cov_params(self):
    """Estimated variance-covariance of model coefficients

    Notes
    -----
    Covariance of vec(B), where B is the matrix
    [params_for_deterministic_terms, A_1, ..., A_p] with the shape
    (K x (Kp + number_of_deterministic_terms))
    Adjusted to be an unbiased estimator
    Ref: Lütkepohl p.74-75
    """
    import warnings

    warnings.warn(
        "For consistency with other statmsodels models, "
        "starting in version 0.11.0 `VARResults.cov_params` "
        "will be a method instead of a property.",
        category=FutureWarning,
    )
    z = self.endog_lagged
    return np.kron(scipy.linalg.inv(np.dot(z.T, z)), self.sigma_u)


# Traceback (ValueError)
In [34]: results._results.cov_params.shape
Out[34]: (36, 36)

In [37]: results.cov_params

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-37-14357748fa96> in <module>()

<snip>
ValueError: Shape of passed values is (36, 36), indices imply (12, 12)

# Fixed code
def cov_params(self):
    """Estimated variance-covariance of model coefficients

    Notes
    -----
    Covariance of vec(B), where B is the matrix
    [params_for_deterministic_terms, A_1, ..., A_p] with the shape
    (K x (Kp + number_of_deterministic_terms))
    Adjusted to be an unbiased estimator
    Ref: Lütkepohl p.74-75
    """
    z = self.endog_lagged
    return np.kron(scipy.linalg.inv(np.dot(z.T, z)), self.sigma_u)
# Buggy code
def _cov_alpha(self):
    """
    Estimated covariance matrix of model coefficients w/o exog
    """
    # drop exog
    return self._cov_params()[self.k_exog * self.neqs :, self.k_exog * self.neqs :]


# Traceback (ValueError)
In [34]: results._results.cov_params.shape
Out[34]: (36, 36)

In [37]: results.cov_params

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-37-14357748fa96> in <module>()

<snip>
ValueError: Shape of passed values is (36, 36), indices imply (12, 12)

# Fixed code
def _cov_alpha(self):
    """
    Estimated covariance matrix of model coefficients w/o exog
    """
    # drop exog
    kn = self.k_exog * self.neqs
    return self.cov_params()[kn:, kn:]
# Buggy code
def stderr(self):
    """Standard errors of coefficients, reshaped to match in size"""
    stderr = np.sqrt(np.diag(self._cov_params()))
    return stderr.reshape((self.df_model, self.neqs), order="C")


# Traceback (ValueError)
In [34]: results._results.cov_params.shape
Out[34]: (36, 36)

In [37]: results.cov_params

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-37-14357748fa96> in <module>()

<snip>
ValueError: Shape of passed values is (36, 36), indices imply (12, 12)

# Fixed code
def stderr(self):
    """Standard errors of coefficients, reshaped to match in size"""
    stderr = np.sqrt(np.diag(self.cov_params()))
    return stderr.reshape((self.df_model, self.neqs), order="C")
# Buggy code
def f(n):
    return np.array([0.86, 0.91, 0.96, 1.06, 1.25]) / np.sqrt(n)


# Traceback (ValueError)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/testone/lib64/python3.6/site-packages/statsmodels/stats/_lilliefors.py", line 344, in kstest_fit
pval = lilliefors_table.prob(d_ks, nobs)
File "/home/testone/lib64/python3.6/site-packages/statsmodels/stats/tabledist.py", line 120, in prob
critv = self._critvals(n)
File "/home/testone/lib64/python3.6/site-packages/statsmodels/stats/tabledist.py", line 99, in _critvals
return np.array([p(n) for p in self.polyn])
File "/home/testone/lib64/python3.6/site-packages/statsmodels/stats/tabledist.py", line 99, in <listcomp>
return np.array([p(n) for p in self.polyn])
File "/usr/lib64/python3.6/site-packages/scipy/interpolate/polyint.py", line 79, in __call__
y = self._evaluate(x)
File "/usr/lib64/python3.6/site-packages/scipy/interpolate/interpolate.py", line 634, in _evaluate
below_bounds, above_bounds = self._check_bounds(x_new)
File "/usr/lib64/python3.6/site-packages/scipy/interpolate/interpolate.py", line 663, in _check_bounds
raise ValueError("A value in x_new is below the interpolation "
ValueError: A value in x_new is below the interpolation range.

# Fixed code
def f(n):
    poly = np.array([1, np.log(n), np.log(n) ** 2])
    return np.exp(poly.dot(params.T))
# Buggy code
def _critvals(self, n):
    """rows of the table, linearly interpolated for given sample size

    Parameters
    ----------
    n : float
        sample size, second parameter of the table

    Returns
    -------
    critv : ndarray, 1d
        critical values (ppf) corresponding to a row of the table

    Notes
    -----
    This is used in two step interpolation, or if we want to know the
    critical values for all alphas for any sample size that we can obtain
    through interpolation

    """
    return np.array([p(n) for p in self.polyn])


# Traceback (ValueError)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/testone/lib64/python3.6/site-packages/statsmodels/stats/_lilliefors.py", line 344, in kstest_fit
pval = lilliefors_table.prob(d_ks, nobs)
File "/home/testone/lib64/python3.6/site-packages/statsmodels/stats/tabledist.py", line 120, in prob
critv = self._critvals(n)
File "/home/testone/lib64/python3.6/site-packages/statsmodels/stats/tabledist.py", line 99, in _critvals
return np.array([p(n) for p in self.polyn])
File "/home/testone/lib64/python3.6/site-packages/statsmodels/stats/tabledist.py", line 99, in <listcomp>
return np.array([p(n) for p in self.polyn])
File "/usr/lib64/python3.6/site-packages/scipy/interpolate/polyint.py", line 79, in __call__
y = self._evaluate(x)
File "/usr/lib64/python3.6/site-packages/scipy/interpolate/interpolate.py", line 634, in _evaluate
below_bounds, above_bounds = self._check_bounds(x_new)
File "/usr/lib64/python3.6/site-packages/scipy/interpolate/interpolate.py", line 663, in _check_bounds
raise ValueError("A value in x_new is below the interpolation "
ValueError: A value in x_new is below the interpolation range.

# Fixed code
def _critvals(self, n):
    """
    Rows of the table, linearly interpolated for given sample size

    Parameters
    ----------
    n : float
        sample size, second parameter of the table

    Returns
    -------
    critv : ndarray, 1d
        critical values (ppf) corresponding to a row of the table

    Notes
    -----
    This is used in two step interpolation, or if we want to know the
    critical values for all alphas for any sample size that we can obtain
    through interpolation
    """
    if n > self.max_size:
        if self.asymptotic is not None:
            cv = self.asymptotic(n)
        else:
            raise ValueError(
                "n is above max(size) and no asymptotic distribtuion is provided"
            )
    else:
        cv = [p(n) for p in self.polyn]
        if n > self.min_nobs:
            w = (n - self.min_nobs) / (self.max_nobs - self.min_nobs)
            w = min(1.0, w)
            a_cv = self.asymptotic(n)
            cv = w * a_cv + (1 - w) * cv

    return cv
# Buggy code
def _make_arma_exog(endog, exog, trend):
    k_trend = 1  # overwritten if no constant
    if exog is None and trend == "c":  # constant only
        exog = np.ones((len(endog), 1))
    elif exog is not None and trend == "c":  # constant plus exogenous
        exog = add_trend(exog, trend="c", prepend=True)
    elif exog is not None and trend == "nc":
        # make sure it's not holding constant from last run
        if exog.var() == 0:
            exog = None
        k_trend = 0
    if trend == "nc":
        k_trend = 0
    return k_trend, exog


# Traceback (ValueError)
import pandas as pd
from statsmodels.tsa.arima_model import ARIMA
X = [0.5,0.5,0.5,0.5,0.5]
Y = [-0.011866,0.003380,0.015357,0.004451,-0.020889]
T = ['2000-01-01', '2000-01-02', '2000-01-03', '2000-01-04', '2000-01-05']
TDT = pd.to_datetime(T)
df = pd.DataFrame({'x': X, 'y': Y})
df.index = TDT
df
x         y
2000-01-01  0.5 -0.011866
2000-01-02  0.5  0.003380
2000-01-03  0.5  0.015357
2000-01-04  0.5  0.004451
2000-01-05  0.5 -0.020889
m = ARIMA(endog=df.y, order=(1,1,0), exog=df.x)
r = m.fit()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.5/dist-packages/statsmodels/tsa/arima_model.py", line 1104, in fit
callback, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/statsmodels/tsa/arima_model.py", line 919, in fit
start_params = self._fit_start_params((k_ar, k_ma, k), method)
File "/usr/local/lib/python3.5/dist-packages/statsmodels/tsa/arima_model.py", line 563, in _fit_start_params
bounds=bounds, iprint=-1)
File "/usr/local/lib/python3.5/dist-packages/scipy/optimize/lbfgsb.py", line 193, in fmin_l_bfgs_b
**opts)
File "/usr/local/lib/python3.5/dist-packages/scipy/optimize/lbfgsb.py", line 328, in _minimize_lbfgsb
f, g = func_and_grad(x)
File "/usr/local/lib/python3.5/dist-packages/scipy/optimize/lbfgsb.py", line 273, in func_and_grad
f = fun(x, *args)
File "/usr/local/lib/python3.5/dist-packages/scipy/optimize/optimize.py", line 292, in function_wrapper
return function(*(wrapper_args + args))
File "/usr/local/lib/python3.5/dist-packages/statsmodels/tsa/arima_model.py", line 554, in <lambda>
func = lambda params: -self.loglike_css(params)
File "/usr/local/lib/python3.5/dist-packages/statsmodels/tsa/arima_model.py", line 788, in loglike_css
y -= dot(self.exog, newparams[:k])
ValueError: shapes (4,1) and (2,) not aligned: 1 (dim 1) != 2 (dim 0)

# Fixed code
def _make_arma_exog(endog, exog, trend):
    k_trend = 1  # overwritten if no constant
    if exog is None and trend == "c":  # constant only
        exog = np.ones((len(endog), 1))
    elif exog is not None and trend == "c":  # constant plus exogenous
        exog = add_trend(exog, trend="c", prepend=True, has_constant="raise")
    elif exog is not None and trend == "nc":
        # make sure it's not holding constant from last run
        if exog.var() == 0:
            exog = None
        k_trend = 0
    if trend == "nc":
        k_trend = 0
    return k_trend, exog
# Buggy code
def _maybe_convert_ynames_int(self, ynames):
    # see if they're integers
    try:
        for i in ynames:
            if ynames[i] % 1 == 0:
                ynames[i] = str(int(ynames[i]))
    except TypeError:
        pass
    return ynames


# Traceback (TypeError)
result.summary()
ynames = ['='.join([yname, name]) for name in ynames]
TypeError: sequence item 1: expected str instance, numpy.float64 found
ynames = ['='.join([yname, name]) for name in ynames]
File "m:\...\statsmodels\discrete\discrete_model.py", line 3916, in <listcomp>
File "m:\...\statsmodels\discrete\discrete_model.py", line 3520, in summary
yname, yname_list = self._get_endog_name(yname, yname_list)
File "m:\...\statsmodels\discrete\discrete_model.py", line 3916, in _get_endog_name
Traceback (most recent call last):
File "<stdin>", line 1, in <module>

# Fixed code
def _maybe_convert_ynames_int(self, ynames):
    # see if they're integers
    issue_warning = False
    msg = (
        "endog contains values are that not int-like. Uses string "
        "representation of value. Use integer-valued endog to "
        "suppress this warning."
    )
    for i in ynames:
        try:
            if ynames[i] % 1 == 0:
                ynames[i] = str(int(ynames[i]))
            else:
                issue_warning = True
                ynames[i] = str(ynames[i])
        except TypeError:
            ynames[i] = str(ynames[i])
    if issue_warning:
        import warnings

        warnings.warn(msg, SpecificationWarning)

    return ynames
# Buggy code
def _make_dictnames(tmp_arr, offset=0):
    """
    Helper function to create a dictionary mapping a column number
    to the name in tmp_arr.
    """
    col_map = {}
    for i, col_name in enumerate(tmp_arr):
        col_map.update({i + offset: col_name})
    return col_map


# Traceback (AttributeError)
In [9]: sm.categorical(pd.DataFrame({'a':[1,2,12], 'b':['a','b','a']}), col='a')
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-9-5966a3ee6951> in <module>()
----> 1 sm.categorical(pd.DataFrame({'a':[1,2,12], 'b':['a','b','a']}), col='a')

/usr/local/lib/python2.7/dist-packages/statsmodels-0.6.0-py2.7-linux-x86_64.egg/statsmodels/tools/tools.pyc in categorical(data, col, dictnames, drop)
143     #TODO: add a NameValidator function
144     # catch recarrays and structured arrays
--> 145     if data.dtype.names or data.__class__ is np.recarray:
146         if not col and np.squeeze(data).ndim > 1:
147             raise IndexError("col is None and the input array is not 1d")

/usr/local/lib/python2.7/dist-packages/pandas-0.13.0_285_gfcfaa7d-py2.7-linux-x86_64.egg/pandas/core/generic.pyc in __getattr__(self, name)
1802                 return self[name]
1803             raise AttributeError("'%s' object has no attribute '%s'" %
-> 1804                                  (type(self).__name__, name))
1805
1806     def __setattr__(self, name, value):

AttributeError: 'DataFrame' object has no attribute 'dtype'

# Fixed code
def _make_dictnames(tmp_arr, offset=0):
    """
    Helper function to create a dictionary mapping a column number
    to the name in tmp_arr.
    """
    col_map = {}
    for i, col_name in enumerate(tmp_arr):
        col_map[i + offset] = col_name
    return col_map
# Buggy code
def _get_names(self, arr):
    if isinstance(arr, DataFrame):
        return list(arr.columns)
    elif isinstance(arr, Series):
        if arr.name:
            return [arr.name]
        else:
            return
    else:
        try:
            return arr.dtype.names
        except AttributeError:
            pass

    return None


# Traceback (ValueError)
Traceback (most recent call last):
File "xxx/__init__.py", line 451, in do_algorithm_usecase
if af.compute():
File "xxx/algorithms/es.py", line 153, in compute
preds = self.fitted_model.predict(predict_from, predict_until)
File "xxx/myenv/lib/python3.7/site-packages/statsmodels/base/wrapper.py", line 95, in wrapper
obj = data.wrap_output(func(results, *args, **kwargs), how)
File "xxx/myenv/lib/python3.7/site-packages/statsmodels/base/data.py", line 416, in wrap_output
return self.attach_dates(obj)
File "xxx/myenv/lib/python3.7/site-packages/statsmodels/base/data.py", line 563, in attach_dates
columns=self.ynames)
File "xxx/myenv/lib/python3.7/site-packages/pandas/core/frame.py", line 379, in __init__
copy=copy)
File "xxx/myenv/lib/python3.7/site-packages/pandas/core/frame.py", line 536, in _init_ndarray
return create_block_manager_from_blocks([values], [columns, index])
File "xxx/myenv/lib/python3.7/site-packages/pandas/core/internals.py", line 4866, in create_block_manager_from_blocks
construction_error(tot_items, blocks[0].shape[1:], axes, e)
File "xxx/myenv/lib/python3.7/site-packages/pandas/core/internals.py", line 4843, in construction_error
passed, implied))
ValueError: Shape of passed values is (1, 3), indices imply (3, 3)

# Fixed code
def _get_names(self, arr):
    if isinstance(arr, DataFrame):
        if isinstance(arr.columns, MultiIndex):
            # Flatten MultiIndexes into "simple" column names
            return [".".join((level for level in c if level)) for c in arr.columns]
        else:
            return list(arr.columns)
    elif isinstance(arr, Series):
        if arr.name:
            return [arr.name]
        else:
            return
    else:
        try:
            return arr.dtype.names
        except AttributeError:
            pass

    return None
# Buggy code
def _compute_bw(self, bw):
    """
    Computes the bandwidth of the data.

    Parameters
    ----------
    bw: array_like or str
        If array_like: user-specified bandwidth.
        If a string, should be one of:

            - cv_ml: cross validation maximum likelihood
            - normal_reference: normal reference rule of thumb
            - cv_ls: cross validation least squares

    Notes
    -----
    The default values for bw is 'normal_reference'.
    """

    self.bw_func = dict(
        normal_reference=self._normal_reference, cv_ml=self._cv_ml, cv_ls=self._cv_ls
    )
    if bw is None:
        bw = "normal_reference"

    if not isinstance(bw, string_types):
        self._bw_method = "user-specified"
        res = np.asarray(bw)
    else:
        # The user specified a bandwidth selection method
        self._bw_method = bw
        bwfunc = self.bw_func[bw]
        res = bwfunc()

    return res


# Traceback (AttributeError)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\[...]\lib\site-packages\statsmodels\graphics\functional.py", line 32, in _pickle_method
if m.im_self is None:
AttributeError: 'function' object has no attribute 'im_self'

# Fixed code
def _compute_bw(self, bw):
    """
    Computes the bandwidth of the data.

    Parameters
    ----------
    bw: array_like or str
        If array_like: user-specified bandwidth.
        If a string, should be one of:

            - cv_ml: cross validation maximum likelihood
            - normal_reference: normal reference rule of thumb
            - cv_ls: cross validation least squares

    Notes
    -----
    The default values for bw is 'normal_reference'.
    """
    if bw is None:
        bw = "normal_reference"

    if not isinstance(bw, string_types):
        self._bw_method = "user-specified"
        res = np.asarray(bw)
    else:
        # The user specified a bandwidth selection method
        self._bw_method = bw
        # Workaround to avoid instance methods in __dict__
        if bw == "normal_reference":
            bwfunc = self._normal_reference
        elif bw == "cv_ml":
            bwfunc = self._cv_ml
        else:  # bw == 'cv_ls'
            bwfunc = self._cv_ls
        res = bwfunc()

    return res
# Buggy code
def __init__(self, endog, exog, var_type, reg_type="ll", bw="cv_ls", defaults=None):
    self.var_type = var_type
    self.data_type = var_type
    self.reg_type = reg_type
    self.k_vars = len(self.var_type)
    self.endog = _adjust_shape(endog, 1)
    self.exog = _adjust_shape(exog, self.k_vars)
    self.data = np.column_stack((self.endog, self.exog))
    self.nobs = np.shape(self.exog)[0]
    self.bw_func = dict(cv_ls=self.cv_loo, aic=self.aic_hurvich)
    self.est = dict(lc=self._est_loc_constant, ll=self._est_loc_linear)
    defaults = EstimatorSettings() if defaults is None else defaults
    self._set_defaults(defaults)
    if not isinstance(bw, string_types):
        bw = np.asarray(bw)
        if len(bw) != self.k_vars:
            raise ValueError(
                "bw must have the same dimension as the number of variables."
            )
    if not self.efficient:
        self.bw = self._compute_reg_bw(bw)
    else:
        self.bw = self._compute_efficient(bw)


# Traceback (AttributeError)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\[...]\lib\site-packages\statsmodels\graphics\functional.py", line 32, in _pickle_method
if m.im_self is None:
AttributeError: 'function' object has no attribute 'im_self'

# Fixed code
def __init__(self, endog, exog, var_type, reg_type="ll", bw="cv_ls", defaults=None):
    self.var_type = var_type
    self.data_type = var_type
    self.reg_type = reg_type
    self.k_vars = len(self.var_type)
    self.endog = _adjust_shape(endog, 1)
    self.exog = _adjust_shape(exog, self.k_vars)
    self.data = np.column_stack((self.endog, self.exog))
    self.nobs = np.shape(self.exog)[0]
    self.est = dict(lc=self._est_loc_constant, ll=self._est_loc_linear)
    defaults = EstimatorSettings() if defaults is None else defaults
    self._set_defaults(defaults)
    if not isinstance(bw, string_types):
        bw = np.asarray(bw)
        if len(bw) != self.k_vars:
            raise ValueError(
                "bw must have the same dimension as the number of variables."
            )
    if not self.efficient:
        self.bw = self._compute_reg_bw(bw)
    else:
        self.bw = self._compute_efficient(bw)
# Buggy code
def _compute_reg_bw(self, bw):
    if not isinstance(bw, string_types):
        self._bw_method = "user-specified"
        return np.asarray(bw)
    else:
        # The user specified a bandwidth selection method e.g. 'cv_ls'
        self._bw_method = bw
        res = self.bw_func[bw]
        X = np.std(self.exog, axis=0)
        h0 = 1.06 * X * self.nobs ** (-1.0 / (4 + np.size(self.exog, axis=1)))

        func = self.est[self.reg_type]
        bw_estimated = optimize.fmin(
            res, x0=h0, args=(func,), maxiter=1e3, maxfun=1e3, disp=0
        )
        return bw_estimated


# Traceback (AttributeError)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\[...]\lib\site-packages\statsmodels\graphics\functional.py", line 32, in _pickle_method
if m.im_self is None:
AttributeError: 'function' object has no attribute 'im_self'

# Fixed code
def _compute_reg_bw(self, bw):
    if not isinstance(bw, string_types):
        self._bw_method = "user-specified"
        return np.asarray(bw)
    else:
        # The user specified a bandwidth selection method e.g. 'cv_ls'
        self._bw_method = bw
        # Workaround to avoid instance methods in __dict__
        if bw == "cv_ls":
            res = self.cv_loo
        else:  # bw == 'aic'
            res = self.aic_hurvich
        X = np.std(self.exog, axis=0)
        h0 = 1.06 * X * self.nobs ** (-1.0 / (4 + np.size(self.exog, axis=1)))

        func = self.est[self.reg_type]
        bw_estimated = optimize.fmin(
            res, x0=h0, args=(func,), maxiter=1e3, maxfun=1e3, disp=0
        )
        return bw_estimated
# Buggy code
def __init__(
    self, endog, exog, var_type, reg_type, bw="cv_ls", censor_val=0, defaults=None
):
    self.var_type = var_type
    self.data_type = var_type
    self.reg_type = reg_type
    self.k_vars = len(self.var_type)
    self.endog = _adjust_shape(endog, 1)
    self.exog = _adjust_shape(exog, self.k_vars)
    self.data = np.column_stack((self.endog, self.exog))
    self.nobs = np.shape(self.exog)[0]
    self.bw_func = dict(cv_ls=self.cv_loo, aic=self.aic_hurvich)
    self.est = dict(lc=self._est_loc_constant, ll=self._est_loc_linear)
    defaults = EstimatorSettings() if defaults is None else defaults
    self._set_defaults(defaults)
    self.censor_val = censor_val
    if self.censor_val is not None:
        self.censored(censor_val)
    else:
        self.W_in = np.ones((self.nobs, 1))

    if not self.efficient:
        self.bw = self._compute_reg_bw(bw)
    else:
        self.bw = self._compute_efficient(bw)


# Traceback (AttributeError)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\[...]\lib\site-packages\statsmodels\graphics\functional.py", line 32, in _pickle_method
if m.im_self is None:
AttributeError: 'function' object has no attribute 'im_self'

# Fixed code
def __init__(
    self, endog, exog, var_type, reg_type, bw="cv_ls", censor_val=0, defaults=None
):
    self.var_type = var_type
    self.data_type = var_type
    self.reg_type = reg_type
    self.k_vars = len(self.var_type)
    self.endog = _adjust_shape(endog, 1)
    self.exog = _adjust_shape(exog, self.k_vars)
    self.data = np.column_stack((self.endog, self.exog))
    self.nobs = np.shape(self.exog)[0]
    self.est = dict(lc=self._est_loc_constant, ll=self._est_loc_linear)
    defaults = EstimatorSettings() if defaults is None else defaults
    self._set_defaults(defaults)
    self.censor_val = censor_val
    if self.censor_val is not None:
        self.censored(censor_val)
    else:
        self.W_in = np.ones((self.nobs, 1))

    if not self.efficient:
        self.bw = self._compute_reg_bw(bw)
    else:
        self.bw = self._compute_efficient(bw)
# Buggy code
def medcouple(y, axis=0):
    """
    Calculates the medcouple robust measure of skew.

    Parameters
    ----------
    y : array-like
    axis : int or None, optional
        Axis along which the medcouple statistic is computed.  If `None`, the
        entire array is used.

    Returns
    -------
    mc : ndarray
        The medcouple statistic with the same shape as `y`, with the specified
        axis removed.

    Notes
    -----
    The current algorithm requires a O(N**2) memory allocations, and so may
    not work for very large arrays (N>10000).

    .. [*] M. Huberta and E. Vandervierenb, "An adjusted boxplot for skewed
       distributions" Computational Statistics & Data Analysis, vol. 52, pp.
       5186-5201, August 2008.
    """
    if axis is None:
        return _medcouple_1d(y.ravel())

    return np.apply_along_axis(_medcouple_1d, axis, y)


# Traceback (OverflowError)
from statsmodels.stats.stattools import medcouple
medcouple(np.arange(9))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "...\statsmodels\stats\stattools.py", line 451, in medcouple
return np.apply_along_axis(_medcouple_1d, axis, y)
File "C:\...\python-3.4.4.amd64\lib\site-packages\numpy\lib\shape_base.py", line 91, in apply_along_axis
res = func1d(arr[tuple(i.tolist())], *args, **kwargs)
File "...\statsmodels\stats\stattools.py", line 417, in _medcouple_1d
standardization[is_zero] = np.inf
OverflowError: cannot convert float infinity to integer

medcouple(np.arange(9)*1.0)
array(0.0)
medcouple(np.random.randn(9))
array(0.03126347622708405)
medcouple(np.random.randn(8))
array(0.0072095663649526616)

# Fixed code
def medcouple(y, axis=0):
    """
    Calculates the medcouple robust measure of skew.

    Parameters
    ----------
    y : array-like
    axis : int or None, optional
        Axis along which the medcouple statistic is computed.  If `None`, the
        entire array is used.

    Returns
    -------
    mc : ndarray
        The medcouple statistic with the same shape as `y`, with the specified
        axis removed.

    Notes
    -----
    The current algorithm requires a O(N**2) memory allocations, and so may
    not work for very large arrays (N>10000).

    .. [*] M. Huberta and E. Vandervierenb, "An adjusted boxplot for skewed
       distributions" Computational Statistics & Data Analysis, vol. 52, pp.
       5186-5201, August 2008.
    """
    y = np.asarray(y, dtype=np.double)  # GH 4243
    if axis is None:
        return _medcouple_1d(y.ravel())

    return np.apply_along_axis(_medcouple_1d, axis, y)
# Buggy code
def __getstate__(self):
    try:
        # remove unpicklable callback
        self.mle_settings["callback"] = None
    except (AttributeError, KeyError):
        pass
    return self.__dict__


# Traceback (cPickle.PicklingError)
Traceback (most recent call last):
File "statsmodels/base/tests/test_shrink_pickle.py", line 290, in <module>
tt.test_remove_data_pickle()
File "statsmodels/base/tests/test_shrink_pickle.py", line 68, in test_remove_data_pickle
res, l = check_pickle(results._results)
File "statsmodels/base/tests/test_shrink_pickle.py", line 27, in check_pickle
cPickle.dump(obj, fh, protocol=cPickle.HIGHEST_PROTOCOL)
cPickle.PicklingError: Can't pickle <type 'instancemethod'>: attribute lookup __builtin__.instancemethod failed

# Fixed code
def __getstate__(self):
    # remove unpicklable methods
    mle_settings = getattr(self, "mle_settings", None)
    if mle_settings is not None:
        if "callback" in mle_settings:
            mle_settings["callback"] = None
        if "cov_params_func" in mle_settings:
            mle_settings["cov_params_func"] = None
    return self.__dict__
# Buggy code
def initialize(self):
    if not self.score:  # right now score is not optional
        self.score = approx_fprime
        if not self.hessian:
            pass
    else:  # can use approx_hess_p if we have a gradient
        if not self.hessian:
            pass
    # Initialize is called by
    # statsmodels.model.LikelihoodModel.__init__
    # and should contain any preprocessing that needs to be done for a model
    from statsmodels.tools import tools

    if self.exog is not None:
        # assume constant
        er = np_matrix_rank(self.exog)
        self.df_model = float(er - 1)
        self.df_resid = float(self.exog.shape[0] - er)
    else:
        self.df_model = np.nan
        self.df_resid = np.nan
    super(GenericLikelihoodModel, self).initialize()


# Traceback (ValueError)
Traceback (most recent call last):
File "C:\git\statsmodels\statsmodels\base\model.py", line 447, in fit
H = -1 * self.hessian(xopt)
File "C:\git\statsmodels\statsmodels\tsa\arima_model.py", line 593, in hessian
return approx_hess_cs(params, self.loglike, args=(False,))
File "C:\git\statsmodels\statsmodels\tools\numdiff.py", line 243, in approx_hess_cs
**kwargs)).imag/2./hess[i, j]
File "C:\git\statsmodels\statsmodels\tsa\arima_model.py", line 776, in loglike
return self.loglike_kalman(params, set_sigma2)
File "C:\git\statsmodels\statsmodels\tsa\arima_model.py", line 786, in loglike_kalman
return KalmanFilter.loglike(params, self, set_sigma2)
File "C:\git\statsmodels\statsmodels\tsa\kalmanf\kalmanfilter.py", line 666, in loglike
R_mat, T_mat)
File "statsmodels\tsa\kalmanf\kalman_loglike.pyx", line 359, in statsmodels.tsa.kalmanf.kalman_loglike.kalman_loglike_complex (statsmodels/tsa/kalmanf/kalman_loglike.c:6432)
v, F, loglikelihood = kalman_filter_complex(y,k,p,q,r,nobs,Z_mat,R_mat,T_mat)
File "statsmodels\tsa\kalmanf\kalman_loglike.pyx", line 229, in statsmodels.tsa.kalmanf.kalman_loglike.kalman_filter_complex (statsmodels/tsa/kalmanf/kalman_loglike.c:4956)
dot(R_mat,R_mat.T).ravel('F')).reshape(r,r, order='F'))
File "statsmodels\tsa\kalmanf\stringsource", line 644, in View.MemoryView.memoryview_cwrapper (statsmodels/tsa/kalmanf/kalman_loglike.c:14545)
File "statsmodels\tsa\kalmanf\stringsource", line 345, in View.MemoryView.memoryview.__cinit__ (statsmodels/tsa/kalmanf/kalman_loglike.c:10820)
ValueError: ndarray is not Fortran contiguous

# Fixed code
def initialize(self):
    if not self.score:  # right now score is not optional
        self.score = approx_fprime
        if not self.hessian:
            pass
    else:  # can use approx_hess_p if we have a gradient
        if not self.hessian:
            pass
    # Initialize is called by
    # statsmodels.model.LikelihoodModel.__init__
    # and should contain any preprocessing that needs to be done for a model
    if self.exog is not None:
        # assume constant
        er = np_matrix_rank(self.exog)
        self.df_model = float(er - 1)
        self.df_resid = float(self.exog.shape[0] - er)
    else:
        self.df_model = np.nan
        self.df_resid = np.nan
    super(GenericLikelihoodModel, self).initialize()
# Buggy code
def _cov_alpha(self):
    """
    Estimated covariance matrix of model coefficients ex intercept
    """
    # drop intercept
    return self.cov_params[self.neqs :, self.neqs :]


# Traceback (ValueError)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/dist-packages/statsmodels/tsa/vector_ar/irf.py", line 138, in plot
stderr = self.cov(orth=orth)
File "/usr/lib/python2.7/dist-packages/statsmodels/tsa/vector_ar/irf.py", line 264, in cov
covs[i] = chain_dot(Gi, self.cov_a, Gi.T)
File "/usr/lib/python2.7/dist-packages/statsmodels/tools/tools.py", line 460, in chain_dot
return reduce(lambda x, y: np.dot(y, x), arrs[::-1])
File "/usr/lib/python2.7/dist-packages/statsmodels/tools/tools.py", line 460, in <lambda>
return reduce(lambda x, y: np.dot(y, x), arrs[::-1])
ValueError: matrices are not aligned

# Fixed code
def _cov_alpha(self):
    """
    Estimated covariance matrix of model coefficients ex intercept
    """
    # drop intercept and trend
    return self.cov_params[self.k_trend * self.neqs :, self.k_trend * self.neqs :]
# Buggy code
def __init__(self, endog, exog=None, missing="none", hasconst=None, **kwargs):
    if missing != "none":
        arrays, nan_idx = self.handle_missing(endog, exog, missing, **kwargs)
        self.missing_row_idx = nan_idx
        self.__dict__.update(arrays)  # attach all the data arrays
        self.orig_endog = self.endog
        self.orig_exog = self.exog
        self.endog, self.exog = self._convert_endog_exog(self.endog, self.exog)
    else:
        self.__dict__.update(kwargs)  # attach the extra arrays anyway
        self.orig_endog = endog
        self.orig_exog = exog
        self.endog, self.exog = self._convert_endog_exog(endog, exog)

    # this has side-effects, attaches k_constant and const_idx
    self._handle_constant(hasconst)
    self._check_integrity()
    self._cache = resettable_cache()


# Traceback (AttributeError)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/dist-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 540, in runfile
execfile(filename, namespace)
File "/home/adrian/Desktop/ToDo/statsmodels_debugging/OLS.py", line 34, in <module>
fit.predict( exog=data[:-1] ) # fails
File "/usr/local/lib/python2.7/dist-packages/statsmodels-0.6.1-py2.7-linux-i686.egg/statsmodels/base/model.py", line 739, in predict
exog = dmatrix(self.model.data.orig_exog.design_info.builder,
File "/usr/local/lib/python2.7/dist-packages/pandas/core/generic.py", line 1936, in __getattr__
(type(self).__name__, name))
AttributeError: 'DataFrame' object has no attribute 'design_info'

# Fixed code
def __init__(self, endog, exog=None, missing="none", hasconst=None, **kwargs):
    if "design_info" in kwargs:
        self.design_info = kwargs.pop("design_info")
    if missing != "none":
        arrays, nan_idx = self.handle_missing(endog, exog, missing, **kwargs)
        self.missing_row_idx = nan_idx
        self.__dict__.update(arrays)  # attach all the data arrays
        self.orig_endog = self.endog
        self.orig_exog = self.exog
        self.endog, self.exog = self._convert_endog_exog(self.endog, self.exog)
    else:
        self.__dict__.update(kwargs)  # attach the extra arrays anyway
        self.orig_endog = endog
        self.orig_exog = exog
        self.endog, self.exog = self._convert_endog_exog(endog, exog)

    # this has side-effects, attaches k_constant and const_idx
    self._handle_constant(hasconst)
    self._check_integrity()
    self._cache = resettable_cache()
# Buggy code
def _handle_data(self, endog, exog, missing, hasconst, **kwargs):
    data = handle_data(endog, exog, missing, hasconst, **kwargs)
    # kwargs arrays could have changed, easier to just attach here
    for key in kwargs:
        # pop so we don't start keeping all these twice or references
        try:
            setattr(self, key, data.__dict__.pop(key))
        except KeyError:  # panel already pops keys in data handling
            pass
    return data


# Traceback (AttributeError)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/dist-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 540, in runfile
execfile(filename, namespace)
File "/home/adrian/Desktop/ToDo/statsmodels_debugging/OLS.py", line 34, in <module>
fit.predict( exog=data[:-1] ) # fails
File "/usr/local/lib/python2.7/dist-packages/statsmodels-0.6.1-py2.7-linux-i686.egg/statsmodels/base/model.py", line 739, in predict
exog = dmatrix(self.model.data.orig_exog.design_info.builder,
File "/usr/local/lib/python2.7/dist-packages/pandas/core/generic.py", line 1936, in __getattr__
(type(self).__name__, name))
AttributeError: 'DataFrame' object has no attribute 'design_info'

# Fixed code
def _handle_data(self, endog, exog, missing, hasconst, **kwargs):
    data = handle_data(endog, exog, missing, hasconst, **kwargs)
    # kwargs arrays could have changed, easier to just attach here
    for key in kwargs:
        if key == "design_info":  # leave this attached to data
            continue
        # pop so we don't start keeping all these twice or references
        try:
            setattr(self, key, data.__dict__.pop(key))
        except KeyError:  # panel already pops keys in data handling
            pass
    return data
# Buggy code
def _isdummy(X):
    """
    Given an array X, returns the column indices for the dummy variables.

    Parameters
    ----------
    X : array-like
        A 1d or 2d array of numbers

    Examples
    --------
    >>> X = np.random.randint(0, 2, size=(15,5)).astype(float)
    >>> X[:,1:3] = np.random.randn(15,2)
    >>> ind = _isdummy(X)
    >>> ind
    array([ True, False, False,  True,  True], dtype=bool)
    """
    X = np.asarray(X)
    if X.ndim > 1:
        ind = np.zeros(X.shape[1]).astype(bool)
    max = np.max(X, axis=0) == 1
    min = np.min(X, axis=0) == 0
    remainder = np.all(X % 1.0 == 0, axis=0)
    ind = min & max & remainder
    if X.ndim == 1:
        ind = np.asarray([ind])
    return ind


# Traceback (TypeError)
======================================================================
ERROR: statsmodels.discrete.tests.test_discrete.TestLogitNewton.test_dummy_dydxmean
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/nose-1.1.2-py2.6.egg/nose/case.py", line 197, in runTest
self.test(*self.arg)
File "/Users/rgommers/Code/statsmodels/statsmodels/discrete/tests/test_discrete.py", line 183, in test_dummy_dydxmean
assert_almost_equal(self.res1.margeff(at='mean', dummy=True),
File "/Users/rgommers/Code/statsmodels/statsmodels/discrete/discrete_model.py", line 1664, in margeff
dummy_ind[const_idx:] -= 1
TypeError: Cannot cast ufunc subtract output from dtype('int32') to dtype('bool') with casting rule 'same_kind'

# Fixed code
def _isdummy(X):
    """
    Given an array X, returns the column indices for the dummy variables.

    Parameters
    ----------
    X : array-like
        A 1d or 2d array of numbers

    Examples
    --------
    >>> X = np.random.randint(0, 2, size=(15,5)).astype(float)
    >>> X[:,1:3] = np.random.randn(15,2)
    >>> ind = _isdummy(X)
    >>> ind
    array([ True, False, False,  True,  True], dtype=bool)
    """
    X = np.asarray(X)
    if X.ndim > 1:
        ind = np.zeros(X.shape[1]).astype(bool)
    max = np.max(X, axis=0) == 1
    min = np.min(X, axis=0) == 0
    remainder = np.all(X % 1.0 == 0, axis=0)
    ind = min & max & remainder
    if X.ndim == 1:
        ind = np.asarray([ind])
    return np.where(ind)[0]