gurudesh/pytracebugs huggingface dataset:
# Buggy code
def _update_monospace_fonts():
    """Update all fonts if fonts.monospace was set."""
    configtypes.Font.monospace_fonts = config.val.fonts.monospace
    for name, opt in configdata.DATA.items():
        if name == "fonts.monospace":
            continue
        elif not isinstance(opt.typ, configtypes.Font):
            continue
        elif not config.instance.get_obj(name).endswith(" monospace"):
            continue

        config.instance.changed.emit(name)


# Traceback (AttributeError)
Traceback (most recent call last):
File "/home/florian/proj/qutebrowser/git/qutebrowser/config/config.py", line 108, in wrapper
return func()
File "/home/florian/proj/qutebrowser/git/qutebrowser/config/configinit.py", line 107, in _update_monospace_fonts
elif not config.instance.get_obj(name).endswith(' monospace'):
AttributeError: 'NoneType' object has no attribute 'endswith'

# Fixed code
def _update_monospace_fonts():
    """Update all fonts if fonts.monospace was set."""
    configtypes.Font.monospace_fonts = config.val.fonts.monospace
    for name, opt in configdata.DATA.items():
        if name == "fonts.monospace":
            continue
        elif not isinstance(opt.typ, configtypes.Font):
            continue

        value = config.instance.get_obj(name)
        if value is None or not value.endswith(" monospace"):
            continue

        config.instance.changed.emit(name)
# Buggy code
def import_txt(self):
    """Import a history text file into sqlite if it exists.

    In older versions of qutebrowser, history was stored in a text format.
    This converts that file into the new sqlite format and moves it to a
    backup location.
    """
    path = os.path.join(standarddir.data(), "history")
    if not os.path.isfile(path):
        return

    def action():
        with debug.log_time(log.init, "Import old history file to sqlite"):
            try:
                self._read(path)
            except ValueError as ex:
                message.error("Failed to import history: {}".format(ex))
            else:
                bakpath = path + ".bak"
                message.info(
                    "History import complete. Moving {} to {}".format(path, bakpath)
                )
                os.rename(path, bakpath)

    # delay to give message time to appear before locking down for import
    message.info("Converting {} to sqlite...".format(path))
    QTimer.singleShot(100, action)


# Traceback (FileExistsError)
08:30:34 INFO     message    message:info:86 History import complete. Moving C:\Users\Florian\AppData\Local\qutebrowser\data\history to C:\Users\Florian\AppData\Local\qutebrowser\data\history.bak
08:30:34 DEBUG    misc       mainwindow:_update_overlay_geometry:285 new geometry for <qutebrowser.mainwindow.messageview.MessageView object at 0x000002666B1B2798>: PyQt5.QtCore.QRect(0, 20, 643, -1)
08:30:34 DEBUG    init       debug:__exit__:264 Import old history file to sqlite took 0.039671 seconds.
08:30:34 ERROR    misc       crashsignal:exception_hook:210 Uncaught exception
Traceback (most recent call last):
File "C:\Users\Florian\qutebrowser\qutebrowser\browser\history.py", line 253, in action
os.rename(path, bakpath)
FileExistsError: [WinError 183] Cannot create a file when that file already exists: 'C:\\Users\\Florian\\AppData\\Local\\qutebrowser\\data\\history' -> 'C:\\Users\\Florian\\AppData\\Local\\qutebrowser\\data\\history.bak'

# Fixed code
def import_txt(self):
    """Import a history text file into sqlite if it exists.

    In older versions of qutebrowser, history was stored in a text format.
    This converts that file into the new sqlite format and moves it to a
    backup location.
    """
    path = os.path.join(standarddir.data(), "history")
    if not os.path.isfile(path):
        return

    def action():
        with debug.log_time(log.init, "Import old history file to sqlite"):
            try:
                self._read(path)
            except ValueError as ex:
                message.error("Failed to import history: {}".format(ex))
            else:
                self._write_backup(path)

    # delay to give message time to appear before locking down for import
    message.info("Converting {} to sqlite...".format(path))
    QTimer.singleShot(100, action)
# Buggy code
def action():
    with debug.log_time(log.init, "Import old history file to sqlite"):
        try:
            self._read(path)
        except ValueError as ex:
            message.error("Failed to import history: {}".format(ex))
        else:
            bakpath = path + ".bak"
            message.info(
                "History import complete. Moving {} to {}".format(path, bakpath)
            )
            os.rename(path, bakpath)


# Traceback (FileExistsError)
08:30:34 INFO     message    message:info:86 History import complete. Moving C:\Users\Florian\AppData\Local\qutebrowser\data\history to C:\Users\Florian\AppData\Local\qutebrowser\data\history.bak
08:30:34 DEBUG    misc       mainwindow:_update_overlay_geometry:285 new geometry for <qutebrowser.mainwindow.messageview.MessageView object at 0x000002666B1B2798>: PyQt5.QtCore.QRect(0, 20, 643, -1)
08:30:34 DEBUG    init       debug:__exit__:264 Import old history file to sqlite took 0.039671 seconds.
08:30:34 ERROR    misc       crashsignal:exception_hook:210 Uncaught exception
Traceback (most recent call last):
File "C:\Users\Florian\qutebrowser\qutebrowser\browser\history.py", line 253, in action
os.rename(path, bakpath)
FileExistsError: [WinError 183] Cannot create a file when that file already exists: 'C:\\Users\\Florian\\AppData\\Local\\qutebrowser\\data\\history' -> 'C:\\Users\\Florian\\AppData\\Local\\qutebrowser\\data\\history.bak'

# Fixed code
def action():
    with debug.log_time(log.init, "Import old history file to sqlite"):
        try:
            self._read(path)
        except ValueError as ex:
            message.error("Failed to import history: {}".format(ex))
        else:
            self._write_backup(path)
# Buggy code
def bind(key):
    """A CompletionModel filled with all bindable commands and descriptions.

    Args:
        key: the key being bound.
    """
    model = completionmodel.CompletionModel(column_widths=(20, 60, 20))
    cmd_name = objreg.get("key-config").get_bindings_for("normal").get(key)

    if cmd_name:
        cmd = cmdutils.cmd_dict.get(cmd_name)
        data = [(cmd_name, cmd.desc, key)]
        model.add_category(listcategory.ListCategory("Current", data))

    cmdlist = _get_cmd_completions(include_hidden=True, include_aliases=True)
    model.add_category(listcategory.ListCategory("Commands", cmdlist))
    return model


# Traceback (AttributeError)
13:01:17 DEBUG    completion completer:schedule_completion_update:192 Scheduling completion update.
13:01:17 DEBUG    completion completer:schedule_completion_update:189 Ignoring update because there were no changes.
13:01:17 DEBUG    completion completer:_partition:132 partitioning ['bind', ' ,x', ' '] around position 8
13:01:17 DEBUG    completion completer:_partition:144 partitioned: ['bind', ',x'] '' []
13:01:17 DEBUG    completion completer:_update_completion:220 Updating completion: ['bind', ',x']  []
13:01:17 DEBUG    completion completer:_get_new_completion:80 Before removing flags: ['bind', ',x']
13:01:17 DEBUG    completion completer:_get_new_completion:82 After removing flags: ['bind', ',x']
13:01:17 DEBUG    completion debug:__exit__:264 Starting bind completion took 0.000124 seconds.
13:01:17 ERROR    misc       crashsignal:exception_hook:210 Uncaught exception
Traceback (most recent call last):
File "/home/florian/proj/qutebrowser/git/qutebrowser/completion/completer.py", line 236, in _update_completion
model = func(*args)
File "/home/florian/proj/qutebrowser/git/qutebrowser/completion/models/miscmodels.py", line 133, in bind
data = [(cmd_name, cmd.desc, key)]
AttributeError: 'NoneType' object has no attribute 'desc'

# Fixed code
def bind(key):
    """A CompletionModel filled with all bindable commands and descriptions.

    Args:
        key: the key being bound.
    """
    model = completionmodel.CompletionModel(column_widths=(20, 60, 20))
    cmd_text = objreg.get("key-config").get_bindings_for("normal").get(key)

    if cmd_text:
        cmd_name = cmd_text.split(" ")[0]
        cmd = cmdutils.cmd_dict.get(cmd_name)
        data = [(cmd_text, cmd.desc, key)]
        model.add_category(listcategory.ListCategory("Current", data))

    cmdlist = _get_cmd_completions(include_hidden=True, include_aliases=True)
    model.add_category(listcategory.ListCategory("Commands", cmdlist))
    return model
# Buggy code
def _resize_columns(self):
    """Resize the completion columns based on column_widths."""
    width = self.size().width()
    column_widths = self.model().column_widths
    pixel_widths = [(width * perc // 100) for perc in column_widths]

    if self.verticalScrollBar().isVisible():
        delta = self.style().pixelMetric(QStyle.PM_ScrollBarExtent) + 5
        if pixel_widths[-1] > delta:
            pixel_widths[-1] -= delta
        else:
            pixel_widths[-2] -= delta
    for i, w in enumerate(pixel_widths):
        assert w >= 0, i
        self.setColumnWidth(i, w)


# Traceback (AttributeError)
[...]
17:18:41 DEBUG    webview    tabbedbrowser:on_title_changed:561 Changing title for idx 0 to 'qutebrowser quickstart | qutebrowser'
17:18:41 ERROR    misc       crashsignal:exception_hook:210 Uncaught exception
Traceback (most recent call last):
File "/usr/lib/python3.6/site-packages/qutebrowser/completion/completionwidget.py", line 359, in resizeEvent
self._resize_columns()
File "/usr/lib/python3.6/site-packages/qutebrowser/completion/completionwidget.py", line 154, in _resize_columns
column_widths = self.model().column_widths
AttributeError: 'NoneType' object has no attribute 'column_widths'

# Fixed code
def _resize_columns(self):
    """Resize the completion columns based on column_widths."""
    if self.model() is None:
        return
    width = self.size().width()
    column_widths = self.model().column_widths
    pixel_widths = [(width * perc // 100) for perc in column_widths]

    if self.verticalScrollBar().isVisible():
        delta = self.style().pixelMetric(QStyle.PM_ScrollBarExtent) + 5
        if pixel_widths[-1] > delta:
            pixel_widths[-1] -= delta
        else:
            pixel_widths[-2] -= delta
    for i, w in enumerate(pixel_widths):
        assert w >= 0, i
        self.setColumnWidth(i, w)
# Buggy code
def read_direct(self, dest, source_sel=None, dest_sel=None):
    """Read data directly from HDF5 into an existing NumPy array.

    The destination array must be C-contiguous and writable.
    Selections must be the output of numpy.s_[<args>].

    Broadcasting is supported for simple indexing.
    """
    with phil:
        if self._is_empty:
            raise TypeError("Empty datasets have no numpy representation")
        if source_sel is None:
            source_sel = sel.SimpleSelection(self.shape)
        else:
            source_sel = sel.select(self.shape, source_sel, self)  # for numpy.s_
        fspace = source_sel.id

        if dest_sel is None:
            dest_sel = sel.SimpleSelection(dest.shape)
        else:
            dest_sel = sel.select(dest.shape, dest_sel, self)

        for mspace in dest_sel.broadcast(source_sel.mshape):
            self.id.read(mspace, fspace, dest, dxpl=self._dxpl)


# Traceback (TypeError)
Traceback (most recent call last):
File "/Users/jasondet/Downloads/h5py_bug.py", line 9, in <module>
dset.read_direct(arr, None, np.s_[2:])
File "/usr/local/lib/python3.9/site-packages/h5py/_hl/dataset.py", line 970, in read_direct
for mspace in dest_sel.broadcast(source_sel.mshape):
File "/usr/local/lib/python3.9/site-packages/h5py/_hl/selections.py", line 291, in broadcast
tshape = self.expand_shape(source_shape)
File "/usr/local/lib/python3.9/site-packages/h5py/_hl/selections.py", line 264, in expand_shape
raise TypeError("Can't broadcast %s -> %s" % (source_shape, self.array_shape))  # array shape
TypeError: Can't broadcast (10,) -> (8,)

# Fixed code
def read_direct(self, dest, source_sel=None, dest_sel=None):
    """Read data directly from HDF5 into an existing NumPy array.

    The destination array must be C-contiguous and writable.
    Selections must be the output of numpy.s_[<args>].

    Broadcasting is supported for simple indexing.
    """
    with phil:
        if self._is_empty:
            raise TypeError("Empty datasets have no numpy representation")
        if source_sel is None:
            source_sel = sel.SimpleSelection(self.shape)
        else:
            source_sel = sel.select(self.shape, source_sel, self)  # for numpy.s_
        fspace = source_sel.id

        if dest_sel is None:
            dest_sel = sel.SimpleSelection(dest.shape)
        else:
            dest_sel = sel.select(dest.shape, dest_sel)

        for mspace in dest_sel.broadcast(source_sel.mshape):
            self.id.read(mspace, fspace, dest, dxpl=self._dxpl)
# Buggy code
def write_direct(self, source, source_sel=None, dest_sel=None):
    """Write data directly to HDF5 from a NumPy array.

    The source array must be C-contiguous.  Selections must be
    the output of numpy.s_[<args>].

    Broadcasting is supported for simple indexing.
    """
    with phil:
        if self._is_empty:
            raise TypeError("Empty datasets cannot be written to")
        if source_sel is None:
            source_sel = sel.SimpleSelection(source.shape)
        else:
            source_sel = sel.select(source.shape, source_sel, self)  # for numpy.s_
        mspace = source_sel.id

        if dest_sel is None:
            dest_sel = sel.SimpleSelection(self.shape)
        else:
            dest_sel = sel.select(self.shape, dest_sel, self)

        for fspace in dest_sel.broadcast(source_sel.mshape):
            self.id.write(mspace, fspace, source, dxpl=self._dxpl)


# Traceback (TypeError)
Traceback (most recent call last):
File "/Users/jasondet/Downloads/h5py_bug.py", line 9, in <module>
dset.read_direct(arr, None, np.s_[2:])
File "/usr/local/lib/python3.9/site-packages/h5py/_hl/dataset.py", line 970, in read_direct
for mspace in dest_sel.broadcast(source_sel.mshape):
File "/usr/local/lib/python3.9/site-packages/h5py/_hl/selections.py", line 291, in broadcast
tshape = self.expand_shape(source_shape)
File "/usr/local/lib/python3.9/site-packages/h5py/_hl/selections.py", line 264, in expand_shape
raise TypeError("Can't broadcast %s -> %s" % (source_shape, self.array_shape))  # array shape
TypeError: Can't broadcast (10,) -> (8,)

# Fixed code
def write_direct(self, source, source_sel=None, dest_sel=None):
    """Write data directly to HDF5 from a NumPy array.

    The source array must be C-contiguous.  Selections must be
    the output of numpy.s_[<args>].

    Broadcasting is supported for simple indexing.
    """
    with phil:
        if self._is_empty:
            raise TypeError("Empty datasets cannot be written to")
        if source_sel is None:
            source_sel = sel.SimpleSelection(source.shape)
        else:
            source_sel = sel.select(source.shape, source_sel)  # for numpy.s_
        mspace = source_sel.id

        if dest_sel is None:
            dest_sel = sel.SimpleSelection(self.shape)
        else:
            dest_sel = sel.select(self.shape, dest_sel, self)

        for fspace in dest_sel.broadcast(source_sel.mshape):
            self.id.write(mspace, fspace, source, dxpl=self._dxpl)
# Buggy code
def __init__(self, dtype):
    self.dtype = dtype


# Traceback (AttributeError)
Traceback (most recent call last):
File "error.py", line 4, in <module>
f.attrs['empty'] = h5py.Empty('f')
File "h5py/_objects.pyx", line 54, in h5py._objects.with_phil.wrapper
File "h5py/_objects.pyx", line 55, in h5py._objects.with_phil.wrapper
File "/usr/local/lib/python3.7/site-packages/h5py/_hl/attrs.py", line 100, in __setitem__
self.create(name, data=value)
File "/usr/local/lib/python3.7/site-packages/h5py/_hl/attrs.py", line 156, in create
if dtype.subdtype is not None:
AttributeError: 'str' object has no attribute 'subdtype'

# Fixed code
def __init__(self, dtype):
    self.dtype = np.dtype(dtype)
# Buggy code
def size(self):
    """Numpy-style attribute giving the total dataset size"""
    return numpy.prod(self.shape, dtype=numpy.intp)


# Traceback (TypeError)
TypeError                                 Traceback (most recent call last)
<ipython-input-10-f4a7fbce39b5> in <module>()
----> 1 hasattr(empty, "size")

h5py/_objects.pyx in h5py._objects.with_phil.wrapper()

h5py/_objects.pyx in h5py._objects.with_phil.wrapper()

~/.local/lib/python3.5/site-packages/h5py/_hl/dataset.py in size(self)
234     def size(self):
235         """Numpy-style attribute giving the total dataset size"""
--> 236         return numpy.prod(self.shape, dtype=numpy.intp)
237
238     @property

~/.local/lib/python3.5/site-packages/numpy/core/fromnumeric.py in prod(a, axis, dtype, out, keepdims)
2564
2565     return _methods._prod(a, axis=axis, dtype=dtype,
-> 2566                           out=out, **kwargs)
2567
2568

~/.local/lib/python3.5/site-packages/numpy/core/_methods.py in _prod(a, axis, dtype, out, keepdims)
33
34 def _prod(a, axis=None, dtype=None, out=None, keepdims=False):
---> 35     return umr_prod(a, axis, dtype, out, keepdims)
36
37 def _any(a, axis=None, dtype=None, out=None, keepdims=False):

TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'

# Fixed code
def size(self):
    """Numpy-style attribute giving the total dataset size"""
    if is_empty_dataspace(self.id):
        return None
    return numpy.prod(self.shape, dtype=numpy.intp)
# Buggy code
def h5py_completer(self, event):
    """Completer function to be loaded into IPython"""
    base = re_object_match.split(event.line)[1]

    if not isinstance(self._ofind(base)["obj"], (AttributeManager, HLObject)):
        raise TryNext

    try:
        return h5py_attr_completer(self, event.line)
    except ValueError:
        pass

    try:
        return h5py_item_completer(self, event.line)
    except ValueError:
        pass

    return []


# Traceback (KeyError)
$ ipython
Python 3.6.1 | packaged by conda-forge | (default, May 11 2017, 18:00:28)
Type 'copyright', 'credits' or 'license' for more information
IPython 6.0.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: [a[Exception in thread Thread-40:
Traceback (most recent call last):
File "/zopt/conda2/envs/test/lib/python3.6/threading.py", line 916, in _bootstrap_inner
self.run()
File "/zopt/conda2/envs/test/lib/python3.6/threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "/zopt/conda2/envs/test/lib/python3.6/site-packages/prompt_toolkit/interface.py", line 860, in run
completions = list(buffer.completer.get_completions(document, complete_event))
File "/zopt/conda2/envs/test/lib/python3.6/site-packages/IPython/terminal/ptutils.py", line 75, in get_completions
yield from self._get_completions(body, offset, cursor_position, self.ipy_completer)
File "/zopt/conda2/envs/test/lib/python3.6/site-packages/IPython/terminal/ptutils.py", line 85, in _get_completions
for c in completions:
File "/zopt/conda2/envs/test/lib/python3.6/site-packages/IPython/core/completer.py", line 429, in _deduplicate_completions
completions = list(completions)
File "/zopt/conda2/envs/test/lib/python3.6/site-packages/IPython/core/completer.py", line 1647, in completions
for c in self._completions(text, offset, _timeout=self.jedi_compute_type_timeout/1000):
File "/zopt/conda2/envs/test/lib/python3.6/site-packages/IPython/core/completer.py", line 1687, in _completions
full_text=full_text, cursor_line=cursor_line, cursor_pos=cursor_column)
File "/zopt/conda2/envs/test/lib/python3.6/site-packages/IPython/core/completer.py", line 1829, in _complete
custom_res = self.dispatch_custom_completer(text)
File "/zopt/conda2/envs/test/lib/python3.6/site-packages/IPython/core/completer.py", line 1582, in dispatch_custom_completer
res = c(event)
File "/zopt/conda2/envs/test/lib/python3.6/site-packages/h5py/ipy_completer.py", line 175, in h5py_completer
if not isinstance(self._ofind(base)['obj'], (AttributeManager, HLObject)):
KeyError: 'obj'

# Fixed code
def h5py_completer(self, event):
    """Completer function to be loaded into IPython"""
    base = re_object_match.split(event.line)[1]

    if not isinstance(self._ofind(base).get("obj"), (AttributeManager, HLObject)):
        raise TryNext

    try:
        return h5py_attr_completer(self, event.line)
    except ValueError:
        pass

    try:
        return h5py_item_completer(self, event.line)
    except ValueError:
        pass

    return []
# Buggy code
def parse(self, handler, name=None):
    args, varargs, kwargs, defaults, kwonly, kwonlydefaults, annotations = (
        getfullargspec(unwrap(handler))
    )
    if ismethod(handler) or handler.__name__ == "__init__":
        args = args[1:]  # drop 'self'
    spec = ArgumentSpec(
        name,
        self._type,
        positional=args,
        varargs=varargs,
        kwargs=kwargs,
        kwonlyargs=kwonly,
        defaults=self._get_defaults(args, defaults, kwonlydefaults),
    )
    spec.types = self._get_types(handler, annotations, spec)
    return spec


# Traceback (TypeError)
from inspect import getfullargspec
from operator import eq
getfullargspec(eq)
Traceback (most recent call last):
[snip]
TypeError: unsupported callable
getfullargspec(len)
[snip]
TypeError: unsupported callable

# Fixed code
def parse(self, handler, name=None):
    args, varargs, kws, defaults, kwo, kwo_defaults, annotations = self._get_arg_spec(
        handler
    )
    spec = ArgumentSpec(
        name,
        self._type,
        positional=args,
        varargs=varargs,
        kwargs=kws,
        kwonlyargs=kwo,
        defaults=self._get_defaults(args, defaults, kwo_defaults),
    )
    spec.types = self._get_types(handler, annotations, spec)
    return spec
# Buggy code
def _get_defaults(self, args, default_values, kwonlydefaults):
    if default_values:
        defaults = dict(zip(args[-len(default_values) :], default_values))
    else:
        defaults = {}
    if kwonlydefaults:
        defaults.update(kwonlydefaults)
    return defaults


# Traceback (TypeError)
from inspect import getfullargspec
from operator import eq
getfullargspec(eq)
Traceback (most recent call last):
[snip]
TypeError: unsupported callable
getfullargspec(len)
[snip]
TypeError: unsupported callable

# Fixed code
def _get_defaults(self, args, default_values, kwo_defaults):
    if default_values:
        defaults = dict(zip(args[-len(default_values) :], default_values))
    else:
        defaults = {}
    if kwo_defaults:
        defaults.update(kwo_defaults)
    return defaults
# Buggy code
def getfullargspec(func):
    return getargspec(unwrap(func)) + ([], None, {})


# Traceback (TypeError)
from inspect import getfullargspec
from operator import eq
getfullargspec(eq)
Traceback (most recent call last):
[snip]
TypeError: unsupported callable
getfullargspec(len)
[snip]
TypeError: unsupported callable

# Fixed code
def getfullargspec(func):
    return getargspec(func) + ([], None, {})
# Buggy code
def _get_writer(self, outpath):
    return file_writer(outpath, newline=self._options["line_separator"])


# Traceback (IOError)
$ python -m robot.libdoc BuiltIn out.html
Unexpected error: IOError: [Errno 13] Permission denied: 'out.html'
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/robot/utils/application.py", line 83, in _execute
rc = self.main(arguments, **options)
File "/usr/local/lib/python2.7/dist-packages/robot/libdoc.py", line 158, in main
libdoc.save(output, self._get_output_format(format, output))
File "/usr/local/lib/python2.7/dist-packages/robot/libdocpkg/model.py", line 52, in save
with LibdocOutput(output, format) as outfile:
File "/usr/local/lib/python2.7/dist-packages/robot/libdocpkg/output.py", line 30, in __enter__
self._output_file = file_writer(self._output_path)
File "/usr/local/lib/python2.7/dist-packages/robot/utils/robotio.py", line 23, in file_writer
f = io.open(path, 'w', encoding=encoding, newline=newline)

# Fixed code
def _get_writer(self, outpath):
    return file_writer(
        outpath, newline=self._options["line_separator"], usage="Tidy output"
    )
# Buggy code
def _remove_element(self, root, element, remove_tail=False):
    parent = self._find_parent(root, element)
    if element.tail and not remove_tail:
        self._preserve_tail(element, parent)
    parent.remove(element)


# Traceback (AttributeError)
AttributeError: 'builtin_function_or_method' object has no attribute 'startswith'
Traceback (most recent call last):
File "/opt/ute/python/lib/python2.7/site-packages/robot/libraries/XML.py", line 447, in parse_xml
NameSpaceStripper().strip(root)
File "/opt/ute/python/lib/python2.7/site-packages/robot/libraries/XML.py", line 1247, in strip
self.strip(child, current_ns)
File "/opt/ute/python/lib/python2.7/site-packages/robot/libraries/XML.py", line 1247, in strip
self.strip(child, current_ns)
File "/opt/ute/python/lib/python2.7/site-packages/robot/libraries/XML.py", line 1247, in strip
self.strip(child, current_ns)
File "/opt/ute/python/lib/python2.7/site-packages/robot/libraries/XML.py", line 1247, in strip
self.strip(child, current_ns)
File "/opt/ute/python/lib/python2.7/site-packages/robot/libraries/XML.py", line 1247, in strip
self.strip(child, current_ns)
File "/opt/ute/python/lib/python2.7/site-packages/robot/libraries/XML.py", line 1241, in strip
if elem.tag.startswith('{') and '}' in elem.tag:

# Fixed code
def _remove_element(self, root, element, remove_tail=False):
    parent = self._find_parent(root, element)
    if not remove_tail:
        self._preserve_tail(element, parent)
    parent.remove(element)
# Buggy code
def _preserve_tail(self, element, parent):
    index = list(parent).index(element)
    if index == 0:
        parent.text = (parent.text or "") + element.tail
    else:
        sibling = parent[index - 1]
        sibling.tail = (sibling.tail or "") + element.tail


# Traceback (AttributeError)
AttributeError: 'builtin_function_or_method' object has no attribute 'startswith'
Traceback (most recent call last):
File "/opt/ute/python/lib/python2.7/site-packages/robot/libraries/XML.py", line 447, in parse_xml
NameSpaceStripper().strip(root)
File "/opt/ute/python/lib/python2.7/site-packages/robot/libraries/XML.py", line 1247, in strip
self.strip(child, current_ns)
File "/opt/ute/python/lib/python2.7/site-packages/robot/libraries/XML.py", line 1247, in strip
self.strip(child, current_ns)
File "/opt/ute/python/lib/python2.7/site-packages/robot/libraries/XML.py", line 1247, in strip
self.strip(child, current_ns)
File "/opt/ute/python/lib/python2.7/site-packages/robot/libraries/XML.py", line 1247, in strip
self.strip(child, current_ns)
File "/opt/ute/python/lib/python2.7/site-packages/robot/libraries/XML.py", line 1247, in strip
self.strip(child, current_ns)
File "/opt/ute/python/lib/python2.7/site-packages/robot/libraries/XML.py", line 1241, in strip
if elem.tag.startswith('{') and '}' in elem.tag:

# Fixed code
def _preserve_tail(self, element, parent):
    if not element.tail:
        return
    index = list(parent).index(element)
    if index == 0:
        parent.text = (parent.text or "") + element.tail
    else:
        sibling = parent[index - 1]
        sibling.tail = (sibling.tail or "") + element.tail
# Buggy code
def exc_info(self):
    """
    Holds the exc_info three-tuple raised by the function if the
    greenlet finished with an error. Otherwise a false value.

    .. note:: This is a provisional API and may change.

    .. versionadded:: 1.1
    """
    ei = self._exc_info
    if ei is not None and ei[0] is not None:
        return (ei[0], ei[1], load_traceback(ei[2]))


# Traceback (RuntimeError)
Traceback (most recent call last):
File "src/gevent/greenlet.py", line 856, in gevent._gevent_cgreenlet.Greenlet.run
File "src/gevent/greenlet.py", line 837, in gevent._gevent_cgreenlet.Greenlet._Greenlet__report_error
File "/home/danmilon/tmp/gevent/src/gevent/_tblib.py", line 415, in g
return f(a)
File "/home/danmilon/tmp/gevent/src/gevent/_tblib.py", line 471, in dump_traceback
return dumps(tb)
File "/home/danmilon/.pyenv/versions/2.7.18/lib/python2.7/copy_reg.py", line 74, in _reduce_ex
getstate = self.__getstate__
RuntimeError: maximum recursion depth exceeded while calling a Python object
2020-11-23T13:06:10Z <callback at 0x7fe4304846e0 stopped> failed with RuntimeError

# Fixed code
def exc_info(self):
    """
    Holds the exc_info three-tuple raised by the function if the
    greenlet finished with an error. Otherwise a false value.

    .. note:: This is a provisional API and may change.

    .. versionadded:: 1.1
    """
    ei = self._exc_info
    if ei is not None and ei[0] is not None:
        return (
            ei[0],
            ei[1],
            # The pickled traceback may be None if we couldn't pickle it.
            load_traceback(ei[2]) if ei[2] else None,
        )
# Buggy code
def __report_error(self, exc_info):
    if isinstance(exc_info[1], GreenletExit):
        self.__report_result(exc_info[1])
        return

    self._exc_info = exc_info[0], exc_info[1], dump_traceback(exc_info[2])

    hub = get_my_hub(self)  # pylint:disable=undefined-variable
    if self._links and not self._notifier:
        self._notifier = hub.loop.run_callback(self._notify_links)

    try:
        hub.handle_error(self, *exc_info)
    finally:
        del exc_info


# Traceback (RuntimeError)
Traceback (most recent call last):
File "src/gevent/greenlet.py", line 856, in gevent._gevent_cgreenlet.Greenlet.run
File "src/gevent/greenlet.py", line 837, in gevent._gevent_cgreenlet.Greenlet._Greenlet__report_error
File "/home/danmilon/tmp/gevent/src/gevent/_tblib.py", line 415, in g
return f(a)
File "/home/danmilon/tmp/gevent/src/gevent/_tblib.py", line 471, in dump_traceback
return dumps(tb)
File "/home/danmilon/.pyenv/versions/2.7.18/lib/python2.7/copy_reg.py", line 74, in _reduce_ex
getstate = self.__getstate__
RuntimeError: maximum recursion depth exceeded while calling a Python object
2020-11-23T13:06:10Z <callback at 0x7fe4304846e0 stopped> failed with RuntimeError

# Fixed code
def __report_error(self, exc_info):
    if isinstance(exc_info[1], GreenletExit):
        self.__report_result(exc_info[1])
        return

    # Depending on the error, we may not be able to pickle it.
    # In particular, RecursionError can be a problem.
    try:
        tb = dump_traceback(exc_info[2])
    except:  # pylint:disable=bare-except
        tb = None
    self._exc_info = exc_info[0], exc_info[1], tb

    hub = get_my_hub(self)  # pylint:disable=undefined-variable
    if self._links and not self._notifier:
        self._notifier = hub.loop.run_callback(self._notify_links)

    try:
        hub.handle_error(self, *exc_info)
    finally:
        del exc_info
# Buggy code
def wait(self, timeout=None):
    """Waiting for a DummySemaphore returns immediately."""


# Traceback (AttributeError)
$ python
Python 3.7.5 (default, Nov 20 2019, 09:21:52)
[GCC 9.2.1 20191008] on linux
Type "help", "copyright", "credits" or "license" for more information.
import sys
import gevent.fileobject
gevent.fileobject.FileObjectThread(sys.stdin).readline()
Traceback (most recent call last):
File "/home/davidlawson/virtualenvs/scrapers_37/lib/python3.7/site-packages/gevent/threadpool.py", line 120, in __run_task
thread_result.set(func(*args, **kwargs))
AttributeError: '_io.TextIOWrapper' object has no attribute 'readinto'
2020-03-10T13:35:10Z (<ThreadPoolWorker at 0x7ffba1fb1ec0 thread_ident=0x7ffba1f87700 hub=<Hub at 0x7ffba21997d0 thread_ident=0x7ffba2de9740>>, <built-in method readline of _io.TextIOWrapper object at 0x7ffba24ce910>) failed with AttributeError

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/davidlawson/virtualenvs/scrapers_37/lib/python3.7/site-packages/gevent/_fileobjectcommon.py", line 525, in thread_method
return threadpool.apply(method, args, kwargs)
File "/home/davidlawson/virtualenvs/scrapers_37/lib/python3.7/site-packages/gevent/pool.py", line 161, in apply
return self.spawn(func, *args, **kwds).get()
File "src/gevent/event.py", line 279, in gevent._event.AsyncResult.get
File "src/gevent/event.py", line 307, in gevent._event.AsyncResult.get
File "src/gevent/event.py", line 297, in gevent._event.AsyncResult.get
File "src/gevent/event.py", line 277, in gevent._event.AsyncResult._raise_exception
File "/home/davidlawson/virtualenvs/scrapers_37/lib/python3.7/site-packages/gevent/_compat.py", line 62, in reraise
raise value.with_traceback(tb)
File "/home/davidlawson/virtualenvs/scrapers_37/lib/python3.7/site-packages/gevent/threadpool.py", line 120, in __run_task
thread_result.set(func(*args, **kwargs))
AttributeError: '_io.TextIOWrapper' object has no attribute 'readinto'

# Fixed code
def wait(self, timeout=None):  # pylint:disable=unused-argument
    """Waiting for a DummySemaphore returns immediately."""
    return 1
# Buggy code
def __repr__(self):
    return "<%s _fobj=%r%s>" % (self.__class__.__name__, self.io, self._extra_repr())


# Traceback (UnicodeDecodeError)
Traceback (most recent call last):
File "src/gevent/greenlet.py", line 766, in gevent._greenlet.Greenlet.run
File "/usr/local/lib/python3.7/site-packages/gevent/subprocess.py", line 725, in _read
data = pipe.read()
File "/usr/local/lib/python3.7/codecs.py", line 322, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode bytes in position 0-1: invalid continuation byte
2020-01-14T10:08:13Z <Greenlet at 0x7ff576becdd0: _read> failed with UnicodeDecodeError

# Fixed code
def __repr__(self):
    return "<%s at 0x%x %s_fobj=%r%s>" % (
        self.__class__.__name__,
        id(self),
        "closed" if self.closed else "",
        self.io,
        self._extra_repr(),
    )
# Buggy code
def _local_find_descriptors(self):
    type_self = type(self)
    gets = set()
    dels = set()
    set_or_del = set()
    sets = set()

    for attr_name in dir(type_self):
        attr = getattr(type_self, attr_name)
        type_attr = type(attr)
        if hasattr(type_attr, "__get__"):
            gets.add(attr_name)
        if hasattr(type_attr, "__delete__"):
            dels.add(attr_name)
            set_or_del.add(attr_name)
        if hasattr(type_attr, "__set__"):
            sets.add(attr_name)

    return (gets, dels, set_or_del, sets)


# Traceback (AttributeError)
Traceback (most recent call last):
...
File "//transaction-2.1.2-py2.py3-none-any.ovo/transaction/__init__.py", line 28, in <module>
manager = ThreadTransactionManager()
File "//gevent/src/gevent/local.py", line 517, in __new__
self.__cinit__(*args[1:], **kw)
File "//gevent/src/gevent/local.py", line 336, in __cinit__
get, dels, sets_or_dels, sets = _local_find_descriptors(self)
File "//gevent/src/gevent/local.py", line 496, in _local_find_descriptors
attr = getattr(type_self, attr_name)
File "//eggs/zope.interface-4.4.3-py2.7.egg/zope/interface/declarations.py", line 634, in __get__
raise AttributeError('__provides__')
AttributeError: __provides__

# Fixed code
def _local_find_descriptors(self):
    type_self = type(self)
    gets = set()
    dels = set()
    set_or_del = set()
    sets = set()
    mro = list(type_self.mro())

    for attr_name in dir(type_self):
        # Conventionally, descriptors when called on a class
        # return themself, but not all do. Notable exceptions are
        # in the zope.interface package, where things like __provides__
        # return other class attributes. So we can't use getattr, and instead
        # walk up the dicts
        for base in mro:
            if attr_name in base.__dict__:
                attr = base.__dict__[attr_name]
                break
        else:
            raise AttributeError(attr_name)

        type_attr = type(attr)
        if hasattr(type_attr, "__get__"):
            gets.add(attr_name)
        if hasattr(type_attr, "__delete__"):
            dels.add(attr_name)
            set_or_del.add(attr_name)
        if hasattr(type_attr, "__set__"):
            sets.add(attr_name)

    return (gets, dels, set_or_del, sets)
# Buggy code
def __setattr__(cls, name, value):
    # Because we can't know whether to try to go to the module
    # or the class, we don't allow setting an attribute after the fact
    raise TypeError("Cannot set attribute")


# Traceback (TypeError)
[DEBUG   ] Local cache dir: '/var/cache/salt/minion/files/base/_proxy'
[DEBUG   ] Refreshing modules...
......
Passed invalid arguments: Cannot set attribute.
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/cli/caller.py", line 196, in call
ret['return'] = func(*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/salt/modules/state.py", line 594, in highstate
whitelist=kwargs.get('whitelist')
File "/usr/lib/python2.7/dist-packages/salt/state.py", line 3173, in call_highstate
self.load_dynamic(matches)
File "/usr/lib/python2.7/dist-packages/salt/state.py", line 2706, in load_dynamic
self.state.module_refresh()
File "/usr/lib/python2.7/dist-packages/salt/state.py", line 857, in module_refresh
reload(site)
File "/usr/lib/python2.7/site.py", line 563, in <module>
main()
File "/usr/lib/python2.7/site.py", line 541, in main
abs__file__()
File "/usr/lib/python2.7/site.py", line 100, in abs__file__
m.__file__ = os.path.abspath(m.__file__)
File "/usr/local/lib/python2.7/dist-packages/gevent/__init__.py", line 87, in __setattr__
raise TypeError("Cannot set attribute")
TypeError: Cannot set attribute

# Fixed code
def __setattr__(cls, name, value):
    # For symmetry with getattr and dir, pass all
    # attribute setting on to the module. (This makes
    # reloading work, see issue #805)
    setattr(_signal_module, name, value)
# Buggy code
def sendall(self, data, flags=0):
    # XXX When we run on PyPy3, see the notes in _socket2.py's sendall()
    data_memory = _get_memory(data)
    if self.timeout is None:
        data_sent = 0
        while data_sent < len(data_memory):
            data_sent += self.send(data_memory[data_sent:], flags)
    else:
        timeleft = self.timeout
        end = time.time() + timeleft
        data_sent = 0
        while True:
            data_sent += self.send(data_memory[data_sent:], flags, timeout=timeleft)
            if data_sent >= len(data_memory):
                break
            timeleft = end - time.time()
            if timeleft <= 0:
                raise timeout("timed out")


# Traceback (SSLError)
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/gevent/greenlet.py", line 327, in run
result = self._run(*self.args, **self.kwargs)
File "/usr/local/lib/python2.7/dist-packages/gevent/server.py", line 102, in wrap_socket_and_handle
ssl_socket = self.wrap_socket(client_socket, **self.ssl_args)
File "/usr/local/lib/python2.7/dist-packages/gevent/_ssl2.py", line 410, in wrap_socket
ciphers=ciphers)
File "/usr/local/lib/python2.7/dist-packages/gevent/_ssl2.py", line 93, in __init__
self.do_handshake()
File "/usr/local/lib/python2.7/dist-packages/gevent/_ssl2.py", line 310, in do_handshake
return self._sslobj.do_handshake()
SSLError: [Errno 8] _ssl.c:510: EOF occurred in violation of protocol
<Greenlet at 0x7fbc02c4a9b0: <bound method WSGIServer.wrap_socket_and_handle of <WSGIServer at 0x7fbc03b9b110 fileno=9 address=0.0.0.0:5000>>(<socket at 0x7fbc02bf7590 fileno=76 sock=10.122.97, ('41.234.232.59', 40471))> failed with SSLError

# Fixed code
def sendall(self, data, flags=0):
    # XXX When we run on PyPy3, see the notes in _socket2.py's sendall()
    data_memory = _get_memory(data)
    len_data_memory = len(data_memory)
    if not len_data_memory:
        # Don't try to send empty data at all, no point, and breaks ssl
        # See issue 719
        return 0

    if self.timeout is None:
        data_sent = 0
        while data_sent < len_data_memory:
            data_sent += self.send(data_memory[data_sent:], flags)
    else:
        timeleft = self.timeout
        end = time.time() + timeleft
        data_sent = 0
        while True:
            data_sent += self.send(data_memory[data_sent:], flags, timeout=timeleft)
            if data_sent >= len_data_memory:
                break
            timeleft = end - time.time()
            if timeleft <= 0:
                raise timeout("timed out")
# Buggy code
def sendall(self, data):
    fileno = self.fileno()
    bytes_total = len(data)
    bytes_written = 0
    while True:
        try:
            bytes_written += _write(fileno, _get_memory(data, bytes_written))
        except (IOError, OSError) as ex:
            code = ex.args[0]
            if code not in ignored_errors:
                raise
            sys.exc_clear()
        if bytes_written >= bytes_total:
            return
        self.hub.wait(self._write_event)


# Traceback (TypeError)
python test.py
Traceback (most recent call last):
File "test.py", line 22, in <module>
TestFails()
File "test.py", line 19, in TestFails
sock.sendall(anStructure)
File "/usr/local/lib/python2.7/site-packages/gevent/socket.py", line 457, in sendall
while data_sent < len(data):
TypeError: object of type 'AnStructure' has no len()

# Fixed code
def sendall(self, data):
    fileno = self.fileno()
    data_memory = _get_memory(data)
    bytes_total = len(data_memory)
    bytes_written = 0
    while True:
        try:
            bytes_written += _write(fileno, data_memory[bytes_written:])
        except (IOError, OSError) as ex:
            code = ex.args[0]
            if code not in ignored_errors:
                raise
            sys.exc_clear()
        if bytes_written >= bytes_total:
            return
        self.hub.wait(self._write_event)
# Buggy code
def sendall(self, data, flags=0):
    if isinstance(data, unicode):
        data = data.encode()
    # this sendall is also reused by gevent.ssl.SSLSocket subclass,
    # so it should not call self._sock methods directly
    if self.timeout is None:
        data_sent = 0
        while data_sent < len(data):
            data_sent += self.send(_get_memory(data, data_sent), flags)
    else:
        timeleft = self.timeout
        end = time.time() + timeleft
        data_sent = 0
        while True:
            data_sent += self.send(
                _get_memory(data, data_sent), flags, timeout=timeleft
            )
            if data_sent >= len(data):
                return
            timeleft = end - time.time()
            if timeleft <= 0:
                raise timeout("timed out")


# Traceback (TypeError)
python test.py
Traceback (most recent call last):
File "test.py", line 22, in <module>
TestFails()
File "test.py", line 19, in TestFails
sock.sendall(anStructure)
File "/usr/local/lib/python2.7/site-packages/gevent/socket.py", line 457, in sendall
while data_sent < len(data):
TypeError: object of type 'AnStructure' has no len()

# Fixed code
def sendall(self, data, flags=0):
    if isinstance(data, unicode):
        data = data.encode()
    # this sendall is also reused by gevent.ssl.SSLSocket subclass,
    # so it should not call self._sock methods directly
    data_memory = _get_memory(data)
    if self.timeout is None:
        data_sent = 0
        while data_sent < len(data_memory):
            data_sent += self.send(data_memory[data_sent:], flags)
    else:
        timeleft = self.timeout
        end = time.time() + timeleft
        data_sent = 0
        while True:
            data_sent += self.send(data_memory[data_sent:], flags, timeout=timeleft)
            if data_sent >= len(data_memory):
                return
            timeleft = end - time.time()
            if timeleft <= 0:
                raise timeout("timed out")
# Buggy code
def _get_memory(string, offset):
    try:
        return memoryview(string)[offset:]
    except TypeError:
        # fixes "python2.7 array.array doesn't support memoryview used in
        # gevent.socket.send" issue
        # (http://code.google.com/p/gevent/issues/detail?id=94)
        return buffer(string, offset)


# Traceback (TypeError)
python test.py
Traceback (most recent call last):
File "test.py", line 22, in <module>
TestFails()
File "test.py", line 19, in TestFails
sock.sendall(anStructure)
File "/usr/local/lib/python2.7/site-packages/gevent/socket.py", line 457, in sendall
while data_sent < len(data):
TypeError: object of type 'AnStructure' has no len()

# Fixed code
def _get_memory(data):
    try:
        mv = memoryview(data)
        if mv.shape:
            return mv
        # No shape, probably working with a ctypes object,
        # or something else exotic that supports the buffer interface
        return mv.tobytes()
    except TypeError:
        # fixes "python2.7 array.array doesn't support memoryview used in
        # gevent.socket.send" issue
        # (http://code.google.com/p/gevent/issues/detail?id=94)
        return buffer(data)
# Buggy code
def _get_memory(string, offset):
    return memoryview(string)[offset:]


# Traceback (TypeError)
python test.py
Traceback (most recent call last):
File "test.py", line 22, in <module>
TestFails()
File "test.py", line 19, in TestFails
sock.sendall(anStructure)
File "/usr/local/lib/python2.7/site-packages/gevent/socket.py", line 457, in sendall
while data_sent < len(data):
TypeError: object of type 'AnStructure' has no len()

# Fixed code
def _get_memory(data):
    mv = memoryview(data)
    if mv.shape:
        return mv
    # No shape, probably working with a ctypes object,
    # or something else exotic that supports the buffer interface
    return mv.tobytes()
# Buggy code
def sendall(self, data, flags=0):
    if self.timeout is None:
        data_sent = 0
        while data_sent < len(data):
            data_sent += self.send(_get_memory(data, data_sent), flags)
    else:
        timeleft = self.timeout
        end = time.time() + timeleft
        data_sent = 0
        while True:
            data_sent += self.send(
                _get_memory(data, data_sent), flags, timeout=timeleft
            )
            if data_sent >= len(data):
                break
            timeleft = end - time.time()
            if timeleft <= 0:
                raise timeout("timed out")


# Traceback (TypeError)
python test.py
Traceback (most recent call last):
File "test.py", line 22, in <module>
TestFails()
File "test.py", line 19, in TestFails
sock.sendall(anStructure)
File "/usr/local/lib/python2.7/site-packages/gevent/socket.py", line 457, in sendall
while data_sent < len(data):
TypeError: object of type 'AnStructure' has no len()

# Fixed code
def sendall(self, data, flags=0):
    data_memory = _get_memory(data)
    if self.timeout is None:
        data_sent = 0
        while data_sent < len(data_memory):
            data_sent += self.send(data_memory[data_sent:], flags)
    else:
        timeleft = self.timeout
        end = time.time() + timeleft
        data_sent = 0
        while True:
            data_sent += self.send(data_memory[data_sent:], flags, timeout=timeleft)
            if data_sent >= len(data_memory):
                break
            timeleft = end - time.time()
            if timeleft <= 0:
                raise timeout("timed out")