gurudesh/pytracebugs huggingface dataset:
# Buggy code
def __setitem__(self, key, value):
    """Set attribute corresponding to key with value."""
    # Catch AttributeError to gracefully handle inability to set an
    # attribute due to it not being writeable or set-table.
    # Fix issue #6728 . Also, catch NotImplementedError for safety.
    try:
        setattr(self.__obj__, key, value)
    except (TypeError, AttributeError, NotImplementedError):
        pass


# Traceback (AttributeError)
File "C:\Anaconda3\lib\site-packages\spyder\widgets\variableexplorer\collectionseditor.py", line 626, in setModelData
self.set_value(index, value)
File "C:\Anaconda3\lib\site-packages\spyder\widgets\variableexplorer\collectionseditor.py", line 387, in set_value
index.model().set_value(index, value)
File "C:\Anaconda3\lib\site-packages\spyder\widgets\variableexplorer\collectionseditor.py", line 342, in set_value
self._data[ self.keys[index.row()] ] = value
File "C:\Anaconda3\lib\site-packages\spyder\widgets\variableexplorer\collectionseditor.py", line 83, in __setitem__
setattr(self.__obj__, key, value)
AttributeError: attribute 'day' of 'pandas._libs.period._Period' objects is not writable

# Fixed code
def __setitem__(self, key, value):
    """Set attribute corresponding to key with value."""
    # Catch AttributeError to gracefully handle inability to set an
    # attribute due to it not being writeable or set-table.
    # Fix issue #6728 . Also, catch NotImplementedError for safety.
    try:
        setattr(self.__obj__, key, value)
    except (TypeError, AttributeError, NotImplementedError):
        pass
    except Exception as e:
        if "cannot set values for" not in str(e):
            raise
# Buggy code
def __getitem__(self, key):
    """Get the attribute corresponding to the given key."""
    # Catch NotImplementedError to fix #6284 in pandas MultiIndex
    # due to NA checking not being supported on a multiindex.
    # Catch AttributeError to fix #5642 in certain special classes like xml
    # when this method is called on certain attributes
    try:
        attribute_toreturn = getattr(self.__obj__, key)
    except (NotImplementedError, AttributeError):
        attribute_toreturn = None
    return attribute_toreturn


# Traceback (TypeError)
Traceback (most recent call last):
File "C:\Anaconda3\lib\site-packages\spyder\widgets\variableexplorer\collectionseditor.py", line 288, in data
value = self.get_value(index)
File "C:\Anaconda3\lib\site-packages\spyder\widgets\variableexplorer\collectionseditor.py", line 269, in get_value
return self._data[ self.keys[index.row()] ]
File "C:\Anaconda3\lib\site-packages\spyder\widgets\variableexplorer\collectionseditor.py", line 78, in __getitem__
return getattr(self.__obj__, key)
File "pandas/_libs/period.pyx", line 826, in pandas._libs.period._Period.end_time.__get__
TypeError: unsupported operand type(s) for +: 'Period' and 'int'

# Fixed code
def __getitem__(self, key):
    """Get the attribute corresponding to the given key."""
    # Catch NotImplementedError to fix #6284 in pandas MultiIndex
    # due to NA checking not being supported on a multiindex.
    # Catch AttributeError to fix #5642 in certain special classes like xml
    # when this method is called on certain attributes.
    # Catch TypeError to prevent fatal Python crash to desktop after
    # modifying certain pandas objects ( Issue #6727 ).
    try:
        attribute_toreturn = getattr(self.__obj__, key)
    except (NotImplementedError, AttributeError, TypeError):
        attribute_toreturn = None
    return attribute_toreturn
# Buggy code
def _import_module_from_path(module_name, plugin_path):
    """Imports `module_name` from `plugin_path`.

    Return None if no module is found.
    """
    module = None
    if PY2:
        info = imp.find_module(module_name, [plugin_path])
        if info:
            module = imp.load_module(module_name, *info)
    elif sys.version_info[0:2] <= (3, 3):
        loader = importlib.machinery.PathFinder.find_module(module_name, [plugin_path])
        if loader:
            module = loader.load_module(module_name)
    else:  # Python 3.4+
        spec = importlib.machinery.PathFinder.find_spec(module_name, [plugin_path])
        if spec:
            module = spec.loader.load_module(module_name)
    return module


# Traceback (AttributeError)
module = _import_module_from_path(module_name, plugin_path)
module = spec.loader.load_module(module_name)
AttributeError: 'NoneType' object has no attribute 'load_module'

# Fixed code
def _import_module_from_path(module_name, plugin_path):
    """Imports `module_name` from `plugin_path`.

    Return None if no module is found.
    """
    module = None
    if PY2:
        info = imp.find_module(module_name, [plugin_path])
        if info:
            module = imp.load_module(module_name, *info)
    elif sys.version_info[0:2] <= (3, 3):
        loader = importlib.machinery.PathFinder.find_module(module_name, [plugin_path])
        if loader:
            module = loader.load_module(module_name)
    else:  # Python 3.4+
        spec = importlib.machinery.PathFinder.find_spec(module_name, [plugin_path])
        if spec:
            # Needed to prevent an error when 'spec.loader' is None
            # See issue 6518
            try:
                module = spec.loader.load_module(module_name)
            except AttributeError:
                module = None
    return module
# Buggy code
def register_plugin(self):
    """Register plugin in Spyder's main window"""
    self.focus_changed.connect(self.main.plugin_focus_changed)
    self.main.add_dockwidget(self)
    self.main.console.set_help(self)

    self.internal_shell = self.main.console.shell
    self.console = self.main.console
    self.ipyconsole = self.main.ipyconsole
    self.editor = self.main.editor


# Traceback (AttributeError)
File "/home/parichay/code/env/spyder3/lib/python3.5/site-packages/spyder/plugins/configdialog.py", line 223, in button_clicked
configpage.apply_changes()
File "/home/parichay/code/env/spyder3/lib/python3.5/site-packages/spyder/plugins/configdialog.py", line 104, in apply_changes
self.apply_callback()
File "/home/parichay/code/env/spyder3/lib/python3.5/site-packages/spyder/plugins/configdialog.py", line 269, in <lambda>
self.apply_settings(self.changed_options))
File "/home/parichay/code/env/spyder3/lib/python3.5/site-packages/spyder/plugins/configdialog.py", line 1187, in apply_settings
self.main.help.apply_plugin_settings(['color_scheme_name'])
File "/home/parichay/code/env/spyder3/lib/python3.5/site-packages/spyder/plugins/help.py", line 552, in apply_plugin_settings
self.editor.apply_plugin_settings(options=[connect_n])
AttributeError: 'NoneType' object has no attribute 'apply_plugin_settings'

# Fixed code
def register_plugin(self):
    """Register plugin in Spyder's main window"""
    self.focus_changed.connect(self.main.plugin_focus_changed)
    self.main.add_dockwidget(self)
    self.main.console.set_help(self)

    self.internal_shell = self.main.console.shell
    self.console = self.main.console
# Buggy code
def apply_plugin_settings(self, options):
    """Apply configuration file's plugin settings"""
    color_scheme_n = "color_scheme_name"
    color_scheme_o = self.get_color_scheme()
    connect_n = "connect_to_oi"
    wrap_n = "wrap"
    wrap_o = self.get_option(wrap_n)
    self.wrap_action.setChecked(wrap_o)
    math_n = "math"
    math_o = self.get_option(math_n)

    if color_scheme_n in options:
        self.set_plain_text_color_scheme(color_scheme_o)
    if wrap_n in options:
        self.toggle_wrap_mode(wrap_o)
    if math_n in options:
        self.toggle_math_mode(math_o)

    # To make auto-connection changes take place instantly
    self.editor.apply_plugin_settings(options=[connect_n])
    self.ipyconsole.apply_plugin_settings(options=[connect_n])


# Traceback (AttributeError)
File "/home/parichay/code/env/spyder3/lib/python3.5/site-packages/spyder/plugins/configdialog.py", line 223, in button_clicked
configpage.apply_changes()
File "/home/parichay/code/env/spyder3/lib/python3.5/site-packages/spyder/plugins/configdialog.py", line 104, in apply_changes
self.apply_callback()
File "/home/parichay/code/env/spyder3/lib/python3.5/site-packages/spyder/plugins/configdialog.py", line 269, in <lambda>
self.apply_settings(self.changed_options))
File "/home/parichay/code/env/spyder3/lib/python3.5/site-packages/spyder/plugins/configdialog.py", line 1187, in apply_settings
self.main.help.apply_plugin_settings(['color_scheme_name'])
File "/home/parichay/code/env/spyder3/lib/python3.5/site-packages/spyder/plugins/help.py", line 552, in apply_plugin_settings
self.editor.apply_plugin_settings(options=[connect_n])
AttributeError: 'NoneType' object has no attribute 'apply_plugin_settings'

# Fixed code
def apply_plugin_settings(self, options):
    """Apply configuration file's plugin settings"""
    color_scheme_n = "color_scheme_name"
    color_scheme_o = self.get_color_scheme()
    connect_n = "connect_to_oi"
    wrap_n = "wrap"
    wrap_o = self.get_option(wrap_n)
    self.wrap_action.setChecked(wrap_o)
    math_n = "math"
    math_o = self.get_option(math_n)

    if color_scheme_n in options:
        self.set_plain_text_color_scheme(color_scheme_o)
    if wrap_n in options:
        self.toggle_wrap_mode(wrap_o)
    if math_n in options:
        self.toggle_math_mode(math_o)

    # To make auto-connection changes take place instantly
    self.main.editor.apply_plugin_settings(options=[connect_n])
    self.main.ipyconsole.apply_plugin_settings(options=[connect_n])
# Buggy code
def __eventually_raise_help(self, text, force=False):
    index = self.source_combo.currentIndex()
    if hasattr(self.main, "tabifiedDockWidgets"):
        # 'QMainWindow.tabifiedDockWidgets' was introduced in PyQt 4.5
        if (
            self.dockwidget
            and (force or self.dockwidget.isVisible())
            and not self.ismaximized
            and (force or text != self._last_texts[index])
        ):
            dockwidgets = self.main.tabifiedDockWidgets(self.dockwidget)
            if (
                self.console.dockwidget not in dockwidgets
                and self.ipyconsole is not None
                and self.ipyconsole.dockwidget not in dockwidgets
            ):
                self.dockwidget.show()
                self.dockwidget.raise_()
    self._last_texts[index] = text


# Traceback (AttributeError)
File "/home/parichay/code/env/spyder3/lib/python3.5/site-packages/spyder/plugins/configdialog.py", line 223, in button_clicked
configpage.apply_changes()
File "/home/parichay/code/env/spyder3/lib/python3.5/site-packages/spyder/plugins/configdialog.py", line 104, in apply_changes
self.apply_callback()
File "/home/parichay/code/env/spyder3/lib/python3.5/site-packages/spyder/plugins/configdialog.py", line 269, in <lambda>
self.apply_settings(self.changed_options))
File "/home/parichay/code/env/spyder3/lib/python3.5/site-packages/spyder/plugins/configdialog.py", line 1187, in apply_settings
self.main.help.apply_plugin_settings(['color_scheme_name'])
File "/home/parichay/code/env/spyder3/lib/python3.5/site-packages/spyder/plugins/help.py", line 552, in apply_plugin_settings
self.editor.apply_plugin_settings(options=[connect_n])
AttributeError: 'NoneType' object has no attribute 'apply_plugin_settings'

# Fixed code
def __eventually_raise_help(self, text, force=False):
    index = self.source_combo.currentIndex()
    if hasattr(self.main, "tabifiedDockWidgets"):
        # 'QMainWindow.tabifiedDockWidgets' was introduced in PyQt 4.5
        if (
            self.dockwidget
            and (force or self.dockwidget.isVisible())
            and not self.ismaximized
            and (force or text != self._last_texts[index])
        ):
            dockwidgets = self.main.tabifiedDockWidgets(self.dockwidget)
            if (
                self.console.dockwidget not in dockwidgets
                and self.main.ipyconsole is not None
                and self.main.ipyconsole.dockwidget not in dockwidgets
            ):
                self.dockwidget.show()
                self.dockwidget.raise_()
    self._last_texts[index] = text
# Buggy code
def get_shell(self):
    """
    Return shell which is currently bound to Help,
    or another running shell if it has been terminated
    """
    if not hasattr(self.shell, "get_doc") or (
        hasattr(self.shell, "is_running") and not self.shell.is_running()
    ):
        self.shell = None
        if self.ipyconsole is not None:
            shell = self.ipyconsole.get_current_shellwidget()
            if shell is not None and shell.kernel_client is not None:
                self.shell = shell
        if self.shell is None:
            self.shell = self.internal_shell
    return self.shell


# Traceback (AttributeError)
File "/home/parichay/code/env/spyder3/lib/python3.5/site-packages/spyder/plugins/configdialog.py", line 223, in button_clicked
configpage.apply_changes()
File "/home/parichay/code/env/spyder3/lib/python3.5/site-packages/spyder/plugins/configdialog.py", line 104, in apply_changes
self.apply_callback()
File "/home/parichay/code/env/spyder3/lib/python3.5/site-packages/spyder/plugins/configdialog.py", line 269, in <lambda>
self.apply_settings(self.changed_options))
File "/home/parichay/code/env/spyder3/lib/python3.5/site-packages/spyder/plugins/configdialog.py", line 1187, in apply_settings
self.main.help.apply_plugin_settings(['color_scheme_name'])
File "/home/parichay/code/env/spyder3/lib/python3.5/site-packages/spyder/plugins/help.py", line 552, in apply_plugin_settings
self.editor.apply_plugin_settings(options=[connect_n])
AttributeError: 'NoneType' object has no attribute 'apply_plugin_settings'

# Fixed code
def get_shell(self):
    """
    Return shell which is currently bound to Help,
    or another running shell if it has been terminated
    """
    if not hasattr(self.shell, "get_doc") or (
        hasattr(self.shell, "is_running") and not self.shell.is_running()
    ):
        self.shell = None
        if self.main.ipyconsole is not None:
            shell = self.main.ipyconsole.get_current_shellwidget()
            if shell is not None and shell.kernel_client is not None:
                self.shell = shell
        if self.shell is None:
            self.shell = self.internal_shell
    return self.shell
# Buggy code
def render_sphinx_doc(self, doc, context=None):
    """Transform doc string dictionary to HTML and show it"""
    # Math rendering option could have changed
    if self.editor is not None:
        fname = self.editor.get_current_filename()
        dname = osp.dirname(fname)
    else:
        dname = ""
    self._sphinx_thread.render(doc, context, self.get_option("math"), dname)


# Traceback (AttributeError)
File "/home/parichay/code/env/spyder3/lib/python3.5/site-packages/spyder/plugins/configdialog.py", line 223, in button_clicked
configpage.apply_changes()
File "/home/parichay/code/env/spyder3/lib/python3.5/site-packages/spyder/plugins/configdialog.py", line 104, in apply_changes
self.apply_callback()
File "/home/parichay/code/env/spyder3/lib/python3.5/site-packages/spyder/plugins/configdialog.py", line 269, in <lambda>
self.apply_settings(self.changed_options))
File "/home/parichay/code/env/spyder3/lib/python3.5/site-packages/spyder/plugins/configdialog.py", line 1187, in apply_settings
self.main.help.apply_plugin_settings(['color_scheme_name'])
File "/home/parichay/code/env/spyder3/lib/python3.5/site-packages/spyder/plugins/help.py", line 552, in apply_plugin_settings
self.editor.apply_plugin_settings(options=[connect_n])
AttributeError: 'NoneType' object has no attribute 'apply_plugin_settings'

# Fixed code
def render_sphinx_doc(self, doc, context=None):
    """Transform doc string dictionary to HTML and show it"""
    # Math rendering option could have changed
    if self.main.editor is not None:
        fname = self.main.editor.get_current_filename()
        dname = osp.dirname(fname)
    else:
        dname = ""
    self._sphinx_thread.render(doc, context, self.get_option("math"), dname)
# Buggy code
def setData(self, index, value, role=Qt.EditRole, change_type=None):
    """Cell content change"""
    column = index.column()
    row = index.row()

    if change_type is not None:
        try:
            value = self.data(index, role=Qt.DisplayRole)
            val = from_qvariant(value, str)
            if change_type is bool:
                val = bool_false_check(val)
            self.df.iloc[row, column] = change_type(val)
        except ValueError:
            self.df.iloc[row, column] = change_type("0")
    else:
        val = from_qvariant(value, str)
        current_value = self.get_value(row, column)
        if isinstance(current_value, bool):
            val = bool_false_check(val)
        supported_types = (bool,) + REAL_NUMBER_TYPES + COMPLEX_NUMBER_TYPES
        if isinstance(current_value, supported_types) or is_text_string(current_value):
            try:
                self.df.iloc[row, column] = current_value.__class__(val)
            except ValueError as e:
                QMessageBox.critical(self.dialog, "Error", "Value error: %s" % str(e))
                return False
        else:
            QMessageBox.critical(
                self.dialog, "Error", "The type of the cell is not a supported type"
            )
            return False
    self.max_min_col_update()
    return True


# Traceback (OverflowError)
Traceback (most recent call last):
File "C:\Users\christopher.gerlach\Anaconda3\lib\site-packages\spyder\widgets\variableexplorer\arrayeditor.py", line 318, in setData
self.test_array[0] = val # will raise an Exception eventually
OverflowError: Python int too large to convert to C long

# Fixed code
def setData(self, index, value, role=Qt.EditRole, change_type=None):
    """Cell content change"""
    column = index.column()
    row = index.row()

    if change_type is not None:
        try:
            value = self.data(index, role=Qt.DisplayRole)
            val = from_qvariant(value, str)
            if change_type is bool:
                val = bool_false_check(val)
            self.df.iloc[row, column] = change_type(val)
        except ValueError:
            self.df.iloc[row, column] = change_type("0")
    else:
        val = from_qvariant(value, str)
        current_value = self.get_value(row, column)
        if isinstance(current_value, bool):
            val = bool_false_check(val)
        supported_types = (bool,) + REAL_NUMBER_TYPES + COMPLEX_NUMBER_TYPES
        if isinstance(current_value, supported_types) or is_text_string(current_value):
            try:
                self.df.iloc[row, column] = current_value.__class__(val)
            except (ValueError, OverflowError) as e:
                QMessageBox.critical(
                    self.dialog, "Error", str(type(e).__name__) + ": " + str(e)
                )
                return False
        else:
            QMessageBox.critical(
                self.dialog, "Error", "The type of the cell is not a supported type"
            )
            return False
    self.max_min_col_update()
    return True
# Buggy code
def setData(self, index, value, role=Qt.EditRole, change_type=None):
    """Cell content change"""
    column = index.column()
    row = index.row()

    if change_type is not None:
        try:
            value = self.data(index, role=Qt.DisplayRole)
            val = from_qvariant(value, str)
            if change_type is bool:
                val = bool_false_check(val)
            self.df.iloc[row, column - 1] = change_type(val)
        except ValueError:
            self.df.iloc[row, column - 1] = change_type("0")
    else:
        val = from_qvariant(value, str)
        current_value = self.get_value(row, column - 1)
        if isinstance(current_value, bool):
            val = bool_false_check(val)
        supported_types = (bool,) + REAL_NUMBER_TYPES + COMPLEX_NUMBER_TYPES
        if isinstance(current_value, supported_types) or is_text_string(current_value):
            try:
                self.df.iloc[row, column - 1] = current_value.__class__(val)
            except (ValueError, OverflowError) as e:
                QMessageBox.critical(self.dialog, "Error", str(type(e)) + ": " + str(e))
                return False
        else:
            QMessageBox.critical(
                self.dialog, "Error", "The type of the cell is not a supported type"
            )
            return False
    self.max_min_col_update()
    return True


# Traceback (OverflowError)
Traceback (most recent call last):
File "C:\Users\christopher.gerlach\Anaconda3\lib\site-packages\spyder\widgets\variableexplorer\arrayeditor.py", line 318, in setData
self.test_array[0] = val # will raise an Exception eventually
OverflowError: Python int too large to convert to C long

# Fixed code
def setData(self, index, value, role=Qt.EditRole, change_type=None):
    """Cell content change"""
    column = index.column()
    row = index.row()

    if change_type is not None:
        try:
            value = self.data(index, role=Qt.DisplayRole)
            val = from_qvariant(value, str)
            if change_type is bool:
                val = bool_false_check(val)
            self.df.iloc[row, column - 1] = change_type(val)
        except ValueError:
            self.df.iloc[row, column - 1] = change_type("0")
    else:
        val = from_qvariant(value, str)
        current_value = self.get_value(row, column - 1)
        if isinstance(current_value, bool):
            val = bool_false_check(val)
        supported_types = (bool,) + REAL_NUMBER_TYPES + COMPLEX_NUMBER_TYPES
        if isinstance(current_value, supported_types) or is_text_string(current_value):
            try:
                self.df.iloc[row, column - 1] = current_value.__class__(val)
            except (ValueError, OverflowError) as e:
                QMessageBox.critical(
                    self.dialog, "Error", str(type(e).__name__) + ": " + str(e)
                )
                return False
        else:
            QMessageBox.critical(
                self.dialog, "Error", "The type of the cell is not a supported type"
            )
            return False
    self.max_min_col_update()
    return True
# Buggy code
def __init__(self, *args, **kwargs):
    super(SpyderKernel, self).__init__(*args, **kwargs)

    self.namespace_view_settings = {}
    self._pdb_obj = None
    self._pdb_step = None
    self._do_publish_pdb_state = True

    kernel_config = self.config.get("IPKernelApp", None)
    if kernel_config is not None:
        cf = kernel_config["connection_file"]
        json_file = osp.basename(cf)
        self._kernel_id = json_file.split(".json")[0]
    else:
        self._kernel_id = None


# Traceback (ModuleNotFoundError)
Traceback (most recent call last):

File "<ipython-input-1-9701cca0214f>", line 1, in <module>
runfile('/home/mukundan/nextcloud/documents/programming/python/misc/plot_test.py', wdir='/home/mukundan/nextcloud/documents/programming/python/misc')

File "/usr/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 710, in runfile
execfile(filename, namespace)

File "/usr/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 101, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)

File "/home/mukundan/nextcloud/documents/programming/python/misc/plot_test.py", line 9, in <module>
import matplotlib.pyplot as plt

File "/usr/lib64/python3.6/site-packages/matplotlib/pyplot.py", line 115, in <module>
_backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup()

File "/usr/lib64/python3.6/site-packages/matplotlib/backends/__init__.py", line 32, in pylab_setup
globals(),locals(),[backend_name],0)

ModuleNotFoundError: No module named 'matplotlib.backends.backend_qt5agg'

# Fixed code
def __init__(self, *args, **kwargs):
    super(SpyderKernel, self).__init__(*args, **kwargs)

    self.namespace_view_settings = {}

    self._pdb_obj = None
    self._pdb_step = None
    self._do_publish_pdb_state = True
    self._mpl_backend_error = None

    kernel_config = self.config.get("IPKernelApp", None)
    if kernel_config is not None:
        cf = kernel_config["connection_file"]
        json_file = osp.basename(cf)
        self._kernel_id = json_file.split(".json")[0]
    else:
        self._kernel_id = None
# Buggy code
def get_syspath(self):
    """Return sys.path contents."""
    import sys

    return sys.path[:]


# Traceback (ModuleNotFoundError)
Traceback (most recent call last):

File "<ipython-input-1-9701cca0214f>", line 1, in <module>
runfile('/home/mukundan/nextcloud/documents/programming/python/misc/plot_test.py', wdir='/home/mukundan/nextcloud/documents/programming/python/misc')

File "/usr/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 710, in runfile
execfile(filename, namespace)

File "/usr/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 101, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)

File "/home/mukundan/nextcloud/documents/programming/python/misc/plot_test.py", line 9, in <module>
import matplotlib.pyplot as plt

File "/usr/lib64/python3.6/site-packages/matplotlib/pyplot.py", line 115, in <module>
_backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup()

File "/usr/lib64/python3.6/site-packages/matplotlib/backends/__init__.py", line 32, in pylab_setup
globals(),locals(),[backend_name],0)

ModuleNotFoundError: No module named 'matplotlib.backends.backend_qt5agg'

# Fixed code
def get_syspath(self):
    """Return sys.path contents."""
    return sys.path[:]
# Buggy code
def get_namespace_view(self):
    """
    Return the namespace view

    This is a dictionary with the following structure

    {'a': {'color': '#800000', 'size': 1, 'type': 'str', 'view': '1'}}

    Here:
    * 'a' is the variable name
    * 'color' is the color used to show it
    * 'size' and 'type' are self-evident
    * and'view' is its value or the text shown in the last column
    """
    settings = self.namespace_view_settings
    if settings:
        ns = self._get_current_namespace()
        view = make_remote_view(ns, settings, EXCLUDED_NAMES)
        return view


# Traceback (SyntaxError)
File "/home/biomike/anaconda2/lib/python2.7/site-packages/qtconsole/base_frontend_mixin.py", line 163, in _dispatch
Traceback (most recent call last):
File "/home/biomike/anaconda2/lib/python2.7/site-packages/qtconsole/base_frontend_mixin.py", line 163, in _dispatch
handler(msg)
File "/home/biomike/anaconda2/lib/python2.7/site-packages/spyder/widgets/ipythonconsole/namespacebrowser.py", line 214, in _handle_execute_reply
self.handle_exec_method(msg)
File "/home/biomike/anaconda2/lib/python2.7/site-packages/spyder/widgets/ipythonconsole/shell.py", line 317, in handle_exec_method
properties = ast.literal_eval(data['text/plain'])
File "/home/biomike/anaconda2/lib/python2.7/ast.py", line 49, in literal_eval
node_or_string = parse(node_or_string, mode='eval')
File "/home/biomike/anaconda2/lib/python2.7/ast.py", line 37, in parse
return compile(source, filename, mode, PyCF_ONLY_AST)
File "<unknown>", line 9001
...}
^
SyntaxError: invalid syntax
handler(msg)
File "/home/biomike/anaconda2/lib/python2.7/site-packages/spyder/widgets/ipythonconsole/namespacebrowser.py", line 214, in _handle_execute_reply
self.handle_exec_method(msg)
File "/home/biomike/anaconda2/lib/python2.7/site-packages/spyder/widgets/ipythonconsole/shell.py", line 311, in handle_exec_method
view = ast.literal_eval(data['text/plain'])
File "/home/biomike/anaconda2/lib/python2.7/ast.py", line 49, in literal_eval
node_or_string = parse(node_or_string, mode='eval')
File "/home/biomike/anaconda2/lib/python2.7/ast.py", line 37, in parse
return compile(source, filename, mode, PyCF_ONLY_AST)
File "<unknown>", line 4001
...}
^
SyntaxError: invalid syntax

# Fixed code
def get_namespace_view(self):
    """
    Return the namespace view

    This is a dictionary with the following structure

    {'a': {'color': '#800000', 'size': 1, 'type': 'str', 'view': '1'}}

    Here:
    * 'a' is the variable name
    * 'color' is the color used to show it
    * 'size' and 'type' are self-evident
    * and'view' is its value or the text shown in the last column
    """
    settings = self.namespace_view_settings
    if settings:
        ns = self._get_current_namespace()
        view = repr(make_remote_view(ns, settings, EXCLUDED_NAMES))
        return view
    else:
        return repr(None)
# Buggy code
def refresh_from_pdb(self, pdb_state):
    """
    Refresh Variable Explorer and Editor from a Pdb session,
    after running any pdb command.

    See publish_pdb_state in utils/ipython/spyder_kernel.py and
    notify_spyder in utils/site/sitecustomize.py and
    """
    if "step" in pdb_state and "fname" in pdb_state["step"]:
        fname = pdb_state["step"]["fname"]
        lineno = pdb_state["step"]["lineno"]
        self.sig_pdb_step.emit(fname, lineno)

    if "namespace_view" in pdb_state:
        self.sig_namespace_view.emit(pdb_state["namespace_view"])

    if "var_properties" in pdb_state:
        self.sig_var_properties.emit(pdb_state["var_properties"])


# Traceback (SyntaxError)
File "/home/biomike/anaconda2/lib/python2.7/site-packages/qtconsole/base_frontend_mixin.py", line 163, in _dispatch
Traceback (most recent call last):
File "/home/biomike/anaconda2/lib/python2.7/site-packages/qtconsole/base_frontend_mixin.py", line 163, in _dispatch
handler(msg)
File "/home/biomike/anaconda2/lib/python2.7/site-packages/spyder/widgets/ipythonconsole/namespacebrowser.py", line 214, in _handle_execute_reply
self.handle_exec_method(msg)
File "/home/biomike/anaconda2/lib/python2.7/site-packages/spyder/widgets/ipythonconsole/shell.py", line 317, in handle_exec_method
properties = ast.literal_eval(data['text/plain'])
File "/home/biomike/anaconda2/lib/python2.7/ast.py", line 49, in literal_eval
node_or_string = parse(node_or_string, mode='eval')
File "/home/biomike/anaconda2/lib/python2.7/ast.py", line 37, in parse
return compile(source, filename, mode, PyCF_ONLY_AST)
File "<unknown>", line 9001
...}
^
SyntaxError: invalid syntax
handler(msg)
File "/home/biomike/anaconda2/lib/python2.7/site-packages/spyder/widgets/ipythonconsole/namespacebrowser.py", line 214, in _handle_execute_reply
self.handle_exec_method(msg)
File "/home/biomike/anaconda2/lib/python2.7/site-packages/spyder/widgets/ipythonconsole/shell.py", line 311, in handle_exec_method
view = ast.literal_eval(data['text/plain'])
File "/home/biomike/anaconda2/lib/python2.7/ast.py", line 49, in literal_eval
node_or_string = parse(node_or_string, mode='eval')
File "/home/biomike/anaconda2/lib/python2.7/ast.py", line 37, in parse
return compile(source, filename, mode, PyCF_ONLY_AST)
File "<unknown>", line 4001
...}
^
SyntaxError: invalid syntax

# Fixed code
def refresh_from_pdb(self, pdb_state):
    """
    Refresh Variable Explorer and Editor from a Pdb session,
    after running any pdb command.

    See publish_pdb_state in utils/ipython/spyder_kernel.py and
    notify_spyder in utils/site/sitecustomize.py and
    """
    if "step" in pdb_state and "fname" in pdb_state["step"]:
        fname = pdb_state["step"]["fname"]
        lineno = pdb_state["step"]["lineno"]
        self.sig_pdb_step.emit(fname, lineno)

    if "namespace_view" in pdb_state:
        self.sig_namespace_view.emit(ast.literal_eval(pdb_state["namespace_view"]))

    if "var_properties" in pdb_state:
        self.sig_var_properties.emit(ast.literal_eval(pdb_state["var_properties"]))
# Buggy code
def _get_len(self, var):
    """Return sequence length"""
    try:
        return len(var)
    except TypeError:
        return None


# Traceback (AttributeError)
In [2]: speedyo.hello_world()
Traceback (most recent call last):
File "<ipython-input-2-c923dc13a4b5>", line 1, in <module>
speedyo.hello_world()
File "C:/Users/Public/SVN_Workspace/ltc_2947_8_9/lab/python/axels.py", line 16, in hello_world
print('Hello world!')
File "C:/Users/Public/SVN_Workspace/ltc_2947_8_9/lab/python/axels.py", line 16, in hello_world
print('Hello world!')
File "c:\python27_64\lib\bdb.py", line 49, in trace_dispatch
return self.dispatch_line(frame)
File "c:\python27_64\lib\bdb.py", line 67, in dispatch_line
self.user_line(frame)
File "c:\python27_64\lib\pdb.py", line 158, in user_line
self.interaction(frame, None)
File "c:\python27_64\lib\site-packages\spyder\utils\site\sitecustomize.py", line 414, in interaction
self.notify_spyder(frame)
File "c:\python27_64\lib\site-packages\spyder\utils\site\sitecustomize.py", line 352, in notify_spyder
ipython_shell.kernel.publish_pdb_state()
File "c:\python27_64\lib\site-packages\spyder\utils\ipython\spyder_kernel.py", line 219, in publish_pdb_state
var_properties = self.get_var_properties(),
File "c:\python27_64\lib\site-packages\spyder\utils\ipython\spyder_kernel.py", line 132, in get_var_properties
'len': self._get_len(value),
File "c:\python27_64\lib\site-packages\spyder\utils\ipython\spyder_kernel.py", line 322, in _get_len
return len(var)
AttributeError: _Feature instance has no attribute '__len__'

# Fixed code
def _get_len(self, var):
    """Return sequence length"""
    try:
        return len(var)
    except:
        return None
# Buggy code
def _get_array_shape(self, var):
    """Return array's shape"""
    try:
        if self._is_array(var):
            return var.shape
        else:
            return None
    except AttributeError:
        return None


# Traceback (AttributeError)
In [2]: speedyo.hello_world()
Traceback (most recent call last):
File "<ipython-input-2-c923dc13a4b5>", line 1, in <module>
speedyo.hello_world()
File "C:/Users/Public/SVN_Workspace/ltc_2947_8_9/lab/python/axels.py", line 16, in hello_world
print('Hello world!')
File "C:/Users/Public/SVN_Workspace/ltc_2947_8_9/lab/python/axels.py", line 16, in hello_world
print('Hello world!')
File "c:\python27_64\lib\bdb.py", line 49, in trace_dispatch
return self.dispatch_line(frame)
File "c:\python27_64\lib\bdb.py", line 67, in dispatch_line
self.user_line(frame)
File "c:\python27_64\lib\pdb.py", line 158, in user_line
self.interaction(frame, None)
File "c:\python27_64\lib\site-packages\spyder\utils\site\sitecustomize.py", line 414, in interaction
self.notify_spyder(frame)
File "c:\python27_64\lib\site-packages\spyder\utils\site\sitecustomize.py", line 352, in notify_spyder
ipython_shell.kernel.publish_pdb_state()
File "c:\python27_64\lib\site-packages\spyder\utils\ipython\spyder_kernel.py", line 219, in publish_pdb_state
var_properties = self.get_var_properties(),
File "c:\python27_64\lib\site-packages\spyder\utils\ipython\spyder_kernel.py", line 132, in get_var_properties
'len': self._get_len(value),
File "c:\python27_64\lib\site-packages\spyder\utils\ipython\spyder_kernel.py", line 322, in _get_len
return len(var)
AttributeError: _Feature instance has no attribute '__len__'

# Fixed code
def _get_array_shape(self, var):
    """Return array's shape"""
    try:
        if self._is_array(var):
            return var.shape
        else:
            return None
    except:
        return None
# Buggy code
def _get_array_ndim(self, var):
    """Return array's ndim"""
    try:
        if self._is_array(var):
            return var.ndim
        else:
            return None
    except AttributeError:
        return None


# Traceback (AttributeError)
In [2]: speedyo.hello_world()
Traceback (most recent call last):
File "<ipython-input-2-c923dc13a4b5>", line 1, in <module>
speedyo.hello_world()
File "C:/Users/Public/SVN_Workspace/ltc_2947_8_9/lab/python/axels.py", line 16, in hello_world
print('Hello world!')
File "C:/Users/Public/SVN_Workspace/ltc_2947_8_9/lab/python/axels.py", line 16, in hello_world
print('Hello world!')
File "c:\python27_64\lib\bdb.py", line 49, in trace_dispatch
return self.dispatch_line(frame)
File "c:\python27_64\lib\bdb.py", line 67, in dispatch_line
self.user_line(frame)
File "c:\python27_64\lib\pdb.py", line 158, in user_line
self.interaction(frame, None)
File "c:\python27_64\lib\site-packages\spyder\utils\site\sitecustomize.py", line 414, in interaction
self.notify_spyder(frame)
File "c:\python27_64\lib\site-packages\spyder\utils\site\sitecustomize.py", line 352, in notify_spyder
ipython_shell.kernel.publish_pdb_state()
File "c:\python27_64\lib\site-packages\spyder\utils\ipython\spyder_kernel.py", line 219, in publish_pdb_state
var_properties = self.get_var_properties(),
File "c:\python27_64\lib\site-packages\spyder\utils\ipython\spyder_kernel.py", line 132, in get_var_properties
'len': self._get_len(value),
File "c:\python27_64\lib\site-packages\spyder\utils\ipython\spyder_kernel.py", line 322, in _get_len
return len(var)
AttributeError: _Feature instance has no attribute '__len__'

# Fixed code
def _get_array_ndim(self, var):
    """Return array's ndim"""
    try:
        if self._is_array(var):
            return var.ndim
        else:
            return None
    except:
        return None
# Buggy code
def hideEvent(self, event):
    """Reimplement Qt method"""
    for plugin in self.widgetlist:
        if plugin.isAncestorOf(self.last_focused_widget):
            plugin.visibility_changed(True)
    QMainWindow.hideEvent(self, event)


# Traceback (RuntimeError)
Traceback (most recent call last):
File "/usr/lib/python3.6/site-packages/spyder/app/mainwindow.py", line 2117, in hideEvent
if plugin.isAncestorOf(self.last_focused_widget):
RuntimeError: wrapped C/C++ object of type QPushButton has been deleted

# Fixed code
def hideEvent(self, event):
    """Reimplement Qt method"""
    try:
        for plugin in self.widgetlist:
            if plugin.isAncestorOf(self.last_focused_widget):
                plugin.visibility_changed(True)
        QMainWindow.hideEvent(self, event)
    except RuntimeError:
        QMainWindow.hideEvent(self, event)
# Buggy code
def register_plugin(self):
    """Register plugin in Spyder's main window"""
    self.focus_changed.connect(self.main.plugin_focus_changed)
    self.main.add_dockwidget(self)
    # Connecting the following signal once the dockwidget has been created:
    self.shell.traceback_available.connect(self.traceback_available)


# Traceback (NameError)
Traceback (most recent call last):
File "/home/jitse/misc/spyder/spyder/plugins/ipythonconsole.py", line 955, in <lambda>
kc.started_channels.connect(lambda c=client: self.process_started(c))
File "/home/jitse/misc/spyder/spyder/plugins/ipythonconsole.py", line 1387, in process_started
self.variableexplorer.add_shellwidget(client.shellwidget)
File "/home/jitse/misc/spyder/spyder/plugins/variableexplorer.py", line 143, in add_shellwidget
nsb = NamespaceBrowser(self)
File "/home/jitse/misc/spyder/spyder/widgets/variableexplorer/namespacebrowser.py", line 65, in __init__
QWdget.__init__(self, parent)
NameError: name 'QWdget' is not defined

# Fixed code
def register_plugin(self):
    """Register plugin in Spyder's main window"""
    self.focus_changed.connect(self.main.plugin_focus_changed)
    self.main.add_dockwidget(self)
    # Connecting the following signal once the dockwidget has been created:
    self.shell.exception_occurred.connect(self.exception_occurred)
# Buggy code
def debug_file(self):
    """Debug current script"""
    self.run_file(debug=True)


# Traceback (RuntimeError)
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 459, in \<lambda>
lambda eid=id(editor): self.editor_accepted(eid))
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 467, in editor_accepted
index = data['model'].get_index_from_key(data['key'])
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 219, in get_index_from_key
return self.createIndex(self.keys.index(key), 0)
RuntimeError: wrapped C/C++ object of type DictModel has been deleted

# Fixed code
def debug_file(self):
    """Debug current script"""
    self.run_file(debug=True)
    # Fixes 2034
    editor = self.get_current_editor()
    if editor.get_breakpoints():
        time.sleep(0.5)
        self.debug_command("continue")
# Buggy code
def execute_code(self, lines, clear_variables=False):
    """Execute code instructions."""
    sw = self.get_current_shellwidget()
    if sw is not None:
        if clear_variables:
            sw.reset_namespace(force=True)
        sw.execute(to_text_string(lines))
        self.activateWindow()
        self.get_current_client().get_control().setFocus()


# Traceback (RuntimeError)
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 459, in \<lambda>
lambda eid=id(editor): self.editor_accepted(eid))
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 467, in editor_accepted
index = data['model'].get_index_from_key(data['key'])
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 219, in get_index_from_key
return self.createIndex(self.keys.index(key), 0)
RuntimeError: wrapped C/C++ object of type DictModel has been deleted

# Fixed code
def execute_code(self, lines, clear_variables=False):
    """Execute code instructions."""
    sw = self.get_current_shellwidget()
    if sw is not None:
        if sw._reading:
            pass
        else:
            if clear_variables:
                sw.reset_namespace(force=True)
            sw.execute(to_text_string(to_text_string(lines)))
        self.activateWindow()
        self.get_current_client().get_control().setFocus()
# Buggy code
def __init__(self, *args, **kwargs):
    super(SpyderKernel, self).__init__(*args, **kwargs)

    self.namespace_view_settings = {}
    self._pdb_obj = None
    self._pdb_step = None


# Traceback (RuntimeError)
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 459, in \<lambda>
lambda eid=id(editor): self.editor_accepted(eid))
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 467, in editor_accepted
index = data['model'].get_index_from_key(data['key'])
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 219, in get_index_from_key
return self.createIndex(self.keys.index(key), 0)
RuntimeError: wrapped C/C++ object of type DictModel has been deleted

# Fixed code
def __init__(self, *args, **kwargs):
    super(SpyderKernel, self).__init__(*args, **kwargs)

    self.namespace_view_settings = {}
    self._pdb_obj = None
    self._pdb_step = None

    kernel_config = self.config.get("IPKernelApp", None)
    if kernel_config is not None:
        cf = kernel_config["connection_file"]
        json_file = osp.basename(cf)
        self._kernel_id = json_file.split(".json")[0]
    else:
        self._kernel_id = None
# Buggy code
def get_value(self, name):
    """Get the value of a variable"""
    ns = self._get_current_namespace()
    value = ns[name]
    publish_data({"__spy_data__": value})


# Traceback (RuntimeError)
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 459, in \<lambda>
lambda eid=id(editor): self.editor_accepted(eid))
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 467, in editor_accepted
index = data['model'].get_index_from_key(data['key'])
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 219, in get_index_from_key
return self.createIndex(self.keys.index(key), 0)
RuntimeError: wrapped C/C++ object of type DictModel has been deleted

# Fixed code
def get_value(self, name):
    """Get the value of a variable"""
    ns = self._get_current_namespace()
    value = ns[name]
    try:
        publish_data({"__spy_data__": value})
    except:
        # * There is no need to inform users about
        #   these errors.
        # * value = None makes Spyder to ignore
        #   petitions to display a value
        value = None
        publish_data({"__spy_data__": value})
# Buggy code
def notify_spyder(self, frame):
    if not frame:
        return
    fname = self.canonic(frame.f_code.co_filename)
    if PY2:
        try:
            fname = unicode(fname, "utf-8")
        except TypeError:
            pass
    lineno = frame.f_lineno
    if isinstance(fname, basestring) and isinstance(lineno, int):
        if osp.isfile(fname):
            if IS_IPYKERNEL:
                from IPython.core.getipython import get_ipython

                ipython_shell = get_ipython()
                if ipython_shell:
                    step = dict(fname=fname, lineno=lineno)
                    ipython_shell.kernel._pdb_step = step
            elif monitor is not None:
                monitor.notify_pdb_step(fname, lineno)
                time.sleep(0.1)


# Traceback (RuntimeError)
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 459, in \<lambda>
lambda eid=id(editor): self.editor_accepted(eid))
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 467, in editor_accepted
index = data['model'].get_index_from_key(data['key'])
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 219, in get_index_from_key
return self.createIndex(self.keys.index(key), 0)
RuntimeError: wrapped C/C++ object of type DictModel has been deleted

# Fixed code
def notify_spyder(self, frame):
    if not frame:
        return

    if IS_IPYKERNEL:
        from IPython.core.getipython import get_ipython

        ipython_shell = get_ipython()
    else:
        ipython_shell = None

    # Get filename and line number of the current frame
    fname = self.canonic(frame.f_code.co_filename)
    if PY2:
        try:
            fname = unicode(fname, "utf-8")
        except TypeError:
            pass
    lineno = frame.f_lineno

    # Set step of the current frame (if any)
    step = {}
    if isinstance(fname, basestring) and isinstance(lineno, int):
        if osp.isfile(fname):
            if ipython_shell:
                step = dict(fname=fname, lineno=lineno)
            elif monitor is not None:
                monitor.notify_pdb_step(fname, lineno)
                time.sleep(0.1)

    # Publish Pdb state so we can update the Variable Explorer
    # and the Editor on the Spyder side
    if ipython_shell:
        ipython_shell.kernel._pdb_step = step
        ipython_shell.kernel.publish_pdb_state()
# Buggy code
def interaction(self, frame, traceback):
    self.setup(frame, traceback)
    if self.send_initial_notification:
        self.notify_spyder(frame)  # -----Spyder-specific-----------------------
    self.print_stack_entry(self.stack[self.curindex])
    self.cmdloop()
    self.forget()


# Traceback (RuntimeError)
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 459, in \<lambda>
lambda eid=id(editor): self.editor_accepted(eid))
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 467, in editor_accepted
index = data['model'].get_index_from_key(data['key'])
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 219, in get_index_from_key
return self.createIndex(self.keys.index(key), 0)
RuntimeError: wrapped C/C++ object of type DictModel has been deleted

# Fixed code
def interaction(self, frame, traceback):
    self.setup(frame, traceback)
    if self.send_initial_notification:
        self.notify_spyder(frame)
    self.print_stack_entry(self.stack[self.curindex])
    self._cmdloop()
    self.forget()
# Buggy code
def stderr_file(self):
    """Filename to save kernel stderr output."""
    json_file = osp.basename(self.connection_file)
    stderr_file = json_file.split("json")[0] + "stderr"
    stderr_file = osp.join(TEMPDIR, stderr_file)
    return stderr_file


# Traceback (RuntimeError)
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 459, in \<lambda>
lambda eid=id(editor): self.editor_accepted(eid))
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 467, in editor_accepted
index = data['model'].get_index_from_key(data['key'])
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 219, in get_index_from_key
return self.createIndex(self.keys.index(key), 0)
RuntimeError: wrapped C/C++ object of type DictModel has been deleted

# Fixed code
def stderr_file(self):
    """Filename to save kernel stderr output."""
    if self.connection_file is not None:
        stderr_file = self.kernel_id + ".stderr"
        stderr_file = osp.join(TEMPDIR, stderr_file)
        return stderr_file