gurudesh/pytracebugs huggingface dataset:
# Buggy code
def _adorn_subplots(self):
    if self.subplots:
        to_adorn = self.axes
    else:
        to_adorn = [self.ax]

    # todo: sharex, sharey handling?

    for ax in to_adorn:
        if self.yticks is not None:
            ax.set_yticks(self.yticks)

        if self.xticks is not None:
            ax.set_xticks(self.xticks)

        if self.ylim is not None:
            ax.set_ylim(self.ylim)

        if self.xlim is not None:
            ax.set_xlim(self.xlim)

        ax.grid(self.grid)

    if self.legend and not self.subplots:
        self.ax.legend(loc="best")

    if self.title:
        if self.subplots:
            self.fig.suptitle(self.title)
        else:
            self.ax.set_title(self.title)

    if self._need_to_set_index:
        xticklabels = [_stringify(key) for key in self.data.index]
        for ax_ in self.axes:
            # ax_.set_xticks(self.xticks)
            ax_.set_xticklabels(xticklabels, rotation=self.rot)


# Traceback (ValueError)
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m')
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>()
----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m')

/home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize)
1209     """
1210     return DatetimeIndex(start=start, end=end, periods=periods,
-> 1211                          freq=freq, tz=tz, normalize=normalize)
1212
1213

/home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds)
202
203         if data is None and offset is None:
--> 204             raise ValueError("Must provide freq argument if no data is "
205                              "supplied")
206

ValueError: Must provide freq argument if no data is supplied

# Fixed code
def _adorn_subplots(self):
    if self.subplots:
        to_adorn = self.axes
    else:
        to_adorn = [self.ax]

    # todo: sharex, sharey handling?

    for ax in to_adorn:
        if self.yticks is not None:
            ax.set_yticks(self.yticks)

        if self.xticks is not None:
            ax.set_xticks(self.xticks)

        if self.ylim is not None:
            ax.set_ylim(self.ylim)

        if self.xlim is not None:
            ax.set_xlim(self.xlim)

        ax.grid(self.grid)

    if self.legend and not self.subplots:
        self.ax.legend(loc="best", title=self.legend_title)

    if self.title:
        if self.subplots:
            self.fig.suptitle(self.title)
        else:
            self.ax.set_title(self.title)

    if self._need_to_set_index:
        xticklabels = [_stringify(key) for key in self.data.index]
        for ax_ in self.axes:
            # ax_.set_xticks(self.xticks)
            ax_.set_xticklabels(xticklabels, rotation=self.rot)
# Buggy code
def _get_xticks(self):
    index = self.data.index
    is_datetype = index.inferred_type in ("datetime", "date")

    if self.use_index:
        if index.is_numeric() or is_datetype:
            """
                Matplotlib supports numeric values or datetime objects as
                xaxis values. Taking LBYL approach here, by the time
                matplotlib raises exception when using non numeric/datetime
                values for xaxis, several actions are already taken by plt.
                """
            x = index.values
        else:
            self._need_to_set_index = True
            x = range(len(index))
    else:
        x = range(len(index))

    return x


# Traceback (ValueError)
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m')
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>()
----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m')

/home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize)
1209     """
1210     return DatetimeIndex(start=start, end=end, periods=periods,
-> 1211                          freq=freq, tz=tz, normalize=normalize)
1212
1213

/home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds)
202
203         if data is None and offset is None:
--> 204             raise ValueError("Must provide freq argument if no data is "
205                              "supplied")
206

ValueError: Must provide freq argument if no data is supplied

# Fixed code
def _get_xticks(self):
    index = self.data.index
    is_datetype = index.inferred_type in ("datetime", "date", "datetime64")

    if self.use_index:
        if index.is_numeric() or is_datetype:
            """
                Matplotlib supports numeric values or datetime objects as
                xaxis values. Taking LBYL approach here, by the time
                matplotlib raises exception when using non numeric/datetime
                values for xaxis, several actions are already taken by plt.
                """
            x = index._mpl_repr()
        else:
            self._need_to_set_index = True
            x = range(len(index))
    else:
        x = range(len(index))

    return x
# Buggy code
def _make_plot(self):
    # this is slightly deceptive
    x = self._get_xticks()

    plotf = self._get_plot_function()

    for i, (label, y) in enumerate(self._iter_data()):
        if self.subplots:
            ax = self.axes[i]
            style = "k"
        else:
            style = ""  # empty string ignored
            ax = self.ax
        if self.style:
            style = self.style

        plotf(ax, x, y, style, label=label, **self.kwds)
        ax.grid(self.grid)


# Traceback (ValueError)
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m')
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>()
----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m')

/home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize)
1209     """
1210     return DatetimeIndex(start=start, end=end, periods=periods,
-> 1211                          freq=freq, tz=tz, normalize=normalize)
1212
1213

/home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds)
202
203         if data is None and offset is None:
--> 204             raise ValueError("Must provide freq argument if no data is "
205                              "supplied")
206

ValueError: Must provide freq argument if no data is supplied

# Fixed code
def _make_plot(self):
    # this is slightly deceptive
    if self.use_index and self.has_ts_index:
        data = self._maybe_convert_index(self.data)
        self._make_ts_plot(data)
    else:
        x = self._get_xticks()

        plotf = self._get_plot_function()

        for i, (label, y) in enumerate(self._iter_data()):
            if self.subplots:
                ax = self.axes[i]
                style = "k"
            else:
                style = ""  # empty string ignored
                ax = self.ax
            if self.style:
                style = self.style

            plotf(ax, x, y, style, label=label, **self.kwds)
            ax.grid(self.grid)
# Buggy code
def _post_plot_logic(self):
    df = self.data

    if self.subplots and self.legend:
        self.axes[0].legend(loc="best")

    condition = (
        df.index.is_all_dates and not self.subplots or (self.subplots and self.sharex)
    )

    for ax in self.axes:
        if condition:
            format_date_labels(ax)


# Traceback (ValueError)
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m')
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>()
----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m')

/home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize)
1209     """
1210     return DatetimeIndex(start=start, end=end, periods=periods,
-> 1211                          freq=freq, tz=tz, normalize=normalize)
1212
1213

/home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds)
202
203         if data is None and offset is None:
--> 204             raise ValueError("Must provide freq argument if no data is "
205                              "supplied")
206

ValueError: Must provide freq argument if no data is supplied

# Fixed code
def _post_plot_logic(self):
    df = self.data

    if self.legend:
        if self.subplots:
            for ax in self.axes:
                ax.legend(loc="best")
        else:
            self.axes[0].legend(loc="best")

    condition = (
        not self.has_ts_index
        and df.index.is_all_dates
        and not self.subplots
        or (self.subplots and self.sharex)
    )

    for ax in self.axes:
        if condition:
            format_date_labels(ax)
# Buggy code
def scatter_plot(data, x, y, by=None, ax=None, figsize=None):
    """

    Returns
    -------
    fig : matplotlib.Figure
    """
    import matplotlib.pyplot as plt

    def plot_group(group, ax):
        xvals = group[x].values
        yvals = group[y].values
        ax.scatter(xvals, yvals)

    if by is not None:
        fig = _grouped_plot(plot_group, data, by=by, figsize=figsize, ax=ax)
    else:
        if ax is None:
            fig = plt.figure()
            ax = fig.add_subplot(111)
        else:
            fig = ax.get_figure()
        plot_group(data, ax)
        ax.set_ylabel(str(y))
        ax.set_xlabel(str(x))

    return fig


# Traceback (ValueError)
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m')
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>()
----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m')

/home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize)
1209     """
1210     return DatetimeIndex(start=start, end=end, periods=periods,
-> 1211                          freq=freq, tz=tz, normalize=normalize)
1212
1213

/home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds)
202
203         if data is None and offset is None:
--> 204             raise ValueError("Must provide freq argument if no data is "
205                              "supplied")
206

ValueError: Must provide freq argument if no data is supplied

# Fixed code
def scatter_plot(data, x, y, by=None, ax=None, figsize=None, grid=False):
    """

    Returns
    -------
    fig : matplotlib.Figure
    """
    import matplotlib.pyplot as plt

    def plot_group(group, ax):
        xvals = group[x].values
        yvals = group[y].values
        ax.scatter(xvals, yvals)
        ax.grid(grid)

    if by is not None:
        fig = _grouped_plot(plot_group, data, by=by, figsize=figsize, ax=ax)
    else:
        if ax is None:
            fig = plt.figure()
            ax = fig.add_subplot(111)
        else:
            fig = ax.get_figure()
        plot_group(data, ax)
        ax.set_ylabel(str(y))
        ax.set_xlabel(str(x))

        ax.grid(grid)

    return fig
# Buggy code
def plot_group(group, ax):
    xvals = group[x].values
    yvals = group[y].values
    ax.scatter(xvals, yvals)


# Traceback (ValueError)
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m')
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>()
----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m')

/home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize)
1209     """
1210     return DatetimeIndex(start=start, end=end, periods=periods,
-> 1211                          freq=freq, tz=tz, normalize=normalize)
1212
1213

/home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds)
202
203         if data is None and offset is None:
--> 204             raise ValueError("Must provide freq argument if no data is "
205                              "supplied")
206

ValueError: Must provide freq argument if no data is supplied

# Fixed code
def plot_group(group, ax):
    xvals = group[x].values
    yvals = group[y].values
    ax.scatter(xvals, yvals)
    ax.grid(grid)
# Buggy code
def initialize_options(self):
    self.all = True
    self._clean_me = []
    self._clean_trees = []
    for root, dirs, files in list(os.walk("pandas")):
        for f in files:
            if os.path.splitext(f)[-1] in (".pyc", ".so", ".o", ".pyd", ".c"):
                self._clean_me.append(pjoin(root, f))
        for d in dirs:
            if d == "__pycache__":
                self._clean_trees.append(pjoin(root, d))

    for d in ("build",):
        if os.path.exists(d):
            self._clean_trees.append(d)


# Traceback (ValueError)
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m')
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>()
----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m')

/home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize)
1209     """
1210     return DatetimeIndex(start=start, end=end, periods=periods,
-> 1211                          freq=freq, tz=tz, normalize=normalize)
1212
1213

/home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds)
202
203         if data is None and offset is None:
--> 204             raise ValueError("Must provide freq argument if no data is "
205                              "supplied")
206

ValueError: Must provide freq argument if no data is supplied

# Fixed code
def initialize_options(self):
    self.all = True
    self._clean_me = []
    self._clean_trees = []
    self._clean_exclude = [
        "np_datetime.c",
        "np_datetime_strings.c",
        "period.c",
        "ujson.c",
        "objToJSON.c",
        "JSONtoObj.c",
        "ultrajsonenc.c",
        "ultrajsondec.c",
    ]

    for root, dirs, files in list(os.walk("pandas")):
        for f in files:
            if f in self._clean_exclude:
                continue
            if os.path.splitext(f)[-1] in (".pyc", ".so", ".o", ".pyd", ".c"):
                self._clean_me.append(pjoin(root, f))
        for d in dirs:
            if d == "__pycache__":
                self._clean_trees.append(pjoin(root, d))

    for d in ("build",):
        if os.path.exists(d):
            self._clean_trees.append(d)
# Buggy code
def run_process():
    runner = BenchmarkRunner(
        benchmarks,
        REPO_PATH,
        REPO_URL,
        BUILD,
        DB_PATH,
        TMP_DIR,
        PREPARE,
        run_option="eod",
        start_date=START_DATE,
        module_dependencies=dependencies,
    )
    runner.run()


# Traceback (ValueError)
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m')
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>()
----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m')

/home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize)
1209     """
1210     return DatetimeIndex(start=start, end=end, periods=periods,
-> 1211                          freq=freq, tz=tz, normalize=normalize)
1212
1213

/home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds)
202
203         if data is None and offset is None:
--> 204             raise ValueError("Must provide freq argument if no data is "
205                              "supplied")
206

ValueError: Must provide freq argument if no data is supplied

# Fixed code
def run_process():
    runner = BenchmarkRunner(
        benchmarks,
        REPO_PATH,
        REPO_URL,
        BUILD,
        DB_PATH,
        TMP_DIR,
        PREPARE,
        always_clean=True,
        run_option="eod",
        start_date=START_DATE,
        module_dependencies=dependencies,
    )
    runner.run()
# Buggy code
def __init__(self, seq, key=lambda x: x):
    for value in seq:
        k = key(value)
        self.setdefault(k, []).append(value)


# Traceback (TypeError)
In [20]: df
Out[20]:
value
id
t1 a   1
b   2
c   3
t2 a   7
b   8

In [21]: df.ix[:, 'value']
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/wesm/Dropbox/book/svn/<ipython-input-21-7d089958dc90> in <module>()
----> 1 df.ix[:, 'value']

/home/wesm/code/pandas/pandas/core/indexing.pyc in __getitem__(self, key)
28                 pass
29
---> 30             return self._getitem_tuple(key)
31         else:
32             return self._getitem_axis(key, axis=0)

/home/wesm/code/pandas/pandas/core/indexing.pyc in _getitem_tuple(self, tup)
97     def _getitem_tuple(self, tup):
98         try:
---> 99             return self._getitem_lowerdim(tup)
100         except IndexingError:
101             pass

/home/wesm/code/pandas/pandas/core/indexing.pyc in _getitem_lowerdim(self, tup)
126                 pass
127             except Exception:
--> 128                 if tup[0] not in ax0:
129                     raise
130

/home/wesm/code/pandas/pandas/core/index.pyc in __contains__(self, key)
209
210     def __contains__(self, key):
--> 211         return key in self._engine
212
213     def __hash__(self):

/home/wesm/code/pandas/pandas/_engines.so in pandas._engines.DictIndexEngine.__contains__ (pandas/src/engines.c:1958)()

TypeError: unhashable type

# Fixed code
def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
    f = UTF8Recoder(f, encoding)
    self.reader = csv.reader(f, dialect=dialect, **kwds)
# Buggy code
def unique(self):
    """
    Return array of unique values in the Series. Significantly faster than
    numpy.unique

    Returns
    -------
    uniques : ndarray
    """
    values = self.values
    if not values.dtype == np.object_:
        values = values.astype("O")
    table = lib.PyObjectHashTable(len(values))
    uniques = lib.list_to_object_array(table.unique(values))
    return lib.maybe_convert_objects(uniques)


# Traceback (TypeError)
In [20]: df
Out[20]:
value
id
t1 a   1
b   2
c   3
t2 a   7
b   8

In [21]: df.ix[:, 'value']
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/wesm/Dropbox/book/svn/<ipython-input-21-7d089958dc90> in <module>()
----> 1 df.ix[:, 'value']

/home/wesm/code/pandas/pandas/core/indexing.pyc in __getitem__(self, key)
28                 pass
29
---> 30             return self._getitem_tuple(key)
31         else:
32             return self._getitem_axis(key, axis=0)

/home/wesm/code/pandas/pandas/core/indexing.pyc in _getitem_tuple(self, tup)
97     def _getitem_tuple(self, tup):
98         try:
---> 99             return self._getitem_lowerdim(tup)
100         except IndexingError:
101             pass

/home/wesm/code/pandas/pandas/core/indexing.pyc in _getitem_lowerdim(self, tup)
126                 pass
127             except Exception:
--> 128                 if tup[0] not in ax0:
129                     raise
130

/home/wesm/code/pandas/pandas/core/index.pyc in __contains__(self, key)
209
210     def __contains__(self, key):
--> 211         return key in self._engine
212
213     def __hash__(self):

/home/wesm/code/pandas/pandas/_engines.so in pandas._engines.DictIndexEngine.__contains__ (pandas/src/engines.c:1958)()

TypeError: unhashable type

# Fixed code
def unique(self):
    """
    Return array of unique values in the Series. Significantly faster than
    numpy.unique

    Returns
    -------
    uniques : ndarray
    """
    values = self.values
    if issubclass(values.dtype.type, np.floating):
        table = lib.Float64HashTable(len(values))
        uniques = np.array(table.unique(values), dtype="f8")
    else:
        if not values.dtype == np.object_:
            values = values.astype("O")
        table = lib.PyObjectHashTable(len(values))
        uniques = lib.list_to_object_array(table.unique(values))
        uniques = lib.maybe_convert_objects(uniques)
    return uniques
# Buggy code
def from_csv(cls, path, sep=",", parse_dates=True):
    """
    Read delimited file into Series

    Parameters
    ----------
    path : string
    sep : string, default ','
        Field delimiter
    parse_dates : boolean, default True
        Parse dates. Different default from read_table

    Returns
    -------
    y : Series
    """
    from pandas.core.frame import DataFrame

    df = DataFrame.from_csv(path, header=None, sep=sep, parse_dates=parse_dates)
    return df[df.columns[0]]


# Traceback (TypeError)
In [20]: df
Out[20]:
value
id
t1 a   1
b   2
c   3
t2 a   7
b   8

In [21]: df.ix[:, 'value']
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/wesm/Dropbox/book/svn/<ipython-input-21-7d089958dc90> in <module>()
----> 1 df.ix[:, 'value']

/home/wesm/code/pandas/pandas/core/indexing.pyc in __getitem__(self, key)
28                 pass
29
---> 30             return self._getitem_tuple(key)
31         else:
32             return self._getitem_axis(key, axis=0)

/home/wesm/code/pandas/pandas/core/indexing.pyc in _getitem_tuple(self, tup)
97     def _getitem_tuple(self, tup):
98         try:
---> 99             return self._getitem_lowerdim(tup)
100         except IndexingError:
101             pass

/home/wesm/code/pandas/pandas/core/indexing.pyc in _getitem_lowerdim(self, tup)
126                 pass
127             except Exception:
--> 128                 if tup[0] not in ax0:
129                     raise
130

/home/wesm/code/pandas/pandas/core/index.pyc in __contains__(self, key)
209
210     def __contains__(self, key):
--> 211         return key in self._engine
212
213     def __hash__(self):

/home/wesm/code/pandas/pandas/_engines.so in pandas._engines.DictIndexEngine.__contains__ (pandas/src/engines.c:1958)()

TypeError: unhashable type

# Fixed code
def from_csv(
    cls, path, sep=",", parse_dates=True, header=None, index_col=0, encoding=None
):
    """
    Read delimited file into Series

    Parameters
    ----------
    path : string
    sep : string, default ','
        Field delimiter
    parse_dates : boolean, default True
        Parse dates. Different default from read_table
    header : int, default 0
        Row to use at header (skip prior rows)
    index_col : int or sequence, default 0
        Column to use for index. If a sequence is given, a MultiIndex
        is used. Different default from read_table
    encoding : string, optional
        a string representing the encoding to use if the contents are
        non-ascii, for python versions prior to 3

    Returns
    -------
    y : Series
    """
    from pandas.core.frame import DataFrame

    df = DataFrame.from_csv(
        path,
        header=header,
        index_col=index_col,
        sep=sep,
        parse_dates=parse_dates,
        encoding=encoding,
    )
    return df.ix[:, 0]
# Buggy code
def to_csv(self, path, index=True):
    """
    Write the Series to a CSV file

    Parameters
    ----------
    path : string or None
        Output filepath. If None, write to stdout
    index : bool, optional
        Include the index as row names or not
    """
    f = open(path, "w")
    csvout = csv.writer(f, lineterminator="\n")
    csvout.writerows(self.iteritems(index))
    f.close()


# Traceback (TypeError)
In [20]: df
Out[20]:
value
id
t1 a   1
b   2
c   3
t2 a   7
b   8

In [21]: df.ix[:, 'value']
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/wesm/Dropbox/book/svn/<ipython-input-21-7d089958dc90> in <module>()
----> 1 df.ix[:, 'value']

/home/wesm/code/pandas/pandas/core/indexing.pyc in __getitem__(self, key)
28                 pass
29
---> 30             return self._getitem_tuple(key)
31         else:
32             return self._getitem_axis(key, axis=0)

/home/wesm/code/pandas/pandas/core/indexing.pyc in _getitem_tuple(self, tup)
97     def _getitem_tuple(self, tup):
98         try:
---> 99             return self._getitem_lowerdim(tup)
100         except IndexingError:
101             pass

/home/wesm/code/pandas/pandas/core/indexing.pyc in _getitem_lowerdim(self, tup)
126                 pass
127             except Exception:
--> 128                 if tup[0] not in ax0:
129                     raise
130

/home/wesm/code/pandas/pandas/core/index.pyc in __contains__(self, key)
209
210     def __contains__(self, key):
--> 211         return key in self._engine
212
213     def __hash__(self):

/home/wesm/code/pandas/pandas/_engines.so in pandas._engines.DictIndexEngine.__contains__ (pandas/src/engines.c:1958)()

TypeError: unhashable type

# Fixed code
def to_csv(
    self,
    path,
    index=True,
    sep=",",
    na_rep="",
    header=False,
    index_label=None,
    mode="w",
    nanRep=None,
    encoding=None,
):
    """
    Write Series to a comma-separated values (csv) file

    Parameters
    ----------
    path : string
        File path
    nanRep : string, default ''
        Missing data rep'n
    header : boolean, default False
        Write out series name
    index : boolean, default True
        Write row names (index)
    index_label : string or sequence, default None
        Column label for index column(s) if desired. If None is given, and
        `header` and `index` are True, then the index names are used. A
        sequence should be given if the DataFrame uses MultiIndex.
    mode : Python write mode, default 'w'
    sep : character, default ","
        Field delimiter for the output file.
    encoding : string, optional
        a string representing the encoding to use if the contents are
        non-ascii, for python versions prior to 3
    """
    from pandas.core.frame import DataFrame

    df = DataFrame(self)
    df.to_csv(
        path,
        index=index,
        sep=sep,
        na_rep=na_rep,
        header=header,
        index_label=index_label,
        mode=mode,
        nanRep=nanRep,
        encoding=encoding,
    )
# Buggy code
def unstack(self, level=-1):
    """
    "Unstack" level from MultiLevel index to produce reshaped DataFrame

    Parameters
    ----------
    level : int, string, or list of these, default last level
        Level(s) to unstack, can pass level name

    Examples
    --------
    >>> s
    one  a   1.
    one  b   2.
    two  a   3.
    two  b   4.

    >>> s.unstack(level=-1)
         a   b
    one  1.  2.
    two  3.  4.

    >>> s.unstack(level=0)
       one  two
    a  1.   2.
    b  3.   4.

    Returns
    -------
    unstacked : DataFrame
    """
    from pandas.core.reshape import unstack

    if isinstance(level, (tuple, list)):
        result = self
        for lev in level:
            result = unstack(result, lev)
        return result
    else:
        return unstack(self, level)


# Traceback (IndexError)
In [180]: df.unstack(level=[0,1])
Out[180]:
A                   A                   B                   B
bar                 foo                 bar                 foo
a         b         a         b         a         b         a         b
0  266.666m  806.406m -1.627    -494.049m  246.100m  894.707m  1.301     120.371m
1 -1.319     638.371m  955.212m -55.806m   475.675m  409.483m  580.450m  169.247m


In [177]: df.unstack(level=[1,2])
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
...
IndexError: pop index out of range

In [178]: df.unstack(level=[1,1])
Out[178]:
A                   A                   B                   B
0                   1                   0                   1
a         b         a         b         a         b         a         b
bar  266.666m  806.406m -1.319     638.371m  246.100m  894.707m  475.675m  409.483m
foo -1.627    -494.049m  955.212m -55.806m   1.301     120.371m  580.450m  169.247m

# Fixed code
def unstack(self, level=-1):
    """
    "Unstack" level from MultiLevel index to produce reshaped DataFrame

    Parameters
    ----------
    level : int, string, or list of these, default last level
        Level(s) to unstack, can pass level name

    Examples
    --------
    >>> s
    one  a   1.
    one  b   2.
    two  a   3.
    two  b   4.

    >>> s.unstack(level=-1)
         a   b
    one  1.  2.
    two  3.  4.

    >>> s.unstack(level=0)
       one  two
    a  1.   2.
    b  3.   4.

    Returns
    -------
    unstacked : DataFrame
    """
    from pandas.core.reshape import unstack

    if isinstance(level, (tuple, list)):
        result = self
        to_unstack = level
        while to_unstack:
            lev = to_unstack[0]
            result = unstack(result, lev)
            to_unstack = [
                other - 1 if other > lev else other for other in to_unstack[1:]
            ]
        return result
    else:
        return unstack(self, level)
# Buggy code
def unique_with_labels(values):
    uniques = Index(lib.fast_unique(values))
    labels = lib.get_unique_labels(values, uniques.indexMap)
    return uniques, labels


# Traceback (AssertionError)
df.as_matrix()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/pandas/core/frame.py", line 671, in as_matrix
self._consolidate_inplace()
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/pandas/core/generic.py", line 267, in _consolidate_inplace
self._data = self._data.consolidate()
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/pandas/core/internals.py", line 516, in consolidate
new_blocks = _consolidate(self.blocks, self.items)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/pandas/core/internals.py", line 938, in _consolidate
new_block = _merge_blocks(list(group_blocks), items)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/pandas/core/internals.py", line 951, in _merge_blocks
do_integrity_check=True)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/pandas/core/internals.py", line 211, in make_block
do_integrity_check=do_integrity_check)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/pandas/core/internals.py", line 34, in __init__
self._check_integrity()
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/pandas/core/internals.py", line 40, in _check_integrity
return (self.ref_locs[1:] > self.ref_locs[:-1]).all()
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/pandas/core/internals.py", line 47, in ref_locs
assert((indexer != -1).all())
AssertionError

# Fixed code
def unique_with_labels(values):
    uniques = Index(lib.fast_unique(values))
    labels = lib.get_unique_labels(values, uniques.indexMap)
    uniques._cleanup()
    return uniques, labels
# Buggy code
def from_blocks(cls, blocks, index):
    # also checks for overlap
    items = _union_block_items(blocks)
    ndim = blocks[0].ndim
    return BlockManager(blocks, [items, index])


# Traceback (IndexError)
In [1]: df = DataFrame(index=['a', 'b', 'c'])

In [2]: df.ix['a']
ERROR: An unexpected error occurred while tokenizing input
The following traceback may be corrupted or invalid
The error message is: ('EOF in multi-line statement', (2, 0))

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
/home/wesm/code/pandas/<ipython-input-2-6181dcf1ffea> in <module>()
----> 1 df.ix['a']

/home/wesm/code/pandas/pandas/core/indexing.pyc in __getitem__(self, key)
102             return self._fancy_getitem(key, axis=0)
103         else:
--> 104             return self._fancy_getitem_axis(key, axis=0)
105
106     def __setitem__(self, key, value):

/home/wesm/code/pandas/pandas/core/indexing.pyc in _fancy_getitem_axis(self, key, axis)
200                 return self.frame.xs(idx)
201             else:
--> 202                 return self.frame.xs(idx, copy=False)
203         else:
204             col = key

/home/wesm/code/pandas/pandas/core/frame.pyc in xs(self, key, copy)
839
840         self._consolidate_inplace()
--> 841         values = self._data.xs(key, axis=1, copy=copy)
842         return Series(values.as_matrix(), index=self.columns)
843

/home/wesm/code/pandas/pandas/core/internals.pyc in xs(self, key, axis, copy)
451                 new_blocks.append(newb)
452         else:
--> 453             vals = self.blocks[0].values[slicer]
454             if copy:
455                 vals = vals.copy()

IndexError: list index out of range

# Fixed code
def from_blocks(cls, blocks, index):
    # also checks for overlap
    items = _union_block_items(blocks)
    return BlockManager(blocks, [items, index])
# Buggy code
def reduce_CreateConstraint(self, *kids):
    r"""%reduce ABSTRACT CONSTRAINT NodeName OptOnExpr \
                    OptExtendingSimple"""
    self.val = qlast.CreateConstraint(
        name=kids[2].val,
        subject=kids[3].val,
        extends=kids[4].val,
    )


# Traceback (AttributeError)
db> CREATE ABSTRACT CONSTRAINT `🚀🍿` EXTENDING max_len_value;
OK: CREATE
db> CREATE SCALAR TYPE foo EXTENDING str {
...     CREATE CONSTRAINT `🚀🍿`(10);
... };
ERROR: InternalServerError: 'NoneType' object has no attribute 'get_parameter_name'
Hint: This is most likely a bug in EdgeDB. Please consider opening an issue ticket at https://github.com/edgedb/edgedb/issues/new?template=bug_report.md
Server traceback:
Traceback (most recent call last):
File "/home/victor/dev/magicstack/edgedb/edb/server/procpool/worker.py", line 75, in worker
res = await meth(*args)
File "/home/victor/dev/magicstack/edgedb/edb/server/compiler/compiler.py", line 1480, in compile_eql_tokens
return self._compile(ctx=ctx, tokens=eql_tokens)
File "/home/victor/dev/magicstack/edgedb/edb/server/compiler/compiler.py", line 1141, in _compile
comp: dbstate.BaseQuery = self._compile_dispatch_ql(ctx, stmt)
File "/home/victor/dev/magicstack/edgedb/edb/server/compiler/compiler.py", line 1076, in _compile_dispatch_ql
return self._compile_ql_ddl(ctx, ql)
File "/home/victor/dev/magicstack/edgedb/edb/server/compiler/compiler.py", line 763, in _compile_ql_ddl
cmd = s_ddl.delta_from_ddl(
File "/home/victor/dev/magicstack/edgedb/edb/schema/ddl.py", line 466, in delta_from_ddl
_, cmd = _delta_from_ddl(ddl_stmt, schema=schema, modaliases=modaliases,
File "/home/victor/dev/magicstack/edgedb/edb/schema/ddl.py", line 496, in _delta_from_ddl
schema = cmd.apply(schema, context)
File "/home/victor/dev/magicstack/edgedb/edb/schema/delta.py", line 1531, in apply
schema = self._create_innards(schema, context)
File "/home/victor/dev/magicstack/edgedb/edb/schema/inheriting.py", line 622, in _create_innards
return super()._create_innards(schema, context)
File "/home/victor/dev/magicstack/edgedb/edb/schema/delta.py", line 1498, in _create_innards
schema = op.apply(schema, context=context)
File "/home/victor/dev/magicstack/edgedb/edb/schema/delta.py", line 1527, in apply
schema = self._create_begin(schema, context)
File "/home/victor/dev/magicstack/edgedb/edb/schema/constraints.py", line 641, in _create_begin
constr_base, attrs, inh = Constraint.get_concrete_constraint_attrs(
File "/home/victor/dev/magicstack/edgedb/edb/schema/constraints.py", line 226, in get_concrete_constraint_attrs
args_map = qlutils.index_parameters(
File "/home/victor/dev/magicstack/edgedb/edb/edgeql/utils.py", line 92, in index_parameters
result[p.get_parameter_name(schema)] = e
AttributeError: 'NoneType' object has no attribute 'get_parameter_name'

# Fixed code
def reduce_CreateConstraint(self, *kids):
    r"""%reduce ABSTRACT CONSTRAINT NodeName OptOnExpr \
                    OptExtendingSimple"""
    self.val = qlast.CreateConstraint(
        name=kids[2].val,
        subject=kids[3].val,
        bases=kids[4].val,
    )
# Buggy code
def apply(self, schema, context):
    attrsubj = context.get(AnnotationSubjectCommandContext)
    assert attrsubj, "Annotation commands must be run in " + "AnnotationSubject context"

    with context(AnnotationValueCommandContext(schema, self, None)):
        name = sn.shortname_from_fullname(self.classname)
        attrs = attrsubj.scls.get_annotations(schema)
        annotation = attrs.get(schema, name, None)
        if annotation is None:
            schema, annotation = super().apply(schema, context)
            schema = self.add_annotation(schema, annotation, attrsubj.scls)
        else:
            schema, annotation = sd.AlterObject.apply(self, schema, context)

        return schema, annotation


# Traceback (edb.schema.objects.FieldValueNotFoundError)
Traceback (most recent call last):
File "/home/victor/dev/magicstack/edgedb/tests/test_schema.py", line 2084, in test_migrations_equivalence_annotation_01
"""])
File "/home/victor/dev/magicstack/edgedb/tests/test_schema.py", line 603, in _assert_migration_equivalence
self._assert_migration_consistency(migrations[-1])
File "/home/victor/dev/magicstack/edgedb/tests/test_schema.py", line 588, in _assert_migration_consistency
diff = s_ddl.delta_schemas(baseline_schema, test_schema)
File "/home/victor/dev/magicstack/edgedb/edb/schema/ddl.py", line 87, in delta_schemas
old, new, old_schema=schema2, new_schema=schema1))
File "/home/victor/dev/magicstack/edgedb/edb/schema/objects.py", line 1143, in delta_sets
their_schema=old_schema)
File "/home/victor/dev/magicstack/edgedb/edb/schema/objects.py", line 778, in compare
context=context)
File "/home/victor/dev/magicstack/edgedb/edb/schema/objects.py", line 796, in compare_field_value
compcoef=field.compcoef or 0.5)
File "/home/victor/dev/magicstack/edgedb/edb/schema/objects.py", line 1466, in compare_values
their_schema=their_schema, context=context))
File "/home/victor/dev/magicstack/edgedb/edb/schema/objects.py", line 770, in compare
their_value = other.get_field_value(their_schema, field_name)
File "/home/victor/dev/magicstack/edgedb/edb/schema/objects.py", line 642, in get_field_value
schema, field_name, allow_default=allow_default)
File "/home/victor/dev/magicstack/edgedb/edb/schema/objects.py", line 635, in _get_schema_field_value
f'{self!r} object has no value for field {field_name!r}')
edb.schema.objects.FieldValueNotFoundError: <AnnotationValue: at 0x7f27da85bf60> object has no value for field 'annotation'

# Fixed code
def apply(self, schema, context):
    attrsubj = context.get(AnnotationSubjectCommandContext)
    assert attrsubj, "Annotation commands must be run in " + "AnnotationSubject context"

    name = sn.shortname_from_fullname(self.classname)
    attrs = attrsubj.scls.get_annotations(schema)
    annotation = attrs.get(schema, name, None)
    if annotation is None:
        schema, annotation = super().apply(schema, context)
    else:
        schema, annotation = sd.AlterObject.apply(self, schema, context)

    return schema, annotation
# Buggy code
def sync_task_status(
    job_id, component_name, task_id, role, party_id, initiator_party_id, task_info
):
    for dest_party_id in {party_id, initiator_party_id}:
        if party_id != initiator_party_id and dest_party_id == initiator_party_id:
            # do not pass the process id to the initiator
            task_info["f_run_ip"] = ""
        federated_api(
            job_id=job_id,
            method="POST",
            endpoint="/{}/job/{}/{}/{}/{}/{}/status".format(
                API_VERSION, job_id, component_name, task_id, role, party_id
            ),
            src_party_id=party_id,
            dest_party_id=dest_party_id,
            json_body=task_info,
            work_mode=RuntimeConfig.WORK_MODE,
        )


# Traceback (ImportError)
stdout:Traceback (most recent call last):
File "/home/wy/FATE/examples/federatedml-1.0-examples/../../fate_flow/fate_flow_client.py", line 17, in <module>
import argparse
File "/home/wy/.pyenv/versions/3.6.0/lib/python3.6/argparse.py", line 86, in <module>
import collections as _collections
File "/home/wy/.pyenv/versions/3.6.0/lib/python3.6/collections/__init__.py", line 26, in <module>
from operator import itemgetter as _itemgetter, eq as _eq
ImportError: cannot import name 'itemgetter'

# Fixed code
def sync_task_status(
    job_id, component_name, task_id, role, party_id, initiator_party_id, task_info
):
    for dest_party_id in {party_id, initiator_party_id}:
        if party_id != initiator_party_id and dest_party_id == initiator_party_id:
            # do not pass the process id to the initiator
            task_info["f_run_ip"] = ""
        federated_api(
            job_id=job_id,
            method="POST",
            endpoint="/{}/schedule/{}/{}/{}/{}/{}/status".format(
                API_VERSION, job_id, component_name, task_id, role, party_id
            ),
            src_party_id=party_id,
            dest_party_id=dest_party_id,
            json_body=task_info,
            work_mode=RuntimeConfig.WORK_MODE,
        )
# Buggy code
def distribute_job(job, roles, job_initiator):
    for role, partys in roles.items():
        job.f_role = role
        for party_id in partys:
            job.f_party_id = party_id
            if role == job_initiator["role"] and party_id == job_initiator["party_id"]:
                job.f_is_initiator = 1
            else:
                job.f_is_initiator = 0
            federated_api(
                job_id=job.f_job_id,
                method="POST",
                endpoint="/{}/job/{}/{}/{}/create".format(
                    API_VERSION, job.f_job_id, role, party_id
                ),
                src_party_id=job_initiator["party_id"],
                dest_party_id=party_id,
                json_body=job.to_json(),
                work_mode=job.f_work_mode,
            )


# Traceback (ImportError)
stdout:Traceback (most recent call last):
File "/home/wy/FATE/examples/federatedml-1.0-examples/../../fate_flow/fate_flow_client.py", line 17, in <module>
import argparse
File "/home/wy/.pyenv/versions/3.6.0/lib/python3.6/argparse.py", line 86, in <module>
import collections as _collections
File "/home/wy/.pyenv/versions/3.6.0/lib/python3.6/collections/__init__.py", line 26, in <module>
from operator import itemgetter as _itemgetter, eq as _eq
ImportError: cannot import name 'itemgetter'

# Fixed code
def distribute_job(job, roles, job_initiator):
    for role, partys in roles.items():
        job.f_role = role
        for party_id in partys:
            job.f_party_id = party_id
            if role == job_initiator["role"] and party_id == job_initiator["party_id"]:
                job.f_is_initiator = 1
            else:
                job.f_is_initiator = 0
            federated_api(
                job_id=job.f_job_id,
                method="POST",
                endpoint="/{}/schedule/{}/{}/{}/create".format(
                    API_VERSION, job.f_job_id, role, party_id
                ),
                src_party_id=job_initiator["party_id"],
                dest_party_id=party_id,
                json_body=job.to_json(),
                work_mode=job.f_work_mode,
            )
# Buggy code
def sync_job_status(job_id, roles, work_mode, initiator_party_id, job_info):
    for role, partys in roles.items():
        job_info["f_role"] = role
        for party_id in partys:
            job_info["f_party_id"] = party_id
            federated_api(
                job_id=job_id,
                method="POST",
                endpoint="/{}/job/{}/{}/{}/status".format(
                    API_VERSION, job_id, role, party_id
                ),
                src_party_id=initiator_party_id,
                dest_party_id=party_id,
                json_body=job_info,
                work_mode=work_mode,
            )


# Traceback (ImportError)
stdout:Traceback (most recent call last):
File "/home/wy/FATE/examples/federatedml-1.0-examples/../../fate_flow/fate_flow_client.py", line 17, in <module>
import argparse
File "/home/wy/.pyenv/versions/3.6.0/lib/python3.6/argparse.py", line 86, in <module>
import collections as _collections
File "/home/wy/.pyenv/versions/3.6.0/lib/python3.6/collections/__init__.py", line 26, in <module>
from operator import itemgetter as _itemgetter, eq as _eq
ImportError: cannot import name 'itemgetter'

# Fixed code
def sync_job_status(job_id, roles, work_mode, initiator_party_id, job_info):
    for role, partys in roles.items():
        job_info["f_role"] = role
        for party_id in partys:
            job_info["f_party_id"] = party_id
            federated_api(
                job_id=job_id,
                method="POST",
                endpoint="/{}/schedule/{}/{}/{}/status".format(
                    API_VERSION, job_id, role, party_id
                ),
                src_party_id=initiator_party_id,
                dest_party_id=party_id,
                json_body=job_info,
                work_mode=work_mode,
            )
# Buggy code
def init_config(**kwargs):
    for k, v in kwargs.items():
        if hasattr(RuntimeConfig, k):
            setattr(RuntimeConfig, k, v)


# Traceback (ImportError)
stdout:Traceback (most recent call last):
File "/home/wy/FATE/examples/federatedml-1.0-examples/../../fate_flow/fate_flow_client.py", line 17, in <module>
import argparse
File "/home/wy/.pyenv/versions/3.6.0/lib/python3.6/argparse.py", line 86, in <module>
import collections as _collections
File "/home/wy/.pyenv/versions/3.6.0/lib/python3.6/collections/__init__.py", line 26, in <module>
from operator import itemgetter as _itemgetter, eq as _eq
ImportError: cannot import name 'itemgetter'

# Fixed code
def init_config(**kwargs):
    for k, v in kwargs.items():
        if hasattr(RuntimeConfig, k):
            setattr(RuntimeConfig, k, v)
            if k == "HTTP_PORT":
                setattr(
                    RuntimeConfig,
                    "JOB_SERVER_HOST",
                    "{}:{}".format(get_lan_ip(), RuntimeConfig.HTTP_PORT),
                )