gurudesh/pytracebugs huggingface dataset:
# Buggy code
def _isna_new(obj):
    if is_scalar(obj):
        return libmissing.checknull(obj)
    # hack (for now) because MI registers as ndarray
    elif isinstance(obj, ABCMultiIndex):
        raise NotImplementedError("isna is not defined for MultiIndex")
    elif isinstance(
        obj,
        (
            ABCSeries,
            np.ndarray,
            ABCIndexClass,
            ABCExtensionArray,
            ABCDatetimeArray,
            ABCTimedeltaArray,
        ),
    ):
        return _isna_ndarraylike(obj)
    elif isinstance(obj, ABCGeneric):
        return obj._constructor(obj._data.isna(func=isna))
    elif isinstance(obj, list):
        return _isna_ndarraylike(np.asarray(obj, dtype=object))
    elif hasattr(obj, "__array__"):
        return _isna_ndarraylike(np.asarray(obj))
    else:
        return obj is None


# Traceback (AttributeError)
import pandas as pd

x = pd.Series([1,2,3,4])
xt = type(x)
pd.isnull(xt)
## Traceback (most recent call last):
##   File "<input>", line 1, in <module>
##   File "/home/bbassett/venv37/lib/python3.7/site-packages/pandas/core/dtypes/missing.py", line 122, in isna
##     return _isna(obj)
##   File "/home/bbassett/venv37/lib/python3.7/site-packages/pandas/core/dtypes/missing.py", line 145, in _isna_new
##     return _isna_ndarraylike(obj)
##   File "/home/bbassett/venv37/lib/python3.7/site-packages/pandas/core/dtypes/missing.py", line 225, in _isna_ndarraylike
##     dtype = values.dtype
## AttributeError: 'property' object has no attribute 'dtype'

y = pd.DataFrame({"col": [1,2,3,4]})
yt = type(y)
pd.isnull(yt)
## Traceback (most recent call last):
##   File "<input>", line 1, in <module>
##   File "/home/bbassett/venv37/lib/python3.7/site-packages/pandas/core/dtypes/missing.py", line 122, in isna
##     return _isna(obj)
##   File "/home/bbassett/venv37/lib/python3.7/site-packages/pandas/core/dtypes/missing.py", line 147, in _isna_new
##     return obj._constructor(obj._data.isna(func=isna))
## AttributeError: 'NoneType' object has no attribute 'isna'

# Fixed code
def _isna_new(obj):
    if is_scalar(obj):
        return libmissing.checknull(obj)
    # hack (for now) because MI registers as ndarray
    elif isinstance(obj, ABCMultiIndex):
        raise NotImplementedError("isna is not defined for MultiIndex")
    elif isinstance(obj, type):
        return False
    elif isinstance(
        obj,
        (
            ABCSeries,
            np.ndarray,
            ABCIndexClass,
            ABCExtensionArray,
            ABCDatetimeArray,
            ABCTimedeltaArray,
        ),
    ):
        return _isna_ndarraylike(obj)
    elif isinstance(obj, ABCGeneric):
        return obj._constructor(obj._data.isna(func=isna))
    elif isinstance(obj, list):
        return _isna_ndarraylike(np.asarray(obj, dtype=object))
    elif hasattr(obj, "__array__"):
        return _isna_ndarraylike(np.asarray(obj))
    else:
        return obj is None
# Buggy code
def _isna_old(obj):
    """Detect missing values. Treat None, NaN, INF, -INF as null.

    Parameters
    ----------
    arr: ndarray or object value

    Returns
    -------
    boolean ndarray or boolean
    """
    if is_scalar(obj):
        return libmissing.checknull_old(obj)
    # hack (for now) because MI registers as ndarray
    elif isinstance(obj, ABCMultiIndex):
        raise NotImplementedError("isna is not defined for MultiIndex")
    elif isinstance(obj, (ABCSeries, np.ndarray, ABCIndexClass)):
        return _isna_ndarraylike_old(obj)
    elif isinstance(obj, ABCGeneric):
        return obj._constructor(obj._data.isna(func=_isna_old))
    elif isinstance(obj, list):
        return _isna_ndarraylike_old(np.asarray(obj, dtype=object))
    elif hasattr(obj, "__array__"):
        return _isna_ndarraylike_old(np.asarray(obj))
    else:
        return obj is None


# Traceback (AttributeError)
import pandas as pd

x = pd.Series([1,2,3,4])
xt = type(x)
pd.isnull(xt)
## Traceback (most recent call last):
##   File "<input>", line 1, in <module>
##   File "/home/bbassett/venv37/lib/python3.7/site-packages/pandas/core/dtypes/missing.py", line 122, in isna
##     return _isna(obj)
##   File "/home/bbassett/venv37/lib/python3.7/site-packages/pandas/core/dtypes/missing.py", line 145, in _isna_new
##     return _isna_ndarraylike(obj)
##   File "/home/bbassett/venv37/lib/python3.7/site-packages/pandas/core/dtypes/missing.py", line 225, in _isna_ndarraylike
##     dtype = values.dtype
## AttributeError: 'property' object has no attribute 'dtype'

y = pd.DataFrame({"col": [1,2,3,4]})
yt = type(y)
pd.isnull(yt)
## Traceback (most recent call last):
##   File "<input>", line 1, in <module>
##   File "/home/bbassett/venv37/lib/python3.7/site-packages/pandas/core/dtypes/missing.py", line 122, in isna
##     return _isna(obj)
##   File "/home/bbassett/venv37/lib/python3.7/site-packages/pandas/core/dtypes/missing.py", line 147, in _isna_new
##     return obj._constructor(obj._data.isna(func=isna))
## AttributeError: 'NoneType' object has no attribute 'isna'

# Fixed code
def _isna_old(obj):
    """Detect missing values. Treat None, NaN, INF, -INF as null.

    Parameters
    ----------
    arr: ndarray or object value

    Returns
    -------
    boolean ndarray or boolean
    """
    if is_scalar(obj):
        return libmissing.checknull_old(obj)
    # hack (for now) because MI registers as ndarray
    elif isinstance(obj, ABCMultiIndex):
        raise NotImplementedError("isna is not defined for MultiIndex")
    elif isinstance(obj, type):
        return False
    elif isinstance(obj, (ABCSeries, np.ndarray, ABCIndexClass)):
        return _isna_ndarraylike_old(obj)
    elif isinstance(obj, ABCGeneric):
        return obj._constructor(obj._data.isna(func=_isna_old))
    elif isinstance(obj, list):
        return _isna_ndarraylike_old(np.asarray(obj, dtype=object))
    elif hasattr(obj, "__array__"):
        return _isna_ndarraylike_old(np.asarray(obj))
    else:
        return obj is None
# Buggy code
def flip(xs):
    """unlike np.transpose, this returns an array of tuples"""
    labels = list(string.ascii_lowercase[: len(xs)])
    dtypes = [x.dtype for x in xs]
    labeled_dtypes = list(zip(labels, dtypes))
    return np.array(list(zip(*xs)), labeled_dtypes)


# Traceback (SystemError)
Traceback (most recent call last):
File "test.py", line 13, in <module>
pd.merge_asof(left, right, by=['by_col1', 'by_col2'], on='on_col')
File "myenv/lib/python3.6/site-packages/pandas/core/reshape/merge.py", line 462, in merge_asof
return op.get_result()
File "myenv/lib/python3.6/site-packages/pandas/core/reshape/merge.py", line 1256, in get_result
join_index, left_indexer, right_indexer = self._get_join_info()
File "myenv/lib/python3.6/site-packages/pandas/core/reshape/merge.py", line 756, in _get_join_info
right_indexer) = self._get_join_indexers()
File "myenv/lib/python3.6/site-packages/pandas/core/reshape/merge.py", line 1504, in _get_join_indexers
left_by_values = flip(left_by_values)
File "myenv/lib/python3.6/site-packages/pandas/core/reshape/merge.py", line 1457, in flip
return np.array(lzip(*xs), labeled_dtypes)
File "myenv/lib/python3.6/site-packages/pandas/core/dtypes/dtypes.py", line 150, in __repr__
return str(self)
File "myenv/lib/python3.6/site-packages/pandas/core/dtypes/dtypes.py", line 129, in __str__
return self.__unicode__()
File "myenv/lib/python3.6/site-packages/pandas/core/dtypes/dtypes.py", line 704, in __unicode__
return "datetime64[{unit}, {tz}]".format(unit=self.unit, tz=self.tz)
SystemError: PyEval_EvalFrameEx returned a result with an error set

# Fixed code
def flip(xs):
    """unlike np.transpose, this returns an array of tuples"""
    xs = [x if not is_extension_array_dtype(x) else x._ndarray_values for x in xs]
    labels = list(string.ascii_lowercase[: len(xs)])
    dtypes = [x.dtype for x in xs]
    labeled_dtypes = list(zip(labels, dtypes))
    return np.array(list(zip(*xs)), labeled_dtypes)
# Buggy code
def _get_value(self, index, col, takeable=False):
    if takeable:
        series = self._iget_item_cache(col)
        return com.maybe_box_datetimelike(series._values[index])

    series = self._get_item_cache(col)
    engine = self.index._engine

    try:
        return engine.get_value(series._values, index)
    except (TypeError, ValueError):
        # we cannot handle direct indexing
        # use positional
        col = self.columns.get_loc(col)
        index = self.index.get_loc(index)
        return self._get_value(index, col, takeable=True)


# Traceback (AttributeError)
Python 3.6.3 (default, Oct  3 2017, 21:45:48)
[GCC 7.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
import pandas as pd
x = pd.Series([1, 2, 3], index=pd.CategoricalIndex(["A", "B", "C"]))
x.loc["A"]
1
x.at["A"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.6/dist-packages/pandas/core/indexing.py", line 1869, in __getitem__
return self.obj._get_value(*key, takeable=self._takeable)
File "/usr/local/lib/python3.6/dist-packages/pandas/core/series.py", line 929, in _get_value
return self.index.get_value(self._values, label)
File "/usr/local/lib/python3.6/dist-packages/pandas/core/indexes/category.py", line 423, in get_value
return series.iloc[indexer]
AttributeError: 'numpy.ndarray' object has no attribute 'iloc'
x = pd.DataFrame([[1, 2], [3, 4], [5, 6]], index=pd.CategoricalIndex(["A", "B", "C"]))
x.loc["B", 1]
4
x.at["B", 1]
Traceback (most recent call last):
File "pandas/_libs/index.pyx", line 139, in pandas._libs.index.IndexEngine.get_loc
File "pandas/_libs/hashtable_class_helper.pxi", line 811, in pandas._libs.hashtable.Int64HashTable.get_item
TypeError: an integer is required

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.6/dist-packages/pandas/core/indexing.py", line 1869, in __getitem__
return self.obj._get_value(*key, takeable=self._takeable)
File "/usr/local/lib/python3.6/dist-packages/pandas/core/frame.py", line 1985, in _get_value
return engine.get_value(series._values, index)
File "pandas/_libs/index.pyx", line 83, in pandas._libs.index.IndexEngine.get_value
File "pandas/_libs/index.pyx", line 91, in pandas._libs.index.IndexEngine.get_value
File "pandas/_libs/index.pyx", line 141, in pandas._libs.index.IndexEngine.get_loc
KeyError: 'B'

# Fixed code
def _get_value(self, index, col, takeable=False):
    if takeable:
        series = self._iget_item_cache(col)
        return com.maybe_box_datetimelike(series._values[index])

    series = self._get_item_cache(col)
    engine = self.index._engine

    try:
        return engine.get_value(series._values, index)
    except KeyError:
        # GH 20629
        if self.index.nlevels > 1:
            # partial indexing forbidden
            raise
    except (TypeError, ValueError):
        pass

    # we cannot handle direct indexing
    # use positional
    col = self.columns.get_loc(col)
    index = self.index.get_loc(index)
    return self._get_value(index, col, takeable=True)
# Buggy code
def _construct_result(left, result, index, name, dtype=None):
    """
    If the raw op result has a non-None name (e.g. it is an Index object) and
    the name argument is None, then passing name to the constructor will
    not be enough; we still need to override the name attribute.
    """
    out = left._constructor(result, index=index, dtype=dtype)

    out.name = name
    return out


# Traceback (ValueError)
a.divmod(b)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/danlaw/Projects/pandas/pandas/core/ops.py", line 1892, in flex_wrapper
return self._binop(other, op, level=level, fill_value=fill_value)
File "/Users/danlaw/Projects/pandas/pandas/core/series.py", line 2522, in _binop
result = self._constructor(result, index=new_index, name=name)
File "/Users/danlaw/Projects/pandas/pandas/core/series.py", line 250, in __init__
.format(val=len(data), ind=len(index)))
ValueError: Length of passed values is 2, index implies 4

# Fixed code
def _construct_result(left, result, index, name, dtype=None):
    """
    If the raw op result has a non-None name (e.g. it is an Index object) and
    the name argument is None, then passing name to the constructor will
    not be enough; we still need to override the name attribute.
    """
    out = left._constructor(result, index=index, dtype=dtype)
    out = out.__finalize__(left)
    out.name = name
    return out
# Buggy code
def _construct_divmod_result(left, result, index, name, dtype=None):
    """divmod returns a tuple of like indexed series instead of a single series."""
    constructor = left._constructor
    return (
        constructor(result[0], index=index, name=name, dtype=dtype),
        constructor(result[1], index=index, name=name, dtype=dtype),
    )


# Traceback (ValueError)
a.divmod(b)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/danlaw/Projects/pandas/pandas/core/ops.py", line 1892, in flex_wrapper
return self._binop(other, op, level=level, fill_value=fill_value)
File "/Users/danlaw/Projects/pandas/pandas/core/series.py", line 2522, in _binop
result = self._constructor(result, index=new_index, name=name)
File "/Users/danlaw/Projects/pandas/pandas/core/series.py", line 250, in __init__
.format(val=len(data), ind=len(index)))
ValueError: Length of passed values is 2, index implies 4

# Fixed code
def _construct_divmod_result(left, result, index, name, dtype=None):
    """divmod returns a tuple of like indexed series instead of a single series."""
    return (
        _construct_result(left, result[0], index=index, name=name, dtype=dtype),
        _construct_result(left, result[1], index=index, name=name, dtype=dtype),
    )
# Buggy code
def _non_reducing_slice(slice_):
    """
    Ensurse that a slice doesn't reduce to a Series or Scalar.

    Any user-paseed `subset` should have this called on it
    to make sure we're always working with DataFrames.
    """
    # default to column slice, like DataFrame
    # ['A', 'B'] -> IndexSlices[:, ['A', 'B']]
    kinds = tuple(list(compat.string_types) + [ABCSeries, np.ndarray, Index, list])
    if isinstance(slice_, kinds):
        slice_ = IndexSlice[:, slice_]

    def pred(part):
        # true when slice does *not* reduce
        return isinstance(part, slice) or is_list_like(part)

    if not is_list_like(slice_):
        if not isinstance(slice_, slice):
            # a 1-d slice, like df.loc[1]
            slice_ = [[slice_]]
        else:
            # slice(a, b, c)
            slice_ = [slice_]  # to tuplize later
    else:
        slice_ = [part if pred(part) else [part] for part in slice_]
    return tuple(slice_)


# Traceback (AttributeError)
Traceback (most recent call last):
File "<stdin>", line 5, in <module>
File "c:\Users\user\AppData\Local\Continuum\Miniconda3\envs\lg\lib\site-packages\pandas\io\formats\style.py", line 434, in render
self._compute()
File "c:\Users\user\AppData\Local\Continuum\Miniconda3\envs\lg\lib\site-packages\pandas\io\formats\style.py", line 502, in _compute
r = func(self)(*args, **kwargs)
File "c:\Users\user\AppData\Local\Continuum\Miniconda3\envs\lg\lib\site-packages\pandas\io\formats\style.py", line 591, in _applymap
result = self.data.loc[subset].applymap(func)
File "c:\Users\user\AppData\Local\Continuum\Miniconda3\envs\lg\lib\site-packages\pandas\core\generic.py", line 3081, in __getattr__
return object.__getattribute__(self, name)
AttributeError: 'Series' object has no attribute 'applymap'

# Fixed code
def _non_reducing_slice(slice_):
    """
    Ensurse that a slice doesn't reduce to a Series or Scalar.

    Any user-paseed `subset` should have this called on it
    to make sure we're always working with DataFrames.
    """
    # default to column slice, like DataFrame
    # ['A', 'B'] -> IndexSlices[:, ['A', 'B']]
    kinds = tuple(list(compat.string_types) + [ABCSeries, np.ndarray, Index, list])
    if isinstance(slice_, kinds):
        slice_ = IndexSlice[:, slice_]

    def pred(part):
        # true when slice does *not* reduce, False when part is a tuple,
        # i.e. MultiIndex slice
        return (isinstance(part, slice) or is_list_like(part)) and not isinstance(
            part, tuple
        )

    if not is_list_like(slice_):
        if not isinstance(slice_, slice):
            # a 1-d slice, like df.loc[1]
            slice_ = [[slice_]]
        else:
            # slice(a, b, c)
            slice_ = [slice_]  # to tuplize later
    else:
        slice_ = [part if pred(part) else [part] for part in slice_]
    return tuple(slice_)
# Buggy code
def pred(part):
    # true when slice does *not* reduce
    return isinstance(part, slice) or is_list_like(part)


# Traceback (AttributeError)
Traceback (most recent call last):
File "<stdin>", line 5, in <module>
File "c:\Users\user\AppData\Local\Continuum\Miniconda3\envs\lg\lib\site-packages\pandas\io\formats\style.py", line 434, in render
self._compute()
File "c:\Users\user\AppData\Local\Continuum\Miniconda3\envs\lg\lib\site-packages\pandas\io\formats\style.py", line 502, in _compute
r = func(self)(*args, **kwargs)
File "c:\Users\user\AppData\Local\Continuum\Miniconda3\envs\lg\lib\site-packages\pandas\io\formats\style.py", line 591, in _applymap
result = self.data.loc[subset].applymap(func)
File "c:\Users\user\AppData\Local\Continuum\Miniconda3\envs\lg\lib\site-packages\pandas\core\generic.py", line 3081, in __getattr__
return object.__getattribute__(self, name)
AttributeError: 'Series' object has no attribute 'applymap'

# Fixed code
def pred(part):
    # true when slice does *not* reduce, False when part is a tuple,
    # i.e. MultiIndex slice
    return (isinstance(part, slice) or is_list_like(part)) and not isinstance(
        part, tuple
    )
# Buggy code
def _has_bool_dtype(x):
    try:
        return x.dtype == bool
    except AttributeError:
        try:
            return "bool" in x.dtypes
        except AttributeError:
            return isinstance(x, (bool, np.bool_))


# Traceback (ValueError)
In [8]: df.loc[:, ['a','dtype']].ne(df.loc[:, ['a', 'dtype']])
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-8-a0710f18822f> in <module>()
----> 1 df.loc[:, ['a','dtype']].ne(df.loc[:, ['a', 'dtype']])

/home/blistein/env/aan/local/lib/python2.7/site-packages/pandas/core/ops.pyc in f(self, other, axis, level)
1588                 self, other = self.align(other, 'outer',
1589                                          level=level, copy=False)
-> 1590             return self._compare_frame(other, na_op, str_rep)
1591
1592         elif isinstance(other, ABCSeries):

/home/blistein/env/aan/local/lib/python2.7/site-packages/pandas/core/frame.pyc in _compare_frame(self, other, func, str_rep)
4790                 return {col: func(a[col], b[col]) for col in a.columns}
4791
-> 4792             new_data = expressions.evaluate(_compare, str_rep, self, other)
4793             return self._constructor(data=new_data, index=self.index,
4794                                      columns=self.columns, copy=False)

/home/blistein/env/aan/local/lib/python2.7/site-packages/pandas/core/computation/expressions.pyc in evaluate(op, op_str, a, b, use_numexpr, **eval_kwargs)
201         """
202
--> 203     use_numexpr = use_numexpr and _bool_arith_check(op_str, a, b)
204     if use_numexpr:
205         return _evaluate(op, op_str, a, b, **eval_kwargs)

/home/blistein/env/aan/local/lib/python2.7/site-packages/pandas/core/computation/expressions.pyc in _bool_arith_check(op_str, a, b, not_allowed, unsupported)
173         unsupported = {'+': '|', '*': '&amp;', '-': '^'}
174
--> 175     if _has_bool_dtype(a) and _has_bool_dtype(b):
176         if op_str in unsupported:
177             warnings.warn("evaluating in Python space because the {op!r} "

/home/blistein/env/aan/local/lib/python2.7/site-packages/pandas/core/generic.pyc in __nonzero__(self)
1574         raise ValueError("The truth value of a {0} is ambiguous. "
1575                          "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
-> 1576                          .format(self.__class__.__name__))
1577
1578     __bool__ = __nonzero__

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

# Fixed code
def _has_bool_dtype(x):
    try:
        if isinstance(x, ABCDataFrame):
            return "bool" in x.dtypes
        else:
            return x.dtype == bool
    except AttributeError:
        return isinstance(x, (bool, np.bool_))
# Buggy code
def wrapper(self, other):
    if _is_convertible_to_td(other) or other is NaT:
        try:
            other = _to_m8(other)
        except ValueError:
            # failed to parse as timedelta
            return ops.invalid_comparison(self, other, op)

        result = meth(self, other)
        if isna(other):
            result.fill(nat_result)

    elif not is_list_like(other):
        return ops.invalid_comparison(self, other, op)

    else:
        try:
            other = type(self)._from_sequence(other)._data
        except (ValueError, TypeError):
            return ops.invalid_comparison(self, other, op)

        result = meth(self, other)
        result = com.values_from_object(result)

        o_mask = np.array(isna(other))
        if o_mask.any():
            result[o_mask] = nat_result

    if self._hasnans:
        result[self._isnan] = nat_result

    return result


# Traceback (ValueError)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-8-8a2a887e6efd> in <module>
----> 1 idx <= idx[[0]]

~/sandbox/pandas/pandas/core/indexes/datetimes.py in wrapper(self, other)
90
91     def wrapper(self, other):
---> 92         result = getattr(DatetimeArrayMixin, opname)(self, other)
93         if is_bool_dtype(result):
94             return result

~/sandbox/pandas/pandas/core/arrays/datetimes.py in wrapper(self, other)
133             else:
134                 self._assert_tzawareness_compat(other)
--> 135                 result = meth(self, np.asarray(other))
136
137             result = com.values_from_object(result)

~/sandbox/pandas/pandas/core/arrays/datetimelike.py in cmp_method(self, other)
51         if isinstance(other, (np.ndarray, ABCIndexClass, ABCSeries)):
52             if other.ndim > 0 and len(self) != len(other):
---> 53                 raise ValueError('Lengths must match to compare')
54
55         if needs_i8_conversion(self) and needs_i8_conversion(other):

ValueError: Lengths must match to compare

# Fixed code
def wrapper(self, other):
    if _is_convertible_to_td(other) or other is NaT:
        try:
            other = _to_m8(other)
        except ValueError:
            # failed to parse as timedelta
            return ops.invalid_comparison(self, other, op)

        result = meth(self, other)
        if isna(other):
            result.fill(nat_result)

    elif not is_list_like(other):
        return ops.invalid_comparison(self, other, op)

    elif len(other) != len(self):
        raise ValueError("Lengths must match")

    else:
        try:
            other = type(self)._from_sequence(other)._data
        except (ValueError, TypeError):
            return ops.invalid_comparison(self, other, op)

        result = meth(self, other)
        result = com.values_from_object(result)

        o_mask = np.array(isna(other))
        if o_mask.any():
            result[o_mask] = nat_result

    if self._hasnans:
        result[self._isnan] = nat_result

    return result
# Buggy code
def _add_numeric_methods_unary(cls):
    """
    Add in numeric unary methods.
    """

    def _make_evaluate_unary(op, opstr):
        def _evaluate_numeric_unary(self):
            self._validate_for_numeric_unaryop(op, opstr)
            attrs = self._get_attributes_dict()
            attrs = self._maybe_update_attributes(attrs)
            return Index(op(self.values), **attrs)

        return _evaluate_numeric_unary

    cls.__neg__ = _make_evaluate_unary(operator.neg, "__neg__")
    cls.__pos__ = _make_evaluate_unary(operator.pos, "__pos__")
    cls.__abs__ = _make_evaluate_unary(np.abs, "__abs__")
    cls.__inv__ = _make_evaluate_unary(lambda x: -x, "__inv__")


# Traceback (ValueError)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-8-8a2a887e6efd> in <module>
----> 1 idx <= idx[[0]]

~/sandbox/pandas/pandas/core/indexes/datetimes.py in wrapper(self, other)
90
91     def wrapper(self, other):
---> 92         result = getattr(DatetimeArrayMixin, opname)(self, other)
93         if is_bool_dtype(result):
94             return result

~/sandbox/pandas/pandas/core/arrays/datetimes.py in wrapper(self, other)
133             else:
134                 self._assert_tzawareness_compat(other)
--> 135                 result = meth(self, np.asarray(other))
136
137             result = com.values_from_object(result)

~/sandbox/pandas/pandas/core/arrays/datetimelike.py in cmp_method(self, other)
51         if isinstance(other, (np.ndarray, ABCIndexClass, ABCSeries)):
52             if other.ndim > 0 and len(self) != len(other):
---> 53                 raise ValueError('Lengths must match to compare')
54
55         if needs_i8_conversion(self) and needs_i8_conversion(other):

ValueError: Lengths must match to compare

# Fixed code
def _add_numeric_methods_unary(cls):
    """
    Add in numeric unary methods.
    """

    def _make_evaluate_unary(op, opstr):
        def _evaluate_numeric_unary(self):
            self._validate_for_numeric_unaryop(op, opstr)
            attrs = self._get_attributes_dict()
            attrs = self._maybe_update_attributes(attrs)
            return Index(op(self.values), **attrs)

        _evaluate_numeric_unary.__name__ = opstr
        return _evaluate_numeric_unary

    cls.__neg__ = _make_evaluate_unary(operator.neg, "__neg__")
    cls.__pos__ = _make_evaluate_unary(operator.pos, "__pos__")
    cls.__abs__ = _make_evaluate_unary(np.abs, "__abs__")
    cls.__inv__ = _make_evaluate_unary(lambda x: -x, "__inv__")
# Buggy code
def _make_evaluate_unary(op, opstr):
    def _evaluate_numeric_unary(self):
        self._validate_for_numeric_unaryop(op, opstr)
        attrs = self._get_attributes_dict()
        attrs = self._maybe_update_attributes(attrs)
        return Index(op(self.values), **attrs)

    return _evaluate_numeric_unary


# Traceback (ValueError)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-8-8a2a887e6efd> in <module>
----> 1 idx <= idx[[0]]

~/sandbox/pandas/pandas/core/indexes/datetimes.py in wrapper(self, other)
90
91     def wrapper(self, other):
---> 92         result = getattr(DatetimeArrayMixin, opname)(self, other)
93         if is_bool_dtype(result):
94             return result

~/sandbox/pandas/pandas/core/arrays/datetimes.py in wrapper(self, other)
133             else:
134                 self._assert_tzawareness_compat(other)
--> 135                 result = meth(self, np.asarray(other))
136
137             result = com.values_from_object(result)

~/sandbox/pandas/pandas/core/arrays/datetimelike.py in cmp_method(self, other)
51         if isinstance(other, (np.ndarray, ABCIndexClass, ABCSeries)):
52             if other.ndim > 0 and len(self) != len(other):
---> 53                 raise ValueError('Lengths must match to compare')
54
55         if needs_i8_conversion(self) and needs_i8_conversion(other):

ValueError: Lengths must match to compare

# Fixed code
def _make_evaluate_unary(op, opstr):
    def _evaluate_numeric_unary(self):
        self._validate_for_numeric_unaryop(op, opstr)
        attrs = self._get_attributes_dict()
        attrs = self._maybe_update_attributes(attrs)
        return Index(op(self.values), **attrs)

    _evaluate_numeric_unary.__name__ = opstr
    return _evaluate_numeric_unary
# Buggy code
def _wrap_inplace_method(method):
    """
    return an inplace wrapper for this method
    """

    def f(self, other):
        result = method(self, other)

        # this makes sure that we are aligned like the input
        # we are updating inplace so we want to ignore is_copy
        self._update_inplace(
            result.reindex_like(self, copy=False)._data, verify_is_copy=False
        )

        return self

    return f


# Traceback (ValueError)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-8-8a2a887e6efd> in <module>
----> 1 idx <= idx[[0]]

~/sandbox/pandas/pandas/core/indexes/datetimes.py in wrapper(self, other)
90
91     def wrapper(self, other):
---> 92         result = getattr(DatetimeArrayMixin, opname)(self, other)
93         if is_bool_dtype(result):
94             return result

~/sandbox/pandas/pandas/core/arrays/datetimes.py in wrapper(self, other)
133             else:
134                 self._assert_tzawareness_compat(other)
--> 135                 result = meth(self, np.asarray(other))
136
137             result = com.values_from_object(result)

~/sandbox/pandas/pandas/core/arrays/datetimelike.py in cmp_method(self, other)
51         if isinstance(other, (np.ndarray, ABCIndexClass, ABCSeries)):
52             if other.ndim > 0 and len(self) != len(other):
---> 53                 raise ValueError('Lengths must match to compare')
54
55         if needs_i8_conversion(self) and needs_i8_conversion(other):

ValueError: Lengths must match to compare

# Fixed code
def _wrap_inplace_method(method):
    """
    return an inplace wrapper for this method
    """

    def f(self, other):
        result = method(self, other)

        # this makes sure that we are aligned like the input
        # we are updating inplace so we want to ignore is_copy
        self._update_inplace(
            result.reindex_like(self, copy=False)._data, verify_is_copy=False
        )

        return self

    f.__name__ = "__i{name}__".format(name=method.__name__.strip("__"))
    return f
# Buggy code
def _coerce_method(converter):
    """
    Install the scalar coercion methods.
    """

    def wrapper(self):
        if len(self) == 1:
            return converter(self.iloc[0])
        raise TypeError("cannot convert the series to {0}".format(str(converter)))

    return wrapper


# Traceback (ValueError)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-8-8a2a887e6efd> in <module>
----> 1 idx <= idx[[0]]

~/sandbox/pandas/pandas/core/indexes/datetimes.py in wrapper(self, other)
90
91     def wrapper(self, other):
---> 92         result = getattr(DatetimeArrayMixin, opname)(self, other)
93         if is_bool_dtype(result):
94             return result

~/sandbox/pandas/pandas/core/arrays/datetimes.py in wrapper(self, other)
133             else:
134                 self._assert_tzawareness_compat(other)
--> 135                 result = meth(self, np.asarray(other))
136
137             result = com.values_from_object(result)

~/sandbox/pandas/pandas/core/arrays/datetimelike.py in cmp_method(self, other)
51         if isinstance(other, (np.ndarray, ABCIndexClass, ABCSeries)):
52             if other.ndim > 0 and len(self) != len(other):
---> 53                 raise ValueError('Lengths must match to compare')
54
55         if needs_i8_conversion(self) and needs_i8_conversion(other):

ValueError: Lengths must match to compare

# Fixed code
def _coerce_method(converter):
    """
    Install the scalar coercion methods.
    """

    def wrapper(self):
        if len(self) == 1:
            return converter(self.iloc[0])
        raise TypeError("cannot convert the series to {0}".format(str(converter)))

    wrapper.__name__ = "__{name}__".format(name=converter.__name__)
    return wrapper
# Buggy code
def _print_as_set(s):
    return "{{arg}}".format(arg=", ".join(pprint_thing(el) for el in s))


# Traceback (ValueError)
import pandas as pd
df_list = pd.read_html('https://google.com', flavor='unknown')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/achabot/envs/tmp-b79b7181308bb9c1/lib/python3.7/site-packages/pandas/io/html.py", line 987, in read_html
displayed_only=displayed_only)
File "/Users/achabot/envs/tmp-b79b7181308bb9c1/lib/python3.7/site-packages/pandas/io/html.py", line 787, in _parse
flavor = _validate_flavor(flavor)
File "/Users/achabot/envs/tmp-b79b7181308bb9c1/lib/python3.7/site-packages/pandas/io/html.py", line 782, in _validate_flavor
valid=_print_as_set(valid_flavors)))
ValueError: {arg} is not a valid set of flavors, valid flavors are {arg}

# Fixed code
def _print_as_set(s):
    return "{" + "{arg}".format(arg=", ".join(pprint_thing(el) for el in s)) + "}"
# Buggy code
def _set_with(self, key, value):
    # other: fancy integer or otherwise
    if isinstance(key, slice):
        indexer = self.index._convert_slice_indexer(key, kind="getitem")
        return self._set_values(indexer, value)
    else:
        if isinstance(key, tuple):
            try:
                self._set_values(key, value)
            except Exception:
                pass

        if not isinstance(key, (list, Series, np.ndarray, Series)):
            try:
                key = list(key)
            except Exception:
                key = [key]

        if isinstance(key, Index):
            key_type = key.inferred_type
        else:
            key_type = lib.infer_dtype(key)

        if key_type == "integer":
            if self.index.inferred_type == "integer":
                self._set_labels(key, value)
            else:
                return self._set_values(key, value)
        elif key_type == "boolean":
            self._set_values(key.astype(np.bool_), value)
        else:
            self._set_labels(key, value)


# Traceback (ValueError)
import pandas
x = pandas.Series([1,2,3],  index=['Date','b','other'])
x
Date     1
b        2
other    3
dtype: int64
from datetime import date
x.Date = date.today()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python37\lib\site-packages\pandas\core\generic.py", line 4405, in __setattr__
self[name] = value
File "C:\Python37\lib\site-packages\pandas\core\series.py", line 939, in __setitem__
setitem(key, value)
File "C:\Python37\lib\site-packages\pandas\core\series.py", line 935, in setitem
self._set_with(key, value)
File "C:\Python37\lib\site-packages\pandas\core\series.py", line 983, in _set_with
self._set_labels(key, value)
File "C:\Python37\lib\site-packages\pandas\core\series.py", line 993, in _set_labels
raise ValueError('%s not contained in the index' % str(key[mask]))
ValueError: ['D' 'a' 't' 'e'] not contained in the index
x.b = date.today()
x.b
datetime.date(2018, 11, 1)
x
Date              1
b        2018-11-01
other             3
dtype: object


# Fixed code
def _set_with(self, key, value):
    # other: fancy integer or otherwise
    if isinstance(key, slice):
        indexer = self.index._convert_slice_indexer(key, kind="getitem")
        return self._set_values(indexer, value)
    else:
        if isinstance(key, tuple):
            try:
                self._set_values(key, value)
            except Exception:
                pass

        if is_scalar(key):
            key = [key]
        elif not isinstance(key, (list, Series, np.ndarray)):
            try:
                key = list(key)
            except Exception:
                key = [key]

        if isinstance(key, Index):
            key_type = key.inferred_type
        else:
            key_type = lib.infer_dtype(key)

        if key_type == "integer":
            if self.index.inferred_type == "integer":
                self._set_labels(key, value)
            else:
                return self._set_values(key, value)
        elif key_type == "boolean":
            self._set_values(key.astype(np.bool_), value)
        else:
            self._set_labels(key, value)
# Buggy code
def _ensure_localized(self, result, ambiguous="raise"):
    """
    ensure that we are re-localized

    This is for compat as we can then call this on all datetimelike
    indexes generally (ignored for Period/Timedelta)

    Parameters
    ----------
    result : DatetimeIndex / i8 ndarray
    ambiguous : str, bool, or bool-ndarray
        default 'raise'

    Returns
    -------
    localized DTI
    """

    # reconvert to local tz
    if getattr(self, "tz", None) is not None:
        if not isinstance(result, ABCIndexClass):
            result = self._simple_new(result)
        result = result.tz_localize(self.tz, ambiguous=ambiguous)
    return result


# Traceback (pytz.exceptions.AmbiguousTimeError)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "(...)/venv/lib/python3.6/site-packages/pandas/core/reshape/merge.py", line 58, in merge
return op.get_result()
File "(...)//venv/lib/python3.6/site-packages/pandas/core/reshape/merge.py", line 604, in get_result
self._maybe_add_join_keys(result, left_indexer, right_indexer)
File "(...)//venv/lib/python3.6/site-packages/pandas/core/reshape/merge.py", line 715, in _maybe_add_join_keys
key_col = Index(lvals).where(~mask, rvals)
File "(...)//venv/lib/python3.6/site-packages/pandas/core/indexes/datetimelike.py", line 809, in where
result = self._ensure_localized(result)
File "(...)//venv/lib/python3.6/site-packages/pandas/core/indexes/datetimelike.py", line 230, in _ensure_localized
result = result.tz_localize(self.tz)
File "(...)//venv/lib/python3.6/site-packages/pandas/util/_decorators.py", line 118, in wrapper
return func(*args, **kwargs)
File "(...)//venv/lib/python3.6/site-packages/pandas/core/indexes/datetimes.py", line 1858, in tz_localize
errors=errors)
File "pandas/_libs/tslib.pyx", line 3593, in pandas._libs.tslib.tz_localize_to_utc
pytz.exceptions.AmbiguousTimeError: Cannot infer dst time from Timestamp('2017-10-29 02:00:00'), try using the 'ambiguous' argument

# Fixed code
def _ensure_localized(self, arg, ambiguous="raise", from_utc=False):
    """
    ensure that we are re-localized

    This is for compat as we can then call this on all datetimelike
    indexes generally (ignored for Period/Timedelta)

    Parameters
    ----------
    arg : DatetimeIndex / i8 ndarray
    ambiguous : str, bool, or bool-ndarray, default 'raise'
    from_utc : bool, default False
        If True, localize the i8 ndarray to UTC first before converting to
        the appropriate tz. If False, localize directly to the tz.

    Returns
    -------
    localized DTI
    """

    # reconvert to local tz
    if getattr(self, "tz", None) is not None:
        if not isinstance(arg, ABCIndexClass):
            arg = self._simple_new(arg)
        if from_utc:
            arg = arg.tz_localize("UTC").tz_convert(self.tz)
        else:
            arg = arg.tz_localize(self.tz, ambiguous=ambiguous)
    return arg
# Buggy code
def where(self, cond, other=None):
    other = _ensure_datetimelike_to_i8(other)
    values = _ensure_datetimelike_to_i8(self)
    result = np.where(cond, values, other).astype("i8")

    result = self._ensure_localized(result)
    return self._shallow_copy(result, **self._get_attributes_dict())


# Traceback (pytz.exceptions.AmbiguousTimeError)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "(...)/venv/lib/python3.6/site-packages/pandas/core/reshape/merge.py", line 58, in merge
return op.get_result()
File "(...)//venv/lib/python3.6/site-packages/pandas/core/reshape/merge.py", line 604, in get_result
self._maybe_add_join_keys(result, left_indexer, right_indexer)
File "(...)//venv/lib/python3.6/site-packages/pandas/core/reshape/merge.py", line 715, in _maybe_add_join_keys
key_col = Index(lvals).where(~mask, rvals)
File "(...)//venv/lib/python3.6/site-packages/pandas/core/indexes/datetimelike.py", line 809, in where
result = self._ensure_localized(result)
File "(...)//venv/lib/python3.6/site-packages/pandas/core/indexes/datetimelike.py", line 230, in _ensure_localized
result = result.tz_localize(self.tz)
File "(...)//venv/lib/python3.6/site-packages/pandas/util/_decorators.py", line 118, in wrapper
return func(*args, **kwargs)
File "(...)//venv/lib/python3.6/site-packages/pandas/core/indexes/datetimes.py", line 1858, in tz_localize
errors=errors)
File "pandas/_libs/tslib.pyx", line 3593, in pandas._libs.tslib.tz_localize_to_utc
pytz.exceptions.AmbiguousTimeError: Cannot infer dst time from Timestamp('2017-10-29 02:00:00'), try using the 'ambiguous' argument

# Fixed code
def where(self, cond, other=None):
    other = _ensure_datetimelike_to_i8(other, to_utc=True)
    values = _ensure_datetimelike_to_i8(self, to_utc=True)
    result = np.where(cond, values, other).astype("i8")

    result = self._ensure_localized(result, from_utc=True)
    return self._shallow_copy(result, **self._get_attributes_dict())
# Buggy code
def _ensure_datetimelike_to_i8(other):
    """helper for coercing an input scalar or array to i8"""
    if is_scalar(other) and isna(other):
        other = iNaT
    elif isinstance(other, ABCIndexClass):
        # convert tz if needed
        if getattr(other, "tz", None) is not None:
            other = other.tz_localize(None).asi8
        else:
            other = other.asi8
    else:
        try:
            other = np.array(other, copy=False).view("i8")
        except TypeError:
            # period array cannot be coerces to int
            other = Index(other).asi8
    return other


# Traceback (pytz.exceptions.AmbiguousTimeError)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "(...)/venv/lib/python3.6/site-packages/pandas/core/reshape/merge.py", line 58, in merge
return op.get_result()
File "(...)//venv/lib/python3.6/site-packages/pandas/core/reshape/merge.py", line 604, in get_result
self._maybe_add_join_keys(result, left_indexer, right_indexer)
File "(...)//venv/lib/python3.6/site-packages/pandas/core/reshape/merge.py", line 715, in _maybe_add_join_keys
key_col = Index(lvals).where(~mask, rvals)
File "(...)//venv/lib/python3.6/site-packages/pandas/core/indexes/datetimelike.py", line 809, in where
result = self._ensure_localized(result)
File "(...)//venv/lib/python3.6/site-packages/pandas/core/indexes/datetimelike.py", line 230, in _ensure_localized
result = result.tz_localize(self.tz)
File "(...)//venv/lib/python3.6/site-packages/pandas/util/_decorators.py", line 118, in wrapper
return func(*args, **kwargs)
File "(...)//venv/lib/python3.6/site-packages/pandas/core/indexes/datetimes.py", line 1858, in tz_localize
errors=errors)
File "pandas/_libs/tslib.pyx", line 3593, in pandas._libs.tslib.tz_localize_to_utc
pytz.exceptions.AmbiguousTimeError: Cannot infer dst time from Timestamp('2017-10-29 02:00:00'), try using the 'ambiguous' argument

# Fixed code
def _ensure_datetimelike_to_i8(other, to_utc=False):
    """
    helper for coercing an input scalar or array to i8

    Parameters
    ----------
    other : 1d array
    to_utc : bool, default False
        If True, convert the values to UTC before extracting the i8 values
        If False, extract the i8 values directly.

    Returns
    -------
    i8 1d array
    """
    if is_scalar(other) and isna(other):
        return iNaT
    elif isinstance(other, ABCIndexClass):
        # convert tz if needed
        if getattr(other, "tz", None) is not None:
            if to_utc:
                other = other.tz_convert("UTC")
            else:
                other = other.tz_localize(None)
    else:
        try:
            return np.array(other, copy=False).view("i8")
        except TypeError:
            # period array cannot be coerces to int
            other = Index(other)
    return other.asi8
# Buggy code
def _round(self, freq, rounder):
    # round the local times
    values = _ensure_datetimelike_to_i8(self)
    result = round_ns(values, rounder, freq)
    result = self._maybe_mask_results(result, fill_value=NaT)

    attribs = self._get_attributes_dict()
    if "freq" in attribs:
        attribs["freq"] = None
    if "tz" in attribs:
        attribs["tz"] = None
    return self._ensure_localized(self._shallow_copy(result, **attribs))


# Traceback (pytz.exceptions.AmbiguousTimeError)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "(...)/venv/lib/python3.6/site-packages/pandas/core/accessor.py", line 115, in f
return self._delegate_method(name, *args, **kwargs)
File "(...)/venv/lib/python3.6/site-packages/pandas/core/indexes/accessors.py", line 131, in _delegate_method
result = method(*args, **kwargs)
File "(...)/venv/lib/python3.6/site-packages/pandas/core/indexes/datetimelike.py", line 118, in floor
return self._round(freq, np.floor)
File "(...)/venv/lib/python3.6/site-packages/pandas/core/indexes/datetimelike.py", line 110, in _round
self._shallow_copy(result, **attribs))
File "(...)/venv/lib/python3.6/site-packages/pandas/core/indexes/datetimelike.py", line 230, in _ensure_localized
result = result.tz_localize(self.tz)
File "(...)/venv/lib/python3.6/site-packages/pandas/util/_decorators.py", line 118, in wrapper
return func(*args, **kwargs)
File "(...)/venv/lib/python3.6/site-packages/pandas/core/indexes/datetimes.py", line 1858, in tz_localize
errors=errors)
File "pandas/_libs/tslib.pyx", line 3593, in pandas._libs.tslib.tz_localize_to_utc
pytz.exceptions.AmbiguousTimeError: Cannot infer dst time from Timestamp('2017-10-29 02:00:00'), try using the 'ambiguous' argument

# Fixed code
def _round(self, freq, rounder, ambiguous):
    # round the local times
    values = _ensure_datetimelike_to_i8(self)
    result = round_ns(values, rounder, freq)
    result = self._maybe_mask_results(result, fill_value=NaT)

    attribs = self._get_attributes_dict()
    if "freq" in attribs:
        attribs["freq"] = None
    if "tz" in attribs:
        attribs["tz"] = None
    return self._ensure_localized(self._shallow_copy(result, **attribs), ambiguous)
# Buggy code
def round(self, freq, *args, **kwargs):
    return self._round(freq, np.round)


# Traceback (pytz.exceptions.AmbiguousTimeError)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "(...)/venv/lib/python3.6/site-packages/pandas/core/accessor.py", line 115, in f
return self._delegate_method(name, *args, **kwargs)
File "(...)/venv/lib/python3.6/site-packages/pandas/core/indexes/accessors.py", line 131, in _delegate_method
result = method(*args, **kwargs)
File "(...)/venv/lib/python3.6/site-packages/pandas/core/indexes/datetimelike.py", line 118, in floor
return self._round(freq, np.floor)
File "(...)/venv/lib/python3.6/site-packages/pandas/core/indexes/datetimelike.py", line 110, in _round
self._shallow_copy(result, **attribs))
File "(...)/venv/lib/python3.6/site-packages/pandas/core/indexes/datetimelike.py", line 230, in _ensure_localized
result = result.tz_localize(self.tz)
File "(...)/venv/lib/python3.6/site-packages/pandas/util/_decorators.py", line 118, in wrapper
return func(*args, **kwargs)
File "(...)/venv/lib/python3.6/site-packages/pandas/core/indexes/datetimes.py", line 1858, in tz_localize
errors=errors)
File "pandas/_libs/tslib.pyx", line 3593, in pandas._libs.tslib.tz_localize_to_utc
pytz.exceptions.AmbiguousTimeError: Cannot infer dst time from Timestamp('2017-10-29 02:00:00'), try using the 'ambiguous' argument

# Fixed code
def round(self, freq, ambiguous="raise"):
    return self._round(freq, np.round, ambiguous)