gurudesh/pytracebugs huggingface dataset:
# Buggy code
def f(arg, window, min_periods=None, freq=None, time_rule=None, **kwargs):
    def call_cython(arg, window, minp, **kwds):
        minp = check_minp(minp, window)
        return func(arg, window, minp, **kwds)

    return _rolling_moment(
        arg, window, call_cython, min_periods, freq=freq, time_rule=time_rule, **kwargs
    )


# Traceback (Exception)
In [25]: df = pandas.DataFrame(np.random.randn(4,4), columns=list('AABC'))

In [26]: df
Out[26]:
A         A         B         C
0 -0.174905  0.332522  1.134984 -0.201270
1  1.730445  0.382556 -0.607761  1.221815
2  0.513049  0.196231 -1.746732 -0.252282
3 -0.297577 -1.000121 -0.090442 -2.129467

In [27]: df.ix[:,['A', 'B']]
Out[27]:
A         A         B
0 -0.174905  0.332522  1.134984
1  1.730445  0.382556 -0.607761
2  0.513049  0.196231 -1.746732
3 -0.297577 -1.000121 -0.090442

In [28]: df[['A', 'B']]
---------------------------------------------------------------------------
Exception                                 Traceback (most recent call last)
...
Exception: Reindexing only valid with uniquely valued Index objects

In [29]: df[['B', 'C']]
---------------------------------------------------------------------------
Exception                                 Traceback (most recent call last)
...
Exception: Reindexing only valid with uniquely valued Index objects

# Fixed code
def f(arg, min_periods=1, freq=None, time_rule=None, **kwargs):
    window = len(arg)

    def call_cython(arg, window, minp, **kwds):
        minp = check_minp(minp, window)
        return func(arg, window, minp, **kwds)

    return _rolling_moment(
        arg, window, call_cython, min_periods, freq=freq, time_rule=time_rule, **kwargs
    )
# Buggy code
def _maybe_add_color(kwargs, style, i):
    if not has_colors and (style is None or re.match("[a-z]+", style) is None):
        kwargs["color"] = colors[i % len(colors)]


# Traceback (Exception)
In [25]: df = pandas.DataFrame(np.random.randn(4,4), columns=list('AABC'))

In [26]: df
Out[26]:
A         A         B         C
0 -0.174905  0.332522  1.134984 -0.201270
1  1.730445  0.382556 -0.607761  1.221815
2  0.513049  0.196231 -1.746732 -0.252282
3 -0.297577 -1.000121 -0.090442 -2.129467

In [27]: df.ix[:,['A', 'B']]
Out[27]:
A         A         B
0 -0.174905  0.332522  1.134984
1  1.730445  0.382556 -0.607761
2  0.513049  0.196231 -1.746732
3 -0.297577 -1.000121 -0.090442

In [28]: df[['A', 'B']]
---------------------------------------------------------------------------
Exception                                 Traceback (most recent call last)
...
Exception: Reindexing only valid with uniquely valued Index objects

In [29]: df[['B', 'C']]
---------------------------------------------------------------------------
Exception                                 Traceback (most recent call last)
...
Exception: Reindexing only valid with uniquely valued Index objects

# Fixed code
def _maybe_add_color(kwargs, style, i):
    if (
        not has_colors
        and (style is None or re.match("[a-z]+", style) is None)
        and "color" not in kwargs
    ):
        kwargs["color"] = colors[i % len(colors)]
# Buggy code
def append(self, other):
    """
    Append a collection of Index options together

    Parameters
    ----------
    other : Index or list/tuple of indices

    Returns
    -------
    appended : Index
    """
    from pandas.core.index import _ensure_compat_concat

    name = self.name
    to_concat = [self]

    if isinstance(other, (list, tuple)):
        to_concat = to_concat + list(other)
    else:
        to_concat.append(other)

    for obj in to_concat:
        if isinstance(obj, Index) and obj.name != name:
            name = None
            break

    to_concat = _ensure_compat_concat(to_concat)
    to_concat = [x.values if isinstance(x, Index) else x for x in to_concat]

    return Index(com._concat_compat(to_concat), name=name)


# Traceback (Exception)
In [25]: df = pandas.DataFrame(np.random.randn(4,4), columns=list('AABC'))

In [26]: df
Out[26]:
A         A         B         C
0 -0.174905  0.332522  1.134984 -0.201270
1  1.730445  0.382556 -0.607761  1.221815
2  0.513049  0.196231 -1.746732 -0.252282
3 -0.297577 -1.000121 -0.090442 -2.129467

In [27]: df.ix[:,['A', 'B']]
Out[27]:
A         A         B
0 -0.174905  0.332522  1.134984
1  1.730445  0.382556 -0.607761
2  0.513049  0.196231 -1.746732
3 -0.297577 -1.000121 -0.090442

In [28]: df[['A', 'B']]
---------------------------------------------------------------------------
Exception                                 Traceback (most recent call last)
...
Exception: Reindexing only valid with uniquely valued Index objects

In [29]: df[['B', 'C']]
---------------------------------------------------------------------------
Exception                                 Traceback (most recent call last)
...
Exception: Reindexing only valid with uniquely valued Index objects

# Fixed code
def append(self, other):
    """
    Append a collection of Index options together

    Parameters
    ----------
    other : Index or list/tuple of indices

    Returns
    -------
    appended : Index
    """
    name = self.name
    to_concat = [self]

    if isinstance(other, (list, tuple)):
        to_concat = to_concat + list(other)
    else:
        to_concat.append(other)

    for obj in to_concat:
        if isinstance(obj, Index) and obj.name != name:
            name = None
            break

    to_concat = self._ensure_compat_concat(to_concat)
    to_concat = [x.values if isinstance(x, Index) else x for x in to_concat]

    return Index(com._concat_compat(to_concat), name=name)
# Buggy code
def equals(self, other):
    """
    Determines if two Index objects contain the same elements.
    """
    if self is other:
        return True

    if not hasattr(other, "inferred_type") or other.inferred_type != "datetime64":
        if self.offset is not None:
            return False
        try:
            other = DatetimeIndex(other)
        except:
            return False

    if self.tz is not None:
        if other.tz is None:
            return False
        same_zone = self.tz.zone == other.tz.zone
    else:
        if other.tz is not None:
            return False
        same_zone = True

    return same_zone and np.array_equal(self.asi8, other.asi8)


# Traceback (Exception)
In [25]: df = pandas.DataFrame(np.random.randn(4,4), columns=list('AABC'))

In [26]: df
Out[26]:
A         A         B         C
0 -0.174905  0.332522  1.134984 -0.201270
1  1.730445  0.382556 -0.607761  1.221815
2  0.513049  0.196231 -1.746732 -0.252282
3 -0.297577 -1.000121 -0.090442 -2.129467

In [27]: df.ix[:,['A', 'B']]
Out[27]:
A         A         B
0 -0.174905  0.332522  1.134984
1  1.730445  0.382556 -0.607761
2  0.513049  0.196231 -1.746732
3 -0.297577 -1.000121 -0.090442

In [28]: df[['A', 'B']]
---------------------------------------------------------------------------
Exception                                 Traceback (most recent call last)
...
Exception: Reindexing only valid with uniquely valued Index objects

In [29]: df[['B', 'C']]
---------------------------------------------------------------------------
Exception                                 Traceback (most recent call last)
...
Exception: Reindexing only valid with uniquely valued Index objects

# Fixed code
def equals(self, other):
    """
    Determines if two Index objects contain the same elements.
    """
    if self is other:
        return True

    if not hasattr(other, "inferred_type") or other.inferred_type != "datetime64":
        if self.offset is not None:
            return False
        try:
            other = DatetimeIndex(other)
        except:
            return False

    if self.tz is not None:
        if other.tz is None:
            return False
        same_zone = lib.get_timezone(self.tz) == lib.get_timezone(other.tz)
    else:
        if other.tz is not None:
            return False
        same_zone = True

    return same_zone and np.array_equal(self.asi8, other.asi8)
# Buggy code
def rollback(self, someDate):
    """Roll provided date backward to next offset only if not on offset"""
    if not self.onOffset(someDate):
        someDate = someDate - self.__class__(1, **self.kwds)
    return someDate


# Traceback (Exception)
In [25]: df = pandas.DataFrame(np.random.randn(4,4), columns=list('AABC'))

In [26]: df
Out[26]:
A         A         B         C
0 -0.174905  0.332522  1.134984 -0.201270
1  1.730445  0.382556 -0.607761  1.221815
2  0.513049  0.196231 -1.746732 -0.252282
3 -0.297577 -1.000121 -0.090442 -2.129467

In [27]: df.ix[:,['A', 'B']]
Out[27]:
A         A         B
0 -0.174905  0.332522  1.134984
1  1.730445  0.382556 -0.607761
2  0.513049  0.196231 -1.746732
3 -0.297577 -1.000121 -0.090442

In [28]: df[['A', 'B']]
---------------------------------------------------------------------------
Exception                                 Traceback (most recent call last)
...
Exception: Reindexing only valid with uniquely valued Index objects

In [29]: df[['B', 'C']]
---------------------------------------------------------------------------
Exception                                 Traceback (most recent call last)
...
Exception: Reindexing only valid with uniquely valued Index objects

# Fixed code
def rollback(self, dt):
    """Roll provided date backward to next offset only if not on offset"""
    if type(dt) == date:
        dt = datetime(dt.year, dt.month, dt.day)

    if not self.onOffset(dt):
        dt = dt - self.__class__(1, **self.kwds)
    return dt
# Buggy code
def rollforward(self, dt):
    """Roll provided date forward to next offset only if not on offset"""
    if not self.onOffset(dt):
        dt = dt + self.__class__(1, **self.kwds)
    return dt


# Traceback (Exception)
In [25]: df = pandas.DataFrame(np.random.randn(4,4), columns=list('AABC'))

In [26]: df
Out[26]:
A         A         B         C
0 -0.174905  0.332522  1.134984 -0.201270
1  1.730445  0.382556 -0.607761  1.221815
2  0.513049  0.196231 -1.746732 -0.252282
3 -0.297577 -1.000121 -0.090442 -2.129467

In [27]: df.ix[:,['A', 'B']]
Out[27]:
A         A         B
0 -0.174905  0.332522  1.134984
1  1.730445  0.382556 -0.607761
2  0.513049  0.196231 -1.746732
3 -0.297577 -1.000121 -0.090442

In [28]: df[['A', 'B']]
---------------------------------------------------------------------------
Exception                                 Traceback (most recent call last)
...
Exception: Reindexing only valid with uniquely valued Index objects

In [29]: df[['B', 'C']]
---------------------------------------------------------------------------
Exception                                 Traceback (most recent call last)
...
Exception: Reindexing only valid with uniquely valued Index objects

# Fixed code
def rollforward(self, dt):
    """Roll provided date forward to next offset only if not on offset"""
    if type(dt) == date:
        dt = datetime(dt.year, dt.month, dt.day)

    if not self.onOffset(dt):
        dt = dt + self.__class__(1, **self.kwds)
    return dt
# Buggy code
def onOffset(self, dt):
    if type(self) == DateOffset:
        return True

    # Default (slow) method for determining if some date is a member of the
    # date range generated by this offset. Subclasses may have this
    # re-implemented in a nicer way.
    a = dt
    b = (dt + self) - self
    return a == b


# Traceback (Exception)
In [25]: df = pandas.DataFrame(np.random.randn(4,4), columns=list('AABC'))

In [26]: df
Out[26]:
A         A         B         C
0 -0.174905  0.332522  1.134984 -0.201270
1  1.730445  0.382556 -0.607761  1.221815
2  0.513049  0.196231 -1.746732 -0.252282
3 -0.297577 -1.000121 -0.090442 -2.129467

In [27]: df.ix[:,['A', 'B']]
Out[27]:
A         A         B
0 -0.174905  0.332522  1.134984
1  1.730445  0.382556 -0.607761
2  0.513049  0.196231 -1.746732
3 -0.297577 -1.000121 -0.090442

In [28]: df[['A', 'B']]
---------------------------------------------------------------------------
Exception                                 Traceback (most recent call last)
...
Exception: Reindexing only valid with uniquely valued Index objects

In [29]: df[['B', 'C']]
---------------------------------------------------------------------------
Exception                                 Traceback (most recent call last)
...
Exception: Reindexing only valid with uniquely valued Index objects

# Fixed code
def onOffset(self, dt):
    # XXX, see #1395
    if type(self) == DateOffset or isinstance(self, Tick):
        return True

    # Default (slow) method for determining if some date is a member of the
    # date range generated by this offset. Subclasses may have this
    # re-implemented in a nicer way.
    a = dt
    b = (dt + self) - self
    return a == b
# Buggy code
def apply(self, other):
    if isinstance(other, (datetime, timedelta)):
        return other + self.delta
    elif isinstance(other, type(self)):
        return type(self)(self.n + other.n)


# Traceback (Exception)
In [25]: df = pandas.DataFrame(np.random.randn(4,4), columns=list('AABC'))

In [26]: df
Out[26]:
A         A         B         C
0 -0.174905  0.332522  1.134984 -0.201270
1  1.730445  0.382556 -0.607761  1.221815
2  0.513049  0.196231 -1.746732 -0.252282
3 -0.297577 -1.000121 -0.090442 -2.129467

In [27]: df.ix[:,['A', 'B']]
Out[27]:
A         A         B
0 -0.174905  0.332522  1.134984
1  1.730445  0.382556 -0.607761
2  0.513049  0.196231 -1.746732
3 -0.297577 -1.000121 -0.090442

In [28]: df[['A', 'B']]
---------------------------------------------------------------------------
Exception                                 Traceback (most recent call last)
...
Exception: Reindexing only valid with uniquely valued Index objects

In [29]: df[['B', 'C']]
---------------------------------------------------------------------------
Exception                                 Traceback (most recent call last)
...
Exception: Reindexing only valid with uniquely valued Index objects

# Fixed code
def apply(self, other):
    if type(other) == date:
        other = datetime(other.year, other.month, other.day)

    if isinstance(other, (datetime, timedelta)):
        return other + self.delta
    elif isinstance(other, type(self)):
        return type(self)(self.n + other.n)
    else:  # pragma: no cover
        raise TypeError("Unhandled type: %s" % type(other))
# Buggy code
def to_timestamp(self, freq=None, how="S"):
    """
    Return the Timestamp at the start/end of the period

    Parameters
    ----------
    freq : string or DateOffset, default frequency of PeriodIndex
        Target frequency
    how: str, default 'S' (start)
        'S', 'E'. Can be aliased as case insensitive
        'Start', 'Finish', 'Begin', 'End'

    Returns
    -------
    Timestamp
    """
    if freq is None:
        base, mult = _gfc(self.freq)
        new_val = self
    else:
        base, mult = _gfc(freq)
        new_val = self.asfreq(freq, how)

    dt64 = plib.period_ordinal_to_dt64(new_val.ordinal, base)
    ts_freq = _period_rule_to_timestamp_rule(new_val.freq, how=how)
    return Timestamp(dt64, offset=to_offset(ts_freq))


# Traceback (Exception)
In [25]: df = pandas.DataFrame(np.random.randn(4,4), columns=list('AABC'))

In [26]: df
Out[26]:
A         A         B         C
0 -0.174905  0.332522  1.134984 -0.201270
1  1.730445  0.382556 -0.607761  1.221815
2  0.513049  0.196231 -1.746732 -0.252282
3 -0.297577 -1.000121 -0.090442 -2.129467

In [27]: df.ix[:,['A', 'B']]
Out[27]:
A         A         B
0 -0.174905  0.332522  1.134984
1  1.730445  0.382556 -0.607761
2  0.513049  0.196231 -1.746732
3 -0.297577 -1.000121 -0.090442

In [28]: df[['A', 'B']]
---------------------------------------------------------------------------
Exception                                 Traceback (most recent call last)
...
Exception: Reindexing only valid with uniquely valued Index objects

In [29]: df[['B', 'C']]
---------------------------------------------------------------------------
Exception                                 Traceback (most recent call last)
...
Exception: Reindexing only valid with uniquely valued Index objects

# Fixed code
def to_timestamp(self, freq=None, how="S"):
    """
    Return the Timestamp at the start/end of the period

    Parameters
    ----------
    freq : string or DateOffset, default frequency of PeriodIndex
        Target frequency
    how: str, default 'S' (start)
        'S', 'E'. Can be aliased as case insensitive
        'Start', 'Finish', 'Begin', 'End'

    Returns
    -------
    Timestamp
    """
    if freq is None:
        base, mult = _gfc(self.freq)
        how = _validate_end_alias(how)
        if how == "S":
            base = _freq_mod.get_to_timestamp_base(base)
            freq = _freq_mod._get_freq_str(base)
            new_val = self.asfreq(freq, how)
        else:
            new_val = self
    else:
        base, mult = _gfc(freq)
        new_val = self.asfreq(freq, how)

    dt64 = plib.period_ordinal_to_dt64(new_val.ordinal, base)
    return Timestamp(dt64)
# Buggy code
def format(self, name=False):
    """
    Render a string representation of the Index
    """
    header = []

    if name:
        header.append(str(self.name) if self.name is not None else "")

    return header + ["%s" % Period(x, freq=self.freq) for x in self]


# Traceback (TypeError)
In [1]: import numpy as np

In [2]: import pandas as pd

In [3]: index = pd.PeriodIndex(['2011-1', '2011-2', '2011-3'], freq='M')

In [4]: frame = pd.DataFrame(np.random.randn(3,4),index=index)

In [5]: frame.to_string()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-b6219037419a> in <module>()
----> 1 frame.to_string()

/mnt/home/jreback/pandas/pandas/core/frame.pyc in to_string(self, buf, columns, col_space, colSpace, header, index, na_rep, formatters, float_format, sparsify, nanRep, index_names, justify, force_unicode, line_width)
1501                                            header=header, index=index,
1502                                            line_width=line_width)
-> 1503         formatter.to_string()
1504
1505         if buf is None:

/mnt/home/jreback/pandas/pandas/core/format.pyc in to_string(self, force_unicode)
295             text = info_line
296         else:
--> 297             strcols = self._to_str_columns()
298             if self.line_width is None:
299                 text = adjoin(1, *strcols)

/mnt/home/jreback/pandas/pandas/core/format.pyc in _to_str_columns(self)
240
241         # may include levels names also
--> 242         str_index = self._get_formatted_index()
243         str_columns = self._get_formatted_column_labels()
244

/mnt/home/jreback/pandas/pandas/core/format.pyc in _get_formatted_index(self)
444                                      formatter=fmt)
445         else:
--> 446             fmt_index = [index.format(name=show_index_names, formatter=fmt)]
447
448         adjoined = adjoin(1, *fmt_index).split('\n')

TypeError: format() got an unexpected keyword argument 'formatter'

# Fixed code
def format(self, name=False, formatter=None):
    """
    Render a string representation of the Index
    """
    header = []

    if name:
        header.append(str(self.name) if self.name is not None else "")

    return header + ["%s" % Period(x, freq=self.freq) for x in self]
# Buggy code
def _interleave(self, items):
    """
    Return ndarray from blocks with specified item order
    Items must be contained in the blocks
    """
    dtype = _interleaved_dtype(self.blocks)
    items = _ensure_index(items)

    result = np.empty(self.shape, dtype=dtype)
    itemmask = np.zeros(len(items), dtype=bool)

    # By construction, all of the item should be covered by one of the
    # blocks
    for block in self.blocks:
        indexer = items.get_indexer(block.items)
        assert (indexer != -1).all()
        result[indexer] = block.get_values(dtype)
        itemmask[indexer] = 1
    assert itemmask.all()
    return result


# Traceback (Exception)
import pandas as pd
def runNow():
#identify sheet
source = 'C:\Users\jlalonde\Desktop\startup_geno\startupgenome_w_id_xl_20121109.xlsx'
xls_file = pd.ExcelFile(source)
sd = xls_file.parse('Sheet1')
source_u = sd.drop_duplicates(cols = 'id_company', take_last=False)
source_r = source_u[['id_company','id_good','description', 'website','keyword', 'company_name','founded_month', 'founded_year', 'description']]
source_i = source_r.reindex() #hail mary
tup_r = [tuple(x) for x in source_i.values]

Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
sg_sql_2.runNow()
File "sg_sql_2.py", line 31, in runNow
tup_r = [tuple(x) for x in source_r.values]
File "C:\Python27\lib\site-packages\pandas\core\frame.py", line 1443, in as_matrix
return self._data.as_matrix(columns).T
File "C:\Python27\lib\site-packages\pandas\core\internals.py", line 723, in as_matrix
mat = self._interleave(self.items)
File "C:\Python27\lib\site-packages\pandas\core\internals.py", line 743, in _interleave
indexer = items.get_indexer(block.items)
File "C:\Python27\lib\site-packages\pandas\core\index.py", line 748, in get_indexer
raise Exception('Reindexing only valid with uniquely valued Index '
Exception: Reindexing only valid with uniquely valued Index objects

# Fixed code
def _interleave(self, items):
    """
    Return ndarray from blocks with specified item order
    Items must be contained in the blocks
    """
    dtype = _interleaved_dtype(self.blocks)
    items = _ensure_index(items)

    result = np.empty(self.shape, dtype=dtype)
    itemmask = np.zeros(len(items), dtype=bool)

    # By construction, all of the item should be covered by one of the
    # blocks
    if items.is_unique:
        for block in self.blocks:
            indexer = items.get_indexer(block.items)
            assert (indexer != -1).all()
            result[indexer] = block.get_values(dtype)
            itemmask[indexer] = 1
    else:
        for block in self.blocks:
            mask = items.isin(block.items)
            indexer = mask.nonzero()[0]
            assert len(indexer) == len(block.items)
            result[indexer] = block.get_values(dtype)
            itemmask[indexer] = 1

    assert itemmask.all()

    return result
# Buggy code
def _isnull_ndarraylike(obj):
    from pandas import Series

    values = np.asarray(obj)

    if values.dtype.kind in ("O", "S", "U"):
        # Working around NumPy ticket 1542
        shape = values.shape

        if values.dtype.kind in ("S", "U"):
            result = np.zeros(values.shape, dtype=bool)
        else:
            result = np.empty(shape, dtype=bool)
            vec = lib.isnullobj(values.ravel())
            result[:] = vec.reshape(shape)

        if isinstance(obj, Series):
            result = Series(result, index=obj.index, copy=False)
    elif values.dtype == np.dtype("M8[ns]"):
        # this is the NaT pattern
        result = values.view("i8") == lib.iNaT
    else:
        result = -np.isfinite(obj)
    return result


# Traceback (TypeError)
import pandas as pd
import numpy as np
print pd.Series(np.array([1100, 20], dtype='timedelta64[s]'))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27_64\lib\site-packages\pandas\core\series.py", line 911, in __str__
return repr(self)
File "C:\Python27_64\lib\site-packages\pandas\core\series.py", line 847, in __repr__
name=True)
File "C:\Python27_64\lib\site-packages\pandas\core\series.py", line 908, in _get_repr
return formatter.to_string()
File "C:\Python27_64\lib\site-packages\pandas\core\format.py", line 126, in to_string
fmt_values = self._get_formatted_values()
File "C:\Python27_64\lib\site-packages\pandas\core\format.py", line 117, in _get_formatted_values
na_rep=self.na_rep)
File "C:\Python27_64\lib\site-packages\pandas\core\format.py", line 691, in format_array
return fmt_obj.get_result()
File "C:\Python27_64\lib\site-packages\pandas\core\format.py", line 814, in get_result
fmt_values = [formatter(x) for x in self.values]
File "C:\Python27_64\lib\site-packages\pandas\core\format.py", line 812, in <lambda>
formatter = lambda x: '% d' % x
TypeError: %d format: a number is required, not numpy.timedelta64

# Fixed code
def _isnull_ndarraylike(obj):
    from pandas import Series

    values = np.asarray(obj)

    if values.dtype.kind in ("O", "S", "U"):
        # Working around NumPy ticket 1542
        shape = values.shape

        if values.dtype.kind in ("S", "U"):
            result = np.zeros(values.shape, dtype=bool)
        else:
            result = np.empty(shape, dtype=bool)
            vec = lib.isnullobj(values.ravel())
            result[:] = vec.reshape(shape)

        if isinstance(obj, Series):
            result = Series(result, index=obj.index, copy=False)
    elif values.dtype == np.dtype("M8[ns]"):
        # this is the NaT pattern
        result = values.view("i8") == lib.iNaT
    elif issubclass(values.dtype.type, np.timedelta64):
        result = -np.isfinite(values.view("i8"))
    else:
        result = -np.isfinite(obj)
    return result
# Buggy code
def is_integer_dtype(arr_or_dtype):
    if isinstance(arr_or_dtype, np.dtype):
        tipo = arr_or_dtype.type
    else:
        tipo = arr_or_dtype.dtype.type
    return issubclass(tipo, np.integer) and not issubclass(tipo, np.datetime64)


# Traceback (TypeError)
import pandas as pd
import numpy as np
print pd.Series(np.array([1100, 20], dtype='timedelta64[s]'))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27_64\lib\site-packages\pandas\core\series.py", line 911, in __str__
return repr(self)
File "C:\Python27_64\lib\site-packages\pandas\core\series.py", line 847, in __repr__
name=True)
File "C:\Python27_64\lib\site-packages\pandas\core\series.py", line 908, in _get_repr
return formatter.to_string()
File "C:\Python27_64\lib\site-packages\pandas\core\format.py", line 126, in to_string
fmt_values = self._get_formatted_values()
File "C:\Python27_64\lib\site-packages\pandas\core\format.py", line 117, in _get_formatted_values
na_rep=self.na_rep)
File "C:\Python27_64\lib\site-packages\pandas\core\format.py", line 691, in format_array
return fmt_obj.get_result()
File "C:\Python27_64\lib\site-packages\pandas\core\format.py", line 814, in get_result
fmt_values = [formatter(x) for x in self.values]
File "C:\Python27_64\lib\site-packages\pandas\core\format.py", line 812, in <lambda>
formatter = lambda x: '% d' % x
TypeError: %d format: a number is required, not numpy.timedelta64

# Fixed code
def is_integer_dtype(arr_or_dtype):
    if isinstance(arr_or_dtype, np.dtype):
        tipo = arr_or_dtype.type
    else:
        tipo = arr_or_dtype.dtype.type
    return issubclass(tipo, np.integer) and not (
        issubclass(tipo, np.datetime64) or issubclass(tipo, np.timedelta64)
    )
# Buggy code
def _nanmin(values, axis=None, skipna=True):
    mask = isnull(values)
    if skipna and not issubclass(values.dtype.type, (np.integer, np.datetime64)):
        values = values.copy()
        np.putmask(values, mask, np.inf)
    # numpy 1.6.1 workaround in Python 3.x
    if values.dtype == np.object_ and sys.version_info[0] >= 3:  # pragma: no cover
        import __builtin__

        if values.ndim > 1:
            apply_ax = axis if axis is not None else 0
            result = np.apply_along_axis(__builtin__.min, apply_ax, values)
        else:
            result = __builtin__.min(values)
    else:
        result = values.min(axis)

    return _maybe_null_out(result, axis, mask)


# Traceback (IndexError)
In [1]: from pandas import *

In [2]: a = DataFrame(columns=['column1'], data=[1])

In [3]: b = DataFrame(columns=['column1'])

In [4]: a.merge(b, on=['column1'], how='left')


IndexError                                Traceback (most recent call last)
IndexError: index out of range for array

# Fixed code
def _nanmin(values, axis=None, skipna=True):
    mask = isnull(values)
    if skipna and not issubclass(values.dtype.type, (np.integer, np.datetime64)):
        values = values.copy()
        np.putmask(values, mask, np.inf)
    # numpy 1.6.1 workaround in Python 3.x
    if values.dtype == np.object_ and sys.version_info[0] >= 3:  # pragma: no cover
        import __builtin__

        if values.ndim > 1:
            apply_ax = axis if axis is not None else 0
            result = np.apply_along_axis(__builtin__.min, apply_ax, values)
        else:
            result = __builtin__.min(values)
    else:
        if (axis is not None and values.shape[axis] == 0) or values.size == 0:
            result = values.sum(axis)
            result.fill(np.nan)
        else:
            result = values.min(axis)

    return _maybe_null_out(result, axis, mask)
# Buggy code
def _nanmax(values, axis=None, skipna=True):
    mask = isnull(values)
    if skipna and not issubclass(values.dtype.type, (np.integer, np.datetime64)):
        values = values.copy()
        np.putmask(values, mask, -np.inf)
    # numpy 1.6.1 workaround in Python 3.x
    if values.dtype == np.object_ and sys.version_info[0] >= 3:  # pragma: no cover
        import __builtin__

        if values.ndim > 1:
            apply_ax = axis if axis is not None else 0
            result = np.apply_along_axis(__builtin__.max, apply_ax, values)
        else:
            result = __builtin__.max(values)
    else:
        result = values.max(axis)
    return _maybe_null_out(result, axis, mask)


# Traceback (IndexError)
In [1]: from pandas import *

In [2]: a = DataFrame(columns=['column1'], data=[1])

In [3]: b = DataFrame(columns=['column1'])

In [4]: a.merge(b, on=['column1'], how='left')


IndexError                                Traceback (most recent call last)
IndexError: index out of range for array

# Fixed code
def _nanmax(values, axis=None, skipna=True):
    mask = isnull(values)
    if skipna and not issubclass(values.dtype.type, (np.integer, np.datetime64)):
        values = values.copy()
        np.putmask(values, mask, -np.inf)
    # numpy 1.6.1 workaround in Python 3.x
    if values.dtype == np.object_ and sys.version_info[0] >= 3:  # pragma: no cover
        import __builtin__

        if values.ndim > 1:
            apply_ax = axis if axis is not None else 0
            result = np.apply_along_axis(__builtin__.max, apply_ax, values)
        else:
            result = __builtin__.max(values)
    else:
        if (axis is not None and values.shape[axis] == 0) or values.size == 0:
            result = values.sum(axis)
            result.fill(np.nan)
        else:
            result = values.max(axis)

    return _maybe_null_out(result, axis, mask)
# Buggy code
def get_corr_func(method):
    if method in ["kendall", "spearman"]:
        from scipy.stats import kendalltau, spearmanr

    def _pearson(a, b):
        return np.corrcoef(a, b)[0, 1]

    def _kendall(a, b):
        return kendalltau(a, b)[0]

    def _spearman(a, b):
        return spearmanr(a, b)[0]

    _cor_methods = {"pearson": _pearson, "kendall": _kendall, "spearman": _spearman}
    return _cor_methods[method]


# Traceback (IndexError)
In [1]: from pandas import *

In [2]: a = DataFrame(columns=['column1'], data=[1])

In [3]: b = DataFrame(columns=['column1'])

In [4]: a.merge(b, on=['column1'], how='left')


IndexError                                Traceback (most recent call last)
IndexError: index out of range for array

# Fixed code
def get_corr_func(method):
    if method in ["kendall", "spearman"]:
        from scipy.stats import kendalltau, spearmanr

    def _pearson(a, b):
        return np.corrcoef(a, b)[0, 1]

    def _kendall(a, b):
        rs = kendalltau(a, b)
        if isinstance(rs, tuple):
            return rs[0]
        return rs

    def _spearman(a, b):
        return spearmanr(a, b)[0]

    _cor_methods = {"pearson": _pearson, "kendall": _kendall, "spearman": _spearman}
    return _cor_methods[method]
# Buggy code
def _kendall(a, b):
    return kendalltau(a, b)[0]


# Traceback (IndexError)
In [1]: from pandas import *

In [2]: a = DataFrame(columns=['column1'], data=[1])

In [3]: b = DataFrame(columns=['column1'])

In [4]: a.merge(b, on=['column1'], how='left')


IndexError                                Traceback (most recent call last)
IndexError: index out of range for array

# Fixed code
def _kendall(a, b):
    rs = kendalltau(a, b)
    if isinstance(rs, tuple):
        return rs[0]
    return rs
# Buggy code
def block2d_to_block3d(
    values, items, shape, major_labels, minor_labels, ref_items=None
):
    """
    Developer method for pivoting DataFrame -> Panel. Used in HDFStore and
    DataFrame.to_panel
    """
    from pandas.core.internals import make_block

    panel_shape = (len(items),) + shape

    # TODO: lexsort depth needs to be 2!!

    # Create observation selection vector using major and minor
    # labels, for converting to panel format.
    selector = minor_labels + shape[1] * major_labels
    mask = np.zeros(np.prod(shape), dtype=bool)
    mask.put(selector, True)

    pvalues = np.empty(panel_shape, dtype=values.dtype)
    if not issubclass(pvalues.dtype.type, np.integer):
        pvalues.fill(np.nan)

    values = values
    for i in xrange(len(items)):
        pvalues[i].flat[mask] = values[:, i]

    if ref_items is None:
        ref_items = items

    return make_block(pvalues, items, ref_items)


# Traceback (IndexError)
In [1]: from pandas import *

In [2]: a = DataFrame(columns=['column1'], data=[1])

In [3]: b = DataFrame(columns=['column1'])

In [4]: a.merge(b, on=['column1'], how='left')


IndexError                                Traceback (most recent call last)
IndexError: index out of range for array

# Fixed code
def block2d_to_block3d(
    values, items, shape, major_labels, minor_labels, ref_items=None
):
    """
    Developer method for pivoting DataFrame -> Panel. Used in HDFStore and
    DataFrame.to_panel
    """
    from pandas.core.internals import make_block

    panel_shape = (len(items),) + shape

    # TODO: lexsort depth needs to be 2!!

    # Create observation selection vector using major and minor
    # labels, for converting to panel format.
    selector = minor_labels + shape[1] * major_labels
    mask = np.zeros(np.prod(shape), dtype=bool)
    mask.put(selector, True)

    pvalues = np.empty(panel_shape, dtype=values.dtype)
    if not issubclass(pvalues.dtype.type, (np.integer, np.bool_)):
        pvalues.fill(np.nan)
    elif not mask.all():
        pvalues = com._maybe_upcast(pvalues)
        pvalues.fill(np.nan)

    values = values
    for i in xrange(len(items)):
        pvalues[i].flat[mask] = values[:, i]

    if ref_items is None:
        ref_items = items

    return make_block(pvalues, items, ref_items)
# Buggy code
def _insert_column(self, key):
    self.columns = Index(np.concatenate((self.columns, [key])))


# Traceback (IndexError)
In [1]: from pandas import *

In [2]: a = DataFrame(columns=['column1'], data=[1])

In [3]: b = DataFrame(columns=['column1'])

In [4]: a.merge(b, on=['column1'], how='left')


IndexError                                Traceback (most recent call last)
IndexError: index out of range for array

# Fixed code
def _insert_column(self, key):
    self.columns = self.columns.insert(len(self.columns), key)
# Buggy code
def __getitem__(self, item):
    """
    Retrieve column or slice from DataFrame
    """
    try:
        # unsure about how kludgy this is
        s = self._series[item]
        s.name = item
        return s
    except (TypeError, KeyError):
        if isinstance(item, slice):
            date_rng = self.index[item]
            return self.reindex(date_rng)

        elif isinstance(item, np.ndarray):
            if len(item) != len(self.index):
                raise Exception(
                    "Item wrong length %d instead of %d!" % (len(item), len(self.index))
                )
            newIndex = self.index[item]
            return self.reindex(newIndex)
        else:  # pragma: no cover
            raise


# Traceback (IndexError)
In [1]: from pandas import *

In [2]: a = DataFrame(columns=['column1'], data=[1])

In [3]: b = DataFrame(columns=['column1'])

In [4]: a.merge(b, on=['column1'], how='left')


IndexError                                Traceback (most recent call last)
IndexError: index out of range for array

# Fixed code
def __getitem__(self, key):
    """
    Retrieve column or slice from DataFrame
    """
    try:
        # unsure about how kludgy this is
        s = self._series[key]
        s.name = key
        return s
    except (TypeError, KeyError):
        if isinstance(key, slice):
            date_rng = self.index[key]
            return self.reindex(date_rng)

        elif isinstance(key, (np.ndarray, list)):
            if isinstance(key, list):
                key = lib.list_to_object_array(key)

            # also raises Exception if object array with NA values
            if com._is_bool_indexer(key):
                key = np.asarray(key, dtype=bool)
            return self._getitem_array(key)
        else:  # pragma: no cover
            raise
# Buggy code
def ewma(arg, com=None, span=None, min_periods=0, freq=None, time_rule=None):
    com = _get_center_of_mass(com, span)
    arg = _conv_timerule(arg, freq, time_rule)

    def _ewma(v):
        result = _tseries.ewma(v, com)
        first_index = _first_valid_index(v)
        result[first_index : first_index + min_periods] = NaN
        return result

    return_hook, values = _process_data_structure(arg)
    output = np.apply_along_axis(_ewma, 0, values)
    return return_hook(output)


# Traceback (IndexError)
In [1]: from pandas import *

In [2]: a = DataFrame(columns=['column1'], data=[1])

In [3]: b = DataFrame(columns=['column1'])

In [4]: a.merge(b, on=['column1'], how='left')


IndexError                                Traceback (most recent call last)
IndexError: index out of range for array

# Fixed code
def ewma(
    arg, com=None, span=None, min_periods=0, freq=None, time_rule=None, adjust=True
):
    com = _get_center_of_mass(com, span)
    arg = _conv_timerule(arg, freq, time_rule)

    def _ewma(v):
        result = lib.ewma(v, com, int(adjust))
        first_index = _first_valid_index(v)
        result[first_index : first_index + min_periods] = NaN
        return result

    return_hook, values = _process_data_structure(arg)
    output = np.apply_along_axis(_ewma, 0, values)
    return return_hook(output)
# Buggy code
def _ewma(v):
    result = _tseries.ewma(v, com)
    first_index = _first_valid_index(v)
    result[first_index : first_index + min_periods] = NaN
    return result


# Traceback (IndexError)
In [1]: from pandas import *

In [2]: a = DataFrame(columns=['column1'], data=[1])

In [3]: b = DataFrame(columns=['column1'])

In [4]: a.merge(b, on=['column1'], how='left')


IndexError                                Traceback (most recent call last)
IndexError: index out of range for array

# Fixed code
def _ewma(v):
    result = lib.ewma(v, com, int(adjust))
    first_index = _first_valid_index(v)
    result[first_index : first_index + min_periods] = NaN
    return result
# Buggy code
def rolling_quantile(
    arg, window, quantile, min_periods=None, freq=None, time_rule=None
):
    """Moving quantile

    Parameters
    ----------
    arg : Series, DataFrame
    window : Number of observations used for calculating statistic
    quantile : 0 <= quantile <= 1
    min_periods : int
        Minimum number of observations in window required to have a value
    freq : None or string alias / date offset object, default=None
        Frequency to conform to before computing statistic

    Returns
    -------
    y : type of input argument
    """

    def call_cython(arg, window, minp):
        minp = _use_window(minp, window)
        return _tseries.roll_quantile(arg, window, minp, quantile)

    return _rolling_moment(
        arg, window, call_cython, min_periods, freq=freq, time_rule=time_rule
    )


# Traceback (IndexError)
In [1]: from pandas import *

In [2]: a = DataFrame(columns=['column1'], data=[1])

In [3]: b = DataFrame(columns=['column1'])

In [4]: a.merge(b, on=['column1'], how='left')


IndexError                                Traceback (most recent call last)
IndexError: index out of range for array

# Fixed code
def rolling_quantile(
    arg, window, quantile, min_periods=None, freq=None, time_rule=None
):
    """Moving quantile

    Parameters
    ----------
    arg : Series, DataFrame
    window : Number of observations used for calculating statistic
    quantile : 0 <= quantile <= 1
    min_periods : int
        Minimum number of observations in window required to have a value
    freq : None or string alias / date offset object, default=None
        Frequency to conform to before computing statistic

    Returns
    -------
    y : type of input argument
    """

    def call_cython(arg, window, minp):
        minp = _use_window(minp, window)
        return lib.roll_quantile(arg, window, minp, quantile)

    return _rolling_moment(
        arg, window, call_cython, min_periods, freq=freq, time_rule=time_rule
    )
# Buggy code
def call_cython(arg, window, minp):
    minp = _use_window(minp, window)
    return _tseries.roll_quantile(arg, window, minp, quantile)


# Traceback (IndexError)
In [1]: from pandas import *

In [2]: a = DataFrame(columns=['column1'], data=[1])

In [3]: b = DataFrame(columns=['column1'])

In [4]: a.merge(b, on=['column1'], how='left')


IndexError                                Traceback (most recent call last)
IndexError: index out of range for array

# Fixed code
def call_cython(arg, window, minp):
    minp = _use_window(minp, window)
    return lib.roll_quantile(arg, window, minp, quantile)
# Buggy code
def rolling_apply(arg, window, func, min_periods=None, freq=None, time_rule=None):
    """Generic moving function application

    Parameters
    ----------
    arg : Series, DataFrame
    window : Number of observations used for calculating statistic
    func : function
        Must produce a single value from an ndarray input
    min_periods : int
        Minimum number of observations in window required to have a value
    freq : None or string alias / date offset object, default=None
        Frequency to conform to before computing statistic

    Returns
    -------
    y : type of input argument
    """

    def call_cython(arg, window, minp):
        minp = _use_window(minp, window)
        return _tseries.roll_generic(arg, window, minp, func)

    return _rolling_moment(
        arg, window, call_cython, min_periods, freq=freq, time_rule=time_rule
    )


# Traceback (IndexError)
In [1]: from pandas import *

In [2]: a = DataFrame(columns=['column1'], data=[1])

In [3]: b = DataFrame(columns=['column1'])

In [4]: a.merge(b, on=['column1'], how='left')


IndexError                                Traceback (most recent call last)
IndexError: index out of range for array

# Fixed code
def rolling_apply(arg, window, func, min_periods=None, freq=None, time_rule=None):
    """Generic moving function application

    Parameters
    ----------
    arg : Series, DataFrame
    window : Number of observations used for calculating statistic
    func : function
        Must produce a single value from an ndarray input
    min_periods : int
        Minimum number of observations in window required to have a value
    freq : None or string alias / date offset object, default=None
        Frequency to conform to before computing statistic

    Returns
    -------
    y : type of input argument
    """

    def call_cython(arg, window, minp):
        minp = _use_window(minp, window)
        return lib.roll_generic(arg, window, minp, func)

    return _rolling_moment(
        arg, window, call_cython, min_periods, freq=freq, time_rule=time_rule
    )
# Buggy code
def call_cython(arg, window, minp):
    minp = _use_window(minp, window)
    return _tseries.roll_generic(arg, window, minp, func)


# Traceback (IndexError)
In [1]: from pandas import *

In [2]: a = DataFrame(columns=['column1'], data=[1])

In [3]: b = DataFrame(columns=['column1'])

In [4]: a.merge(b, on=['column1'], how='left')


IndexError                                Traceback (most recent call last)
IndexError: index out of range for array

# Fixed code
def call_cython(arg, window, minp):
    minp = _use_window(minp, window)
    return lib.roll_generic(arg, window, minp, func)
# Buggy code
def __init__(
    self,
    data,
    kind=None,
    by=None,
    subplots=False,
    sharex=True,
    sharey=False,
    use_index=True,
    figsize=None,
    grid=None,
    legend=True,
    rot=None,
    ax=None,
    fig=None,
    title=None,
    xlim=None,
    ylim=None,
    xticks=None,
    yticks=None,
    sort_columns=False,
    fontsize=None,
    secondary_y=False,
    **kwds,
):
    self.data = data
    self.by = by

    self.kind = kind

    self.sort_columns = sort_columns

    self.subplots = subplots
    self.sharex = sharex
    self.sharey = sharey
    self.figsize = figsize

    self.xticks = xticks
    self.yticks = yticks
    self.xlim = xlim
    self.ylim = ylim
    self.title = title
    self.use_index = use_index

    self.fontsize = fontsize
    self.rot = rot

    if grid is None:
        grid = False if secondary_y else True

    self.grid = grid
    self.legend = legend

    for attr in self._pop_attributes:
        value = kwds.pop(attr, self._attr_defaults.get(attr, None))
        setattr(self, attr, value)

    self.ax = ax
    self.fig = fig
    self.axes = None

    self.secondary_y = secondary_y

    self.kwds = kwds


# Traceback (IndexError)
In [1]: from pandas import *

In [2]: a = DataFrame(columns=['column1'], data=[1])

In [3]: b = DataFrame(columns=['column1'])

In [4]: a.merge(b, on=['column1'], how='left')


IndexError                                Traceback (most recent call last)
IndexError: index out of range for array

# Fixed code
def __init__(
    self,
    data,
    kind=None,
    by=None,
    subplots=False,
    sharex=True,
    sharey=False,
    use_index=True,
    figsize=None,
    grid=None,
    legend=True,
    rot=None,
    ax=None,
    fig=None,
    title=None,
    xlim=None,
    ylim=None,
    xticks=None,
    yticks=None,
    sort_columns=False,
    fontsize=None,
    secondary_y=False,
    **kwds,
):
    self.data = data
    self.by = by

    self.kind = kind

    self.sort_columns = sort_columns

    self.subplots = subplots
    self.sharex = sharex
    self.sharey = sharey
    self.figsize = figsize

    self.xticks = xticks
    self.yticks = yticks
    self.xlim = xlim
    self.ylim = ylim
    self.title = title
    self.use_index = use_index

    self.fontsize = fontsize
    self.rot = rot

    if grid is None:
        grid = False if secondary_y else True

    self.grid = grid
    self.legend = legend

    for attr in self._pop_attributes:
        value = kwds.pop(attr, self._attr_defaults.get(attr, None))
        setattr(self, attr, value)

    self.ax = ax
    self.fig = fig
    self.axes = None

    if not isinstance(secondary_y, (bool, tuple, list, np.ndarray)):
        secondary_y = [secondary_y]
    self.secondary_y = secondary_y

    self.kwds = kwds
# Buggy code
def _iter_data(self):
    from pandas.core.frame import DataFrame

    if isinstance(self.data, (Series, np.ndarray)):
        yield com._stringify(self.label), np.asarray(self.data)
    elif isinstance(self.data, DataFrame):
        df = self.data

        if self.sort_columns:
            columns = com._try_sort(df.columns)
        else:
            columns = df.columns

        for col in columns:
            empty = df[col].count() == 0
            # is this right?
            values = df[col].values if not empty else np.zeros(len(df))

            col = com._stringify(col)
            yield col, values


# Traceback (IndexError)
In [1]: from pandas import *

In [2]: a = DataFrame(columns=['column1'], data=[1])

In [3]: b = DataFrame(columns=['column1'])

In [4]: a.merge(b, on=['column1'], how='left')


IndexError                                Traceback (most recent call last)
IndexError: index out of range for array

# Fixed code
def _iter_data(self):
    from pandas.core.frame import DataFrame

    if isinstance(self.data, (Series, np.ndarray)):
        yield self.label, np.asarray(self.data)
    elif isinstance(self.data, DataFrame):
        df = self.data

        if self.sort_columns:
            columns = com._try_sort(df.columns)
        else:
            columns = df.columns

        for col in columns:
            empty = df[col].count() == 0
            # is this right?
            values = df[col].values if not empty else np.zeros(len(df))

            yield col, values