gurudesh/pytracebugs huggingface dataset:
# Buggy code
def _process_msg(self, msg):
    if "data" not in msg:
        return {}
    msg["data"] = dict(msg["data"])
    for col, values in msg["data"].items():
        if isinstance(values, dict):
            items = sorted([(int(k), v) for k, v in values.items()])
            values = [v for k, v in items]
        elif isinstance(values, list) and values and isinstance(values[0], dict):
            new_values = []
            for vals in values:
                if isinstance(vals, dict):
                    vals = sorted([(int(k), v) for k, v in vals.items()])
                    vals = [v for k, v in vals]
                new_values.append(vals)
            values = new_values
        msg["data"][col] = values
    return self._transform(msg)


# Traceback (AttributeError)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-42-14b61901e2c2> in <module>
----> 1 poly_annotator2.selected

~/projects/holoviews_annotators/holoviews/annotators.py in selected(self)
85     @property
86     def selected(self):
---> 87         selected = self.annotator.selected
88         if Store.current_backend == 'bokeh':
89             return selected.opts(clone=True, tools=['hover'])

~/projects/holoviews_annotators/holoviews/annotators.py in selected(self)
400         index = self._selection.index
401         data = [p for i, p in enumerate(self._stream.element.split()) if i in index]
--> 402         return self.element.clone(data)
403
404

AttributeError: 'PolyAnnotator' object has no attribute 'element'

# Fixed code
def _process_msg(self, msg):
    if "data" not in msg:
        return {}
    msg["data"] = dict(msg["data"])
    for col, values in msg["data"].items():
        if isinstance(values, dict):
            items = sorted([(int(k), v) for k, v in values.items()])
            values = [v for k, v in items]
        elif isinstance(values, list) and values and isinstance(values[0], dict):
            new_values = []
            for vals in values:
                if isinstance(vals, dict):
                    vals = sorted([(int(k), v) for k, v in vals.items()])
                    vals = [v for k, v in vals]
                new_values.append(vals)
            values = new_values
        elif any(isinstance(v, (int, float)) for v in values):
            values = [np.nan if v is None else v for v in values]
        msg["data"][col] = values
    return self._transform(msg)
# Buggy code
def dimension_values(self, dimension, expanded=True, flat=True):
    index = self.get_dimension_index(dimension)
    if index == 0:
        return np.array([self.data if np.isscalar(self.data) else self.data[index]])
    elif index == 1:
        return [] if np.isscalar(self.data) else np.array([self.data[1]])
    else:
        return super(Annotation, self).dimension_values(dimension)


# Traceback (TypeError)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-529bcc0b7b40> in <module>
----> 1 spline.clone()

~/Desktop/development/holoviews/holoviews/element/annotation.py in clone(self, *args, **overrides)
72         if 'id' not in settings:
73             settings['id'] = self.id
---> 74         return self.__class__(*args, **settings)
75
76

TypeError: __init__() missing 1 required positional argument: 'spline_points'

# Fixed code
def dimension_values(self, dimension, expanded=True, flat=True):
    """Return the values along the requested dimension.

    Args:
        dimension: The dimension to return values for
        expanded (bool, optional): Whether to expand values
        flat (bool, optional): Whether to flatten array

    Returns:
        NumPy array of values along the requested dimension
    """
    index = self.get_dimension_index(dimension)
    if index == 0:
        return np.array([self.data if np.isscalar(self.data) else self.data[index]])
    elif index == 1:
        return [] if np.isscalar(self.data) else np.array([self.data[1]])
    else:
        return super(Annotation, self).dimension_values(dimension)
# Buggy code
def dimension_values(self, dimension, expanded=True, flat=True):
    index = self.get_dimension_index(dimension)
    if index == 0:
        return np.array([self.data])
    elif index == 1:
        return np.array([])
    else:
        return super(VLine, self).dimension_values(dimension)


# Traceback (TypeError)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-529bcc0b7b40> in <module>
----> 1 spline.clone()

~/Desktop/development/holoviews/holoviews/element/annotation.py in clone(self, *args, **overrides)
72         if 'id' not in settings:
73             settings['id'] = self.id
---> 74         return self.__class__(*args, **settings)
75
76

TypeError: __init__() missing 1 required positional argument: 'spline_points'

# Fixed code
def dimension_values(self, dimension, expanded=True, flat=True):
    """Return the values along the requested dimension.

    Args:
        dimension: The dimension to return values for
        expanded (bool, optional): Whether to expand values
        flat (bool, optional): Whether to flatten array

    Returns:
        NumPy array of values along the requested dimension
    """
    index = self.get_dimension_index(dimension)
    if index == 0:
        return np.array([self.data])
    elif index == 1:
        return np.array([])
    else:
        return super(VLine, self).dimension_values(dimension)
# Buggy code
def dimension_values(self, dimension, expanded=True, flat=True):
    index = self.get_dimension_index(dimension)
    if index == 0:
        return np.array([])
    elif index == 1:
        return np.array([self.data])
    else:
        return super(HLine, self).dimension_values(dimension)


# Traceback (TypeError)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-529bcc0b7b40> in <module>
----> 1 spline.clone()

~/Desktop/development/holoviews/holoviews/element/annotation.py in clone(self, *args, **overrides)
72         if 'id' not in settings:
73             settings['id'] = self.id
---> 74         return self.__class__(*args, **settings)
75
76

TypeError: __init__() missing 1 required positional argument: 'spline_points'

# Fixed code
def dimension_values(self, dimension, expanded=True, flat=True):
    """Return the values along the requested dimension.

    Args:
        dimension: The dimension to return values for
        expanded (bool, optional): Whether to expand values
        flat (bool, optional): Whether to flatten array

    Returns:
        NumPy array of values along the requested dimension
    """
    index = self.get_dimension_index(dimension)
    if index == 0:
        return np.array([])
    elif index == 1:
        return np.array([self.data])
    else:
        return super(HLine, self).dimension_values(dimension)
# Buggy code
def dimension_values(self, dimension, expanded=True, flat=True):
    index = self.get_dimension_index(dimension)
    if index in [0, 1]:
        return np.array([point[index] for point in self.data[0]])
    else:
        return super(Spline, self).dimension_values(dimension)


# Traceback (TypeError)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-529bcc0b7b40> in <module>
----> 1 spline.clone()

~/Desktop/development/holoviews/holoviews/element/annotation.py in clone(self, *args, **overrides)
72         if 'id' not in settings:
73             settings['id'] = self.id
---> 74         return self.__class__(*args, **settings)
75
76

TypeError: __init__() missing 1 required positional argument: 'spline_points'

# Fixed code
def dimension_values(self, dimension, expanded=True, flat=True):
    """Return the values along the requested dimension.

    Args:
        dimension: The dimension to return values for
        expanded (bool, optional): Whether to expand values
        flat (bool, optional): Whether to flatten array

    Returns:
        NumPy array of values along the requested dimension
    """
    index = self.get_dimension_index(dimension)
    if index in [0, 1]:
        return np.array([point[index] for point in self.data[0]])
    else:
        return super(Spline, self).dimension_values(dimension)
# Buggy code
def dimension_values(self, dimension, expanded=True, flat=True):
    index = self.get_dimension_index(dimension)
    if index == 0:
        return np.array([self.x])
    elif index == 1:
        return np.array([self.y])
    else:
        return super(Arrow, self).dimension_values(dimension)


# Traceback (TypeError)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-529bcc0b7b40> in <module>
----> 1 spline.clone()

~/Desktop/development/holoviews/holoviews/element/annotation.py in clone(self, *args, **overrides)
72         if 'id' not in settings:
73             settings['id'] = self.id
---> 74         return self.__class__(*args, **settings)
75
76

TypeError: __init__() missing 1 required positional argument: 'spline_points'

# Fixed code
def dimension_values(self, dimension, expanded=True, flat=True):
    """Return the values along the requested dimension.

    Args:
        dimension: The dimension to return values for
        expanded (bool, optional): Whether to expand values
        flat (bool, optional): Whether to flatten array

    Returns:
        NumPy array of values along the requested dimension
    """
    index = self.get_dimension_index(dimension)
    if index == 0:
        return np.array([self.x])
    elif index == 1:
        return np.array([self.y])
    else:
        return super(Arrow, self).dimension_values(dimension)
# Buggy code
def clone(self, *args, **overrides):
    if len(args) == 1 and isinstance(args[0], tuple):
        args = args[0]
    # Apply name mangling for __ attribute
    pos_args = getattr(self, "_" + type(self).__name__ + "__pos_params", [])
    settings = {
        k: v
        for k, v in dict(self.get_param_values(), **overrides).items()
        if k not in pos_args[: len(args)]
    }
    if "id" not in settings:
        settings["id"] = self.id
    return self.__class__(*args, **settings)


# Traceback (TypeError)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-529bcc0b7b40> in <module>
----> 1 spline.clone()

~/Desktop/development/holoviews/holoviews/element/annotation.py in clone(self, *args, **overrides)
72         if 'id' not in settings:
73             settings['id'] = self.id
---> 74         return self.__class__(*args, **settings)
75
76

TypeError: __init__() missing 1 required positional argument: 'spline_points'

# Fixed code
def clone(self, data=None, shared_data=True, new_type=None, *args, **overrides):
    """Clones the object, overriding data and parameters.

    Args:
        data: New data replacing the existing data
        shared_data (bool, optional): Whether to use existing data
        new_type (optional): Type to cast object to
        *args: Additional arguments to pass to constructor
        **overrides: New keyword arguments to pass to constructor

    Returns:
        Cloned Spline
    """
    return Element2D.clone(self, data, shared_data, new_type, *args, **overrides)
# Buggy code
def _glyph_properties(self, *args):
    props = super(BarPlot, self)._glyph_properties(*args)
    del props["width"]
    return props


# Traceback (AttributeError)
heatmap.options()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-3-20a23445f470> in <module>()
----> 1 heatmap.options()

/Users/jbednar/holoviews_git/holoviews/core/dimension.py in options(self, options, backend, clone, **kwargs)
1215
1216         from ..util import opts
-> 1217         expanded = opts.expand_options(options, backend)
1218         return self.opts(expanded, backend, clone)
1219

/Users/jbednar/holoviews_git/holoviews/util/__init__.py in expand_options(cls, options, backend)
122         backend_options = Store.options(backend=backend or current_backend)
123         expanded = {}
--> 124         for objspec, options in options.items():
125             objtype = objspec.split('.')[0]
126             if objtype not in backend_options:

AttributeError: 'NoneType' object has no attribute 'items'

# Fixed code
def _glyph_properties(self, *args):
    props = super(BarPlot, self)._glyph_properties(*args)
    return {k: v for k, v in props.items() if k not in ["width", "bar_width"]}
# Buggy code
def draw_annotation(self, axis, data, opts):
    x, y, text, direction, points, arrowstyle = data
    if self.invert_axes:
        x, y = y, x
    direction = direction.lower()
    arrowprops = dict(
        {"arrowstyle": arrowstyle},
        **{k: opts[k] for k in self._arrow_style_opts if k in opts},
    )
    textopts = {k: opts[k] for k in self._text_style_opts if k in opts}
    if direction in ["v", "^"]:
        xytext = (0, points if direction == "v" else -points)
    elif direction in [">", "<"]:
        xytext = (points if direction == "<" else -points, 0)
    return [
        axis.annotate(
            text,
            xy=(x, y),
            textcoords="offset points",
            xytext=xytext,
            ha="center",
            va="center",
            arrowprops=arrowprops,
            **textopts,
        )
    ]


# Traceback (AttributeError)
heatmap.options()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-3-20a23445f470> in <module>()
----> 1 heatmap.options()

/Users/jbednar/holoviews_git/holoviews/core/dimension.py in options(self, options, backend, clone, **kwargs)
1215
1216         from ..util import opts
-> 1217         expanded = opts.expand_options(options, backend)
1218         return self.opts(expanded, backend, clone)
1219

/Users/jbednar/holoviews_git/holoviews/util/__init__.py in expand_options(cls, options, backend)
122         backend_options = Store.options(backend=backend or current_backend)
123         expanded = {}
--> 124         for objspec, options in options.items():
125             objtype = objspec.split('.')[0]
126             if objtype not in backend_options:

AttributeError: 'NoneType' object has no attribute 'items'

# Fixed code
def draw_annotation(self, axis, data, opts):
    x, y, text, direction, points, arrowstyle = data
    if self.invert_axes:
        x, y = y, x
    direction = direction.lower()
    arrowprops = dict(
        {"arrowstyle": arrowstyle},
        **{k: opts[k] for k in self._arrow_style_opts if k in opts},
    )
    textopts = {k: opts[k] for k in self._text_style_opts if k in opts}
    if direction in ["v", "^"]:
        xytext = (0, points if direction == "v" else -points)
    elif direction in [">", "<"]:
        xytext = (points if direction == "<" else -points, 0)
    if "textsize" in textopts:
        textopts["fontsize"] = textopts.pop("textsize")
    return [
        axis.annotate(
            text,
            xy=(x, y),
            textcoords="offset points",
            xytext=xytext,
            ha="center",
            va="center",
            arrowprops=arrowprops,
            **textopts,
        )
    ]
# Buggy code
def graph_options(self, element, ranges):
    if "steps" in self.interpolation:
        element = interpolate_curve(element, interpolation=self.interpolation)
    opts = super(CurvePlot, self).graph_options(element, ranges)
    opts["mode"] = "lines"
    style = self.style[self.cyclic_index]
    opts["line"] = style
    return opts


# Traceback (AttributeError)
heatmap.options()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-3-20a23445f470> in <module>()
----> 1 heatmap.options()

/Users/jbednar/holoviews_git/holoviews/core/dimension.py in options(self, options, backend, clone, **kwargs)
1215
1216         from ..util import opts
-> 1217         expanded = opts.expand_options(options, backend)
1218         return self.opts(expanded, backend, clone)
1219

/Users/jbednar/holoviews_git/holoviews/util/__init__.py in expand_options(cls, options, backend)
122         backend_options = Store.options(backend=backend or current_backend)
123         expanded = {}
--> 124         for objspec, options in options.items():
125             objtype = objspec.split('.')[0]
126             if objtype not in backend_options:

AttributeError: 'NoneType' object has no attribute 'items'

# Fixed code
def graph_options(self, element, ranges):
    if "steps" in self.interpolation:
        element = interpolate_curve(element, interpolation=self.interpolation)
    opts = super(CurvePlot, self).graph_options(element, ranges)
    opts["mode"] = "lines"
    style = self.style[self.cyclic_index]
    if "line_width" in style:
        style["width"] = style.pop("line_width")
    opts["line"] = style
    return opts
# Buggy code
def get_data(self, element, ranges):
    neg_error = element.dimension_values(2)
    pos_idx = 3 if len(element.dimensions()) > 3 else 2
    pos_error = element.dimension_values(pos_idx)

    style = self.style[self.cyclic_index]
    error_y = dict(
        type="data", array=pos_error, arrayminus=neg_error, visible=True, **style
    )
    return (), dict(
        x=element.dimension_values(0), y=element.dimension_values(1), error_y=error_y
    )


# Traceback (AttributeError)
heatmap.options()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-3-20a23445f470> in <module>()
----> 1 heatmap.options()

/Users/jbednar/holoviews_git/holoviews/core/dimension.py in options(self, options, backend, clone, **kwargs)
1215
1216         from ..util import opts
-> 1217         expanded = opts.expand_options(options, backend)
1218         return self.opts(expanded, backend, clone)
1219

/Users/jbednar/holoviews_git/holoviews/util/__init__.py in expand_options(cls, options, backend)
122         backend_options = Store.options(backend=backend or current_backend)
123         expanded = {}
--> 124         for objspec, options in options.items():
125             objtype = objspec.split('.')[0]
126             if objtype not in backend_options:

AttributeError: 'NoneType' object has no attribute 'items'

# Fixed code
def get_data(self, element, ranges):
    neg_error = element.dimension_values(2)
    pos_idx = 3 if len(element.dimensions()) > 3 else 2
    pos_error = element.dimension_values(pos_idx)

    style = self.style[self.cyclic_index]
    if "line_width" in style:
        style["width"] = style.pop("line_width")
    error_y = dict(
        type="data", array=pos_error, arrayminus=neg_error, visible=True, **style
    )
    return (), dict(
        x=element.dimension_values(0), y=element.dimension_values(1), error_y=error_y
    )
# Buggy code
def _compute_filename(self, obj, info, filename=None):
    if filename is None:
        hashfn = sha256()
        obj_str = "None" if obj is None else self.object_formatter(obj)
        dimensions = self._dim_formatter(obj)
        dimensions = dimensions if dimensions else ""

        hashfn.update(obj_str.encode("utf-8"))
        format_values = {
            "timestamp": "{timestamp}",
            "dimensions": dimensions,
            "group": getattr(obj, "group", "no-group"),
            "label": getattr(obj, "label", "no-label"),
            "type": obj.__class__.__name__,
            "obj": obj_str,
            "SHA": hashfn.hexdigest(),
        }

        filename = self._format(self.filename_formatter, dict(info, **format_values))

    filename = self._normalize_name(filename)
    ext = info.get("file-ext", "")
    (unique_key, ext) = self._unique_name(filename, ext, self._files.keys(), force=True)
    return (unique_key, ext)


# Traceback (IOError)
The last call to holoviews.archive.export was unsuccessful.

Traceback (most recent call last):
File "/home/tenner/src/holoviews/holoviews/ipython/archive.py", line 273, in _export_with_html
info={'notebook':self.notebook_name})
File "/home/tenner/src/holoviews/holoviews/core/io.py", line 807, in export
self._directory_archive(export_name, files, root)
File "/home/tenner/src/holoviews/holoviews/core/io.py", line 747, in _directory_archive
with open(fpath, 'wb') as f:
IOError: [Errno 2] No such file or directory: '/media/data2/tenner/data/ipython-notebooks/Tests/Test_holoviews_export/Curve-./test.svg'

# Fixed code
def _compute_filename(self, obj, info, filename=None):
    if filename is None:
        hashfn = sha256()
        obj_str = "None" if obj is None else self.object_formatter(obj)
        dimensions = self._dim_formatter(obj)
        dimensions = dimensions if dimensions else ""

        hashfn.update(obj_str.encode("utf-8"))
        label = sanitizer(getattr(obj, "label", "no-label"))
        group = sanitizer(getattr(obj, "group", "no-group"))
        format_values = {
            "timestamp": "{timestamp}",
            "dimensions": dimensions,
            "group": group,
            "label": label,
            "type": obj.__class__.__name__,
            "obj": sanitizer(obj_str),
            "SHA": hashfn.hexdigest(),
        }

        filename = self._format(self.filename_formatter, dict(info, **format_values))

    filename = self._normalize_name(filename)
    ext = info.get("file-ext", "")
    (unique_key, ext) = self._unique_name(filename, ext, self._files.keys(), force=True)
    return (unique_key, ext)
# Buggy code
def _unique_name(self, basename, ext, existing, force=False):
    """
    Find a unique basename for a new file/key where existing is
    either a list of (basename, ext) pairs or an absolute path to
    a directory.

    By default, uniqueness is enforced dependning on the state of
    the unique_name parameter (for export names). If force is
    True, this parameter is ignored and uniqueness is guaranteed.
    """
    skip = False if force else (not self.unique_name)
    if skip:
        return (basename, ext)
    ext = "" if ext is None else ext
    if isinstance(existing, str):
        split = [os.path.splitext(el) for el in os.listdir(os.path.abspath(existing))]
        existing = [(n, ex if not ex else ex[1:]) for (n, ex) in split]
    new_name, counter = basename, 1
    while (new_name, ext) in existing:
        new_name = basename + "-" + str(counter)
        counter += 1
    return (new_name, ext)


# Traceback (IOError)
The last call to holoviews.archive.export was unsuccessful.

Traceback (most recent call last):
File "/home/tenner/src/holoviews/holoviews/ipython/archive.py", line 273, in _export_with_html
info={'notebook':self.notebook_name})
File "/home/tenner/src/holoviews/holoviews/core/io.py", line 807, in export
self._directory_archive(export_name, files, root)
File "/home/tenner/src/holoviews/holoviews/core/io.py", line 747, in _directory_archive
with open(fpath, 'wb') as f:
IOError: [Errno 2] No such file or directory: '/media/data2/tenner/data/ipython-notebooks/Tests/Test_holoviews_export/Curve-./test.svg'

# Fixed code
def _unique_name(self, basename, ext, existing, force=False):
    """
    Find a unique basename for a new file/key where existing is
    either a list of (basename, ext) pairs or an absolute path to
    a directory.

    By default, uniqueness is enforced dependning on the state of
    the unique_name parameter (for export names). If force is
    True, this parameter is ignored and uniqueness is guaranteed.
    """
    skip = False if force else (not self.unique_name)
    if skip:
        return (basename, ext)
    ext = "" if ext is None else ext
    if isinstance(existing, str):
        split = [os.path.splitext(el) for el in os.listdir(os.path.abspath(existing))]
        existing = [(n, ex if not ex else ex[1:]) for (n, ex) in split]
    new_name, counter = basename, 1
    while (new_name, ext) in existing:
        new_name = basename + "-" + str(counter)
        counter += 1
    return (sanitizer(new_name), ext)
# Buggy code
def save(
    self_or_cls, obj, basename, fmt="auto", key={}, info={}, options=None, **kwargs
):
    """
    Save a HoloViews object to file, either using an explicitly
    supplied format or to the appropriate default.
    """
    if info or key:
        raise Exception("MPLRenderer does not support saving metadata to file.")

    with StoreOptions.options(obj, options, **kwargs):
        plot = self_or_cls.get_plot(obj)

    if (fmt in list(self_or_cls.widgets.keys()) + ["auto"]) and len(plot) > 1:
        with StoreOptions.options(obj, options, **kwargs):
            self_or_cls.export_widgets(plot, basename + ".html", fmt)
        return

    with StoreOptions.options(obj, options, **kwargs):
        rendered = self_or_cls(plot, fmt)
    if rendered is None:
        return
    (data, info) = rendered
    if isinstance(basename, BytesIO):
        basename.write(data)
        basename.seek(0)
    else:
        encoded = self_or_cls.encode(rendered)
        filename = "%s.%s" % (basename, info["file-ext"])
        with open(filename, "wb") as f:
            f.write(encoded)


# Traceback (TypeError)
renderer.save(test, 'example_I')
Traceback (most recent call last):

File "<ipython-input-19-7e2a8a193726>", line 2, in <module>
renderer.save(test, 'example_I')

File "C:\Work\Anaconda\lib\site-packages\holoviews\plotting\renderer.py", line 467, in save
f.write(encoded)

TypeError: a bytes-like object is required, not 'str'

# Fixed code
def save(
    self_or_cls, obj, basename, fmt="auto", key={}, info={}, options=None, **kwargs
):
    """
    Save a HoloViews object to file, either using an explicitly
    supplied format or to the appropriate default.
    """
    if info or key:
        raise Exception("MPLRenderer does not support saving metadata to file.")

    with StoreOptions.options(obj, options, **kwargs):
        plot = self_or_cls.get_plot(obj)

    if (fmt in list(self_or_cls.widgets.keys()) + ["auto"]) and len(plot) > 1:
        with StoreOptions.options(obj, options, **kwargs):
            self_or_cls.export_widgets(plot, basename + ".html", fmt)
        return

    with StoreOptions.options(obj, options, **kwargs):
        rendered = self_or_cls(plot, fmt)
    if rendered is None:
        return
    (data, info) = rendered
    encoded = self_or_cls.encode(rendered)
    if isinstance(basename, BytesIO):
        basename.write(encoded)
        basename.seek(0)
    else:
        filename = "%s.%s" % (basename, info["file-ext"])
        with open(filename, "wb") as f:
            f.write(encoded)
# Buggy code
def _adjust_cbar(self, cbar, label, dim):
    noalpha = math.floor(self.style[self.cyclic_index].get("alpha", 1)) == 1
    if cbar.solids and noalpha:
        cbar.solids.set_edgecolor("face")
    cbar.set_label(label)
    if isinstance(self.cbar_ticks, ticker.Locator):
        cbar.set_major_locator(self.cbar_ticks)
    elif self.cbar_ticks == 0:
        cbar.set_ticks([])
    elif isinstance(self.cbar_ticks, int):
        locator = ticker.MaxNLocator(self.cbar_ticks)
        cbar.set_major_locator(locator)
    elif isinstance(self.cbar_ticks, list):
        if all(isinstance(t, tuple) for t in self.cbar_ticks):
            ticks, labels = zip(*self.cbar_ticks)
        else:
            ticks, labels = zip(*[(t, dim.pprint_value(t)) for t in self.cbar_ticks])
        cbar.set_ticks(ticks)
        cbar.set_ticklabels(labels)


# Traceback (AttributeError)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
/home/tenner/.local/lib/python2.7/site-packages/IPython/core/formatters.pyc in __call__(self, obj)
337                 pass
338             else:
--> 339                 return printer(obj)
340             # Finally look for special method names
341             method = _safe_get_formatter_method(obj, self.print_method)

/home/tenner/src/holoviews/holoviews/ipython/display_hooks.pyc in pprint_display(obj)
222     if not ip.display_formatter.formatters['text/plain'].pprint:
223         return None
--> 224     return display(obj, raw=True)
225
226

/home/tenner/src/holoviews/holoviews/ipython/display_hooks.pyc in display(obj, raw, **kwargs)
204         html = grid_display(obj)
205     elif isinstance(obj, (CompositeOverlay, ViewableElement)):
--> 206         html = element_display(obj)
207     elif isinstance(obj, (Layout, NdLayout, AdjointLayout)):
208         html = layout_display(obj)

/home/tenner/src/holoviews/holoviews/ipython/display_hooks.pyc in wrapped(element)
136                        'Call ipython.show_traceback() for details')
137                 return msg % e
--> 138             raise e
139
140     return wrapped

AttributeError: Colorbar instance has no attribute 'set_major_locator'

# Fixed code
def _adjust_cbar(self, cbar, label, dim):
    noalpha = math.floor(self.style[self.cyclic_index].get("alpha", 1)) == 1
    if cbar.solids and noalpha:
        cbar.solids.set_edgecolor("face")
    cbar.set_label(label)
    if isinstance(self.cbar_ticks, ticker.Locator):
        cbar.ax.yaxis.set_major_locator(self.cbar_ticks)
    elif self.cbar_ticks == 0:
        cbar.set_ticks([])
    elif isinstance(self.cbar_ticks, int):
        locator = ticker.MaxNLocator(self.cbar_ticks)
        cbar.ax.yaxis.set_major_locator(locator)
    elif isinstance(self.cbar_ticks, list):
        if all(isinstance(t, tuple) for t in self.cbar_ticks):
            ticks, labels = zip(*self.cbar_ticks)
        else:
            ticks, labels = zip(*[(t, dim.pprint_value(t)) for t in self.cbar_ticks])
        cbar.set_ticks(ticks)
        cbar.set_ticklabels(labels)
# Buggy code
def _init_plot(self, key, plots, ranges=None):
    """
    Initializes Bokeh figure to draw Element into and sets basic
    figure and axis attributes including axes types, labels,
    titles and plot height and width.
    """
    element = self._get_frame(key)
    subplots = list(self.subplots.values()) if self.subplots else []

    axis_types, labels, plot_ranges = self._axes_props(plots, subplots, element, ranges)
    xlabel, ylabel, zlabel = labels
    x_axis_type, y_axis_type = axis_types
    tools = self._init_tools(element)
    properties = dict(plot_ranges)
    properties["x_axis_label"] = xlabel if "x" in self.show_labels else " "
    properties["y_axis_label"] = ylabel if "y" in self.show_labels else " "

    major, minor = [int(v) for v in bokeh.__version__.split(".")][0:2]
    if major > 0 or minor > "10":
        properties["webgl"] = True
    return bokeh.plotting.figure(
        x_axis_type=x_axis_type, y_axis_type=y_axis_type, tools=tools, **properties
    )


# Traceback (ValueError)
In [1]:


import pandas as pd
import holoviews as hv
​
%reload_ext holoviews.ipython
%output backend='bokeh'
HoloViewsJS successfully loaded.
WARNING:root:Warning: Some elements and plot options are not supported by Bokeh library and backend.
BokehJS successfully loaded.
In [2]:

from holoviews.ipython import display_hooks
display_hooks.ABBREVIATE_TRACEBACKS=False
hv.Points([[0,2],[3,7]])
Traceback (most recent call last):
File "holoviews/ipython/display_hooks.py", line 162, in wrapped
widget_mode = widget_mode)
File "holoviews/ipython/display_hooks.py", line 197, in element_display
return render_plot(element_plot, False)
File "holoviews/ipython/display_hooks.py", line 137, in render_plot
plot.update(0)
File "holoviews/plotting/plot.py", line 381, in update
return self.initialize_plot()
File "holoviews/plotting/bokeh/element.py", line 408, in initialize_plot
plot = self._init_plot(key, ranges=ranges, plots=plots)
File "holoviews/plotting/bokeh/element.py", line 247, in _init_plot
major, minor = [int(v) for v  in bokeh.__version__.split('.')][0:2]
ValueError: invalid literal for int() with base 10: '0-351-g12f56e0-dirty'
Out[2]:
:Points   [x,y]

# Fixed code
def _init_plot(self, key, plots, ranges=None):
    """
    Initializes Bokeh figure to draw Element into and sets basic
    figure and axis attributes including axes types, labels,
    titles and plot height and width.
    """
    element = self._get_frame(key)
    subplots = list(self.subplots.values()) if self.subplots else []

    axis_types, labels, plot_ranges = self._axes_props(plots, subplots, element, ranges)
    xlabel, ylabel, zlabel = labels
    x_axis_type, y_axis_type = axis_types
    tools = self._init_tools(element)
    properties = dict(plot_ranges)
    properties["x_axis_label"] = xlabel if "x" in self.show_labels else " "
    properties["y_axis_label"] = ylabel if "y" in self.show_labels else " "

    major, minor = [int(v) for v in bokeh.__version__.split(".")[0:2]]
    if major > 0 or minor > "10":
        properties["webgl"] = True
    return bokeh.plotting.figure(
        x_axis_type=x_axis_type, y_axis_type=y_axis_type, tools=tools, **properties
    )
# Buggy code
def from_values(cls, val):
    """
    Returns a Layout given a list (or tuple) of viewable
    elements or just a single viewable element.
    """
    collection = isinstance(val, (list, tuple))
    if type(val) is cls:
        return val
    elif collection and len(val) > 1:
        return cls._from_values(val)
    elif collection:
        val = val[0]
    return cls(
        items=[
            (
                (
                    sanitize_identifier(val.group),
                    sanitize_identifier(val.label if val.label else "I"),
                ),
                val,
            )
        ]
    )


# Traceback (ValueError)
Traceback (most recent call last):
File "/home/bnijholt/python/env_stable/lib/python2.7/site-packages/holoviews/ipython/display_hooks.py", line 215, in wrapped
**kwargs)
File "/home/bnijholt/python/env_stable/lib/python2.7/site-packages/holoviews/ipython/display_hooks.py", line 277, in layout_display
layoutplot = LayoutPlot(layout, **opts(layout, size))
File "/home/bnijholt/python/env_stable/lib/python2.7/site-packages/holoviews/plotting/plot.py", line 937, in __init__
raise ValueError("Cannot display empty layout")
ValueError: Cannot display empty layout
Out[346]:
:Layout

# Fixed code
def from_values(cls, val):
    """
    Returns a Layout given a list (or tuple) of viewable
    elements or just a single viewable element.
    """
    collection = isinstance(val, (list, tuple))
    if type(val) is cls:
        return val
    elif collection and len(val) > 1:
        return cls._from_values(val)
    elif collection:
        val = val[0]
    group = sanitize_identifier(val.group)
    group = "".join([group[0].upper(), group[1:]])
    label = sanitize_identifier(val.label if val.label else "I")
    label = "".join([label[0].upper(), label[1:]])
    return cls(items=[((group, label), val)])
# Buggy code
def _plot_figure(self, idx):
    from .display_hooks import display_figure

    fig = self.plot[idx]
    if OutputMagic.options["backend"] == "d3":
        import mpld3

        mpld3.plugins.connect(fig, mpld3.plugins.MousePosition(fontsize=14))
        return mpld3.fig_to_dict(fig)
    return display_figure(fig)


# Traceback (RuntimeError)
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/holoviews/ipython/display_hooks.py", line 203, in wrapped
**kwargs)
File "/usr/local/lib/python2.7/dist-packages/holoviews/ipython/display_hooks.py", line 233, in element_display
**opts(element, get_plot_size(element, size)))()
File "/usr/local/lib/python2.7/dist-packages/holoviews/plotting/raster.py", line 34, in __init__
super(RasterPlot, self).__init__(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/holoviews/plotting/element.py", line 132, in __init__
uniform=uniform, **dict(params, **plot_opts))
File "/usr/local/lib/python2.7/dist-packages/holoviews/plotting/plot.py", line 114, in __init__
self.handles['axis'] = self._init_axis(axis)
File "/usr/local/lib/python2.7/dist-packages/holoviews/plotting/plot.py", line 248, in _init_axis
fig = plt.figure()
File "/usr/local/lib/python2.7/dist-packages/matplotlib/pyplot.py", line 435, in figure
**kwargs)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/backends/backend_qt4agg.py", line 47, in new_figure_manager
return new_figure_manager_given_figure(num, thisFig)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/backends/backend_qt4agg.py", line 54, in new_figure_manager_given_figure
canvas = FigureCanvasQTAgg(figure)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/backends/backend_qt4agg.py", line 72, in __init__
FigureCanvasQT.__init__(self, figure)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/backends/backend_qt4.py", line 68, in __init__
_create_qApp()
File "/usr/local/lib/python2.7/dist-packages/matplotlib/backends/backend_qt5.py", line 138, in _create_qApp
raise RuntimeError('Invalid DISPLAY variable')
RuntimeError: Invalid DISPLAY variable

# Fixed code
def _plot_figure(self, idx):
    from .display_hooks import display_figure

    fig = self.plot[idx]
    if OutputMagic.options["backend"] == "d3":
        import mpld3

        mpld3.plugins.connect(fig, mpld3.plugins.MousePosition(fontsize=14))
        return mpld3.fig_to_dict(fig)
    return display_figure(fig, allow_nbagg=False)
# Buggy code
async def default_disable(self, cog_name: str):
    """
    Sets the default for a cog as disabled.

    Parameters
    ----------
    cog_name: str
        This should be the cog's qualified name, not necessarily the classname
    """
    await self._config.custom("COG_DISABLE_SETTINGS", cog_name, 0).disabled.set(True)
    del self._disable_map[cog_name]


# Traceback (KeyError)
Exception in command 'command defaultdisablecog'
Traceback (most recent call last):
File "C:\Users\Bobloy\Documents\GitHub\Red-DiscordBot\.venv\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\Bobloy\Documents\GitHub\Red-DiscordBot\redbot\core\core_commands.py", line 3732, in command_default_disable_cog
await self.bot._disabled_cog_cache.default_disable(cogname)
File "C:\Users\Bobloy\Documents\GitHub\Red-DiscordBot\redbot\core\settings_caches.py", line 440, in default_disable
del self._disable_map[cog_name]
KeyError: 'Economy'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "C:\Users\Bobloy\Documents\GitHub\Red-DiscordBot\.venv\lib\site-packages\discord\ext\commands\bot.py", line 903, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Bobloy\Documents\GitHub\Red-DiscordBot\redbot\core\commands\commands.py", line 825, in invoke
await super().invoke(ctx)
File "C:\Users\Bobloy\Documents\GitHub\Red-DiscordBot\.venv\lib\site-packages\discord\ext\commands\core.py", line 1329, in invoke
await ctx.invoked_subcommand.invoke(ctx)
File "C:\Users\Bobloy\Documents\GitHub\Red-DiscordBot\.venv\lib\site-packages\discord\ext\commands\core.py", line 859, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Bobloy\Documents\GitHub\Red-DiscordBot\.venv\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: 'Economy'

# Fixed code
async def default_disable(self, cog_name: str):
    """
    Sets the default for a cog as disabled.

    Parameters
    ----------
    cog_name: str
        This should be the cog's qualified name, not necessarily the classname
    """
    await self._config.custom("COG_DISABLE_SETTINGS", cog_name, 0).disabled.set(True)
    self._disable_map.pop(cog_name, None)
# Buggy code
async def default_enable(self, cog_name: str):
    """
    Sets the default for a cog as enabled.

    Parameters
    ----------
    cog_name: str
        This should be the cog's qualified name, not necessarily the classname
    """
    await self._config.custom("COG_DISABLE_SETTINGS", cog_name, 0).disabled.clear()
    del self._disable_map[cog_name]


# Traceback (KeyError)
Exception in command 'command defaultdisablecog'
Traceback (most recent call last):
File "C:\Users\Bobloy\Documents\GitHub\Red-DiscordBot\.venv\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\Bobloy\Documents\GitHub\Red-DiscordBot\redbot\core\core_commands.py", line 3732, in command_default_disable_cog
await self.bot._disabled_cog_cache.default_disable(cogname)
File "C:\Users\Bobloy\Documents\GitHub\Red-DiscordBot\redbot\core\settings_caches.py", line 440, in default_disable
del self._disable_map[cog_name]
KeyError: 'Economy'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "C:\Users\Bobloy\Documents\GitHub\Red-DiscordBot\.venv\lib\site-packages\discord\ext\commands\bot.py", line 903, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Bobloy\Documents\GitHub\Red-DiscordBot\redbot\core\commands\commands.py", line 825, in invoke
await super().invoke(ctx)
File "C:\Users\Bobloy\Documents\GitHub\Red-DiscordBot\.venv\lib\site-packages\discord\ext\commands\core.py", line 1329, in invoke
await ctx.invoked_subcommand.invoke(ctx)
File "C:\Users\Bobloy\Documents\GitHub\Red-DiscordBot\.venv\lib\site-packages\discord\ext\commands\core.py", line 859, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Bobloy\Documents\GitHub\Red-DiscordBot\.venv\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: 'Economy'

# Fixed code
async def default_enable(self, cog_name: str):
    """
    Sets the default for a cog as enabled.

    Parameters
    ----------
    cog_name: str
        This should be the cog's qualified name, not necessarily the classname
    """
    await self._config.custom("COG_DISABLE_SETTINGS", cog_name, 0).disabled.clear()
    self._disable_map.pop(cog_name, None)
# Buggy code
def _ensure_path_obj(path: Union[Path, str]) -> Path:
    """Guarantee an object will be a path object.

    Parameters
    ----------
    path : `pathlib.Path` or `str`

    Returns
    -------
    pathlib.Path

    """
    try:
        path.exists()
    except AttributeError:
        path = Path(path)
    return path


# Traceback (ValueError)
[23/04/2019 21:40] ERROR events on_command_error 207: Exception in command 'removepath'
Traceback (most recent call last):
File "<my path to red>/RedBotV3/.venv/lib/python3.6/site-packages/discord/ext/commands/core.py", line 79, in wrapped
ret = await coro(*args, **kwargs)
File "<my path to red>/RedBotV3/.venv/lib/python3.6/site-packages/redbot/core/cog_manager.py", line 372, in removepath
await ctx.bot.cog_mgr.remove_path(to_remove)
File "<my path to red>/RedBotV3/.venv/lib/python3.6/site-packages/redbot/core/cog_manager.py", line 182, in remove_path
paths.remove(path)
ValueError: list.remove(x): x not in list

# Fixed code
def _ensure_path_obj(path: Union[Path, str]) -> Path:
    """Guarantee an object will be a path object.

    Parameters
    ----------
    path : `pathlib.Path` or `str`

    Returns
    -------
    pathlib.Path

    """
    return Path(path)
# Buggy code
async def remove_path(self, path: Union[Path, str]) -> None:
    """Remove a path from the current paths list.

    Parameters
    ----------
    path : `pathlib.Path` or `str`
        Path to remove.

    """
    path = self._ensure_path_obj(path).resolve()
    paths = await self.user_defined_paths()

    paths.remove(path)
    await self.set_paths(paths)


# Traceback (ValueError)
[23/04/2019 21:40] ERROR events on_command_error 207: Exception in command 'removepath'
Traceback (most recent call last):
File "<my path to red>/RedBotV3/.venv/lib/python3.6/site-packages/discord/ext/commands/core.py", line 79, in wrapped
ret = await coro(*args, **kwargs)
File "<my path to red>/RedBotV3/.venv/lib/python3.6/site-packages/redbot/core/cog_manager.py", line 372, in removepath
await ctx.bot.cog_mgr.remove_path(to_remove)
File "<my path to red>/RedBotV3/.venv/lib/python3.6/site-packages/redbot/core/cog_manager.py", line 182, in remove_path
paths.remove(path)
ValueError: list.remove(x): x not in list

# Fixed code
async def remove_path(self, path: Union[Path, str]) -> None:
    """Remove a path from the current paths list.

    Parameters
    ----------
    path : `pathlib.Path` or `str`
        Path to remove.

    """
    path = self._ensure_path_obj(path)
    paths = await self.user_defined_paths()

    paths.remove(path)
    await self.set_paths(paths)
# Buggy code
def setup(bot: commands.Bot):
    cog = Audio(bot)
    bot.add_cog(cog)


# Traceback (AttributeError)
Traceback (most recent call last):
File "/home/bot/botenv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 83, in wrapped
ret = await coro(*args, **kwargs)
File "/home/bot/botenv/lib/python3.8/site-packages/redbot/cogs/audio/audio.py", line 4937, in _playlist_list
playlists = await get_all_playlist(scope, self.bot, guild, author, specified_user)
File "/home/bot/botenv/lib/python3.8/site-packages/redbot/cogs/audio/playlists.py", line 475, in get_all_playlist
scope_standard, scope_id = _prepare_config_scope(scope, author, guild)
File "/home/bot/botenv/lib/python3.8/site-packages/redbot/cogs/audio/playlists.py", line 86, in _prepare_config_scope
scope = standardize_scope(scope)
File "/home/bot/botenv/lib/python3.8/site-packages/redbot/cogs/audio/playlists.py", line 62, in standardize_scope
scope = scope.upper()
AttributeError: 'NoneType' object has no attribute 'upper'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "/home/bot/botenv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 892, in invoke
await ctx.command.invoke(ctx)
File "/home/bot/botenv/lib/python3.8/site-packages/redbot/core/commands/commands.py", line 799, in invoke
await super().invoke(ctx)
File "/home/bot/botenv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 1234, in invoke
await ctx.invoked_subcommand.invoke(ctx)
File "/home/bot/botenv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 797, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/bot/botenv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 92, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'upper'

# Fixed code
def setup(bot: Red):
    cog = Audio(bot)
    bot.add_cog(cog)
    cog.start_up_task()