gurudesh/pytracebugs huggingface dataset:
# Buggy code
def refresh_plugin(self):
    """Refresh tabwidget"""
    client = None
    if self.tabwidget.count():
        # Give focus to the control widget of the selected tab
        client = self.tabwidget.currentWidget()
        control = client.get_control()
        control.setFocus()
        widgets = client.get_toolbar_buttons() + [5]
    else:
        control = None
        widgets = []
    self.find_widget.set_editor(control)
    self.tabwidget.set_corner_widgets({Qt.TopRightCorner: widgets})
    if client:
        sw = client.shellwidget
        self.variableexplorer.set_shellwidget_from_id(id(sw))
        self.help.set_shell(sw)
    self.main.last_console_plugin_focus_was_python = False
    self.update_plugin_title.emit()


# Traceback (IndexError)
import tensorflow
Traceback (most recent call last):

File "<ipython-input-1-a649b509054f>", line 1, in <module>
import tensorflow

File "/usr/local/lib/python2.7/dist-packages/tensorflow/__init__.py", line 24, in <module>
from tensorflow.python import *

File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/__init__.py", line 100, in <module>
from tensorflow.python.platform import app

File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/platform/app.py", line 23, in <module>
from tensorflow.python.platform import flags

File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/platform/flags.py", line 25, in <module>
_global_parser = _argparse.ArgumentParser()

File "/usr/lib/python2.7/argparse.py", line 1586, in __init__
prog = _os.path.basename(_sys.argv[0])

IndexError: list index out of range

# Fixed code
def refresh_plugin(self):
    """Refresh tabwidget"""
    client = None
    if self.tabwidget.count():
        # Give focus to the control widget of the selected tab
        client = self.tabwidget.currentWidget()
        control = client.get_control()
        control.setFocus()
        widgets = client.get_toolbar_buttons() + [5]
    else:
        control = None
        widgets = []
    self.find_widget.set_editor(control)
    self.tabwidget.set_corner_widgets({Qt.TopRightCorner: widgets})
    if client and not self.testing:
        sw = client.shellwidget
        self.variableexplorer.set_shellwidget_from_id(id(sw))
        self.help.set_shell(sw)
    if not self.testing:
        self.main.last_console_plugin_focus_was_python = False
    self.update_plugin_title.emit()
# Buggy code
def create_kernel_manager_and_kernel_client(self, connection_file, stderr_file):
    """Create kernel manager and client."""
    # Kernel manager
    kernel_manager = QtKernelManager(
        connection_file=connection_file, config=None, autorestart=True
    )
    kernel_manager._kernel_spec = self.create_kernel_spec()

    # Save stderr in a file to read it later in case of errors
    stderr = codecs.open(stderr_file, "w", encoding="utf-8")
    kernel_manager.start_kernel(stderr=stderr)

    # Kernel client
    kernel_client = kernel_manager.client()

    # Increase time to detect if a kernel is alive
    # See Issue 3444
    kernel_client.hb_channel.time_to_dead = 6.0

    return kernel_manager, kernel_client


# Traceback (IndexError)
import tensorflow
Traceback (most recent call last):

File "<ipython-input-1-a649b509054f>", line 1, in <module>
import tensorflow

File "/usr/local/lib/python2.7/dist-packages/tensorflow/__init__.py", line 24, in <module>
from tensorflow.python import *

File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/__init__.py", line 100, in <module>
from tensorflow.python.platform import app

File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/platform/app.py", line 23, in <module>
from tensorflow.python.platform import flags

File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/platform/flags.py", line 25, in <module>
_global_parser = _argparse.ArgumentParser()

File "/usr/lib/python2.7/argparse.py", line 1586, in __init__
prog = _os.path.basename(_sys.argv[0])

IndexError: list index out of range

# Fixed code
def create_kernel_manager_and_kernel_client(self, connection_file, stderr_file):
    """Create kernel manager and client."""
    # Kernel manager
    kernel_manager = QtKernelManager(
        connection_file=connection_file, config=None, autorestart=True
    )
    kernel_manager._kernel_spec = self.create_kernel_spec()

    # Save stderr in a file to read it later in case of errors
    if not self.testing:
        stderr = codecs.open(stderr_file, "w", encoding="utf-8")
        kernel_manager.start_kernel(stderr=stderr)
    else:
        kernel_manager.start_kernel()

    # Kernel client
    kernel_client = kernel_manager.client()

    # Increase time to detect if a kernel is alive
    # See Issue 3444
    kernel_client.hb_channel.time_to_dead = 6.0

    return kernel_manager, kernel_client
# Buggy code
def refresh_plugin(self):
    """Refresh tabwidget"""
    client = None
    if self.tabwidget.count():
        # Give focus to the control widget of the selected tab
        client = self.tabwidget.currentWidget()
        control = client.get_control()
        control.setFocus()
        widgets = client.get_toolbar_buttons() + [5]
    else:
        control = None
        widgets = []
    self.find_widget.set_editor(control)
    self.tabwidget.set_corner_widgets({Qt.TopRightCorner: widgets})
    if client:
        sw = client.shellwidget
        self.variableexplorer.set_shellwidget_from_id(id(sw))
        self.help.set_shell(sw)
    self.main.last_console_plugin_focus_was_python = False
    self.sig_update_plugin_title.emit()


# Traceback (IndexError)
import tensorflow
Traceback (most recent call last):

File "<ipython-input-1-a649b509054f>", line 1, in <module>
import tensorflow

File "/usr/local/lib/python2.7/dist-packages/tensorflow/__init__.py", line 24, in <module>
from tensorflow.python import *

File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/__init__.py", line 100, in <module>
from tensorflow.python.platform import app

File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/platform/app.py", line 23, in <module>
from tensorflow.python.platform import flags

File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/platform/flags.py", line 25, in <module>
_global_parser = _argparse.ArgumentParser()

File "/usr/lib/python2.7/argparse.py", line 1586, in __init__
prog = _os.path.basename(_sys.argv[0])

IndexError: list index out of range

# Fixed code
def refresh_plugin(self):
    """Refresh tabwidget"""
    client = None
    if self.tabwidget.count():
        # Give focus to the control widget of the selected tab
        client = self.tabwidget.currentWidget()
        control = client.get_control()
        control.setFocus()
        widgets = client.get_toolbar_buttons() + [5]
    else:
        control = None
        widgets = []
    self.find_widget.set_editor(control)
    self.tabwidget.set_corner_widgets({Qt.TopRightCorner: widgets})
    if client and not self.testing:
        sw = client.shellwidget
        self.variableexplorer.set_shellwidget_from_id(id(sw))
        self.help.set_shell(sw)
    if not self.testing:
        self.main.last_console_plugin_focus_was_python = False
    self.sig_update_plugin_title.emit()
# Buggy code
def reorder_filenames(self, filenames):
    """Take the last session filenames and put the last open on first.

    It takes a list of filenames and using the current filename from the
    layout settings, sets the one that had focused last in the position 0.
    It also reorders the current lines for each file (supposing that they
    are in the same order as the filenames) and sets them back in the
    layout settings.
    """
    layout = self.get_option("layout_settings", None)
    splitsettings = layout.get("splitsettings")
    index_first_file = 0
    reordered_splitsettings = []
    for index, (is_vertical, cfname, clines) in enumerate(splitsettings):
        # the first element of filenames is now the one that last had focus
        if index == 0:
            index_first_file = filenames.index(cfname)
            filenames.pop(index_first_file)
            filenames.insert(0, cfname)
        clines_0 = clines[0]
        clines.pop(index_first_file)
        clines.insert(0, clines_0)
        reordered_splitsettings.append((is_vertical, cfname, clines))
    layout["splitsettings"] = reordered_splitsettings
    self.set_option("layout_settings", layout)
    return filenames


# Traceback (ValueError)
Traceback (most recent call last):
File "/home/rlaverde/code/spyder/spyder/plugins/projects.py", line 144, in <lambda>
lambda v: self.editor.setup_open_files())
File "/home/rlaverde/code/spyder/spyder/plugins/editor.py", line 2635, in setup_open_files
filenames = self.reorder_filenames(filenames)
File "/home/rlaverde/code/spyder/spyder/plugins/editor.py", line 2667, in reorder_filenames
index_first_file = filenames.index(cfname)
ValueError: '/home/rlaverde/code/spyder/spyder/widgets/panels/scrollflag.py' is not in list

# Fixed code
def reorder_filenames(self, filenames):
    """Take the last session filenames and put the last open on first.

    It takes a list of filenames and using the current filename from the
    layout settings, sets the one that had focused last in the position 0.
    It also reorders the current lines for each file (supposing that they
    are in the same order as the filenames) and sets them back in the
    layout settings.
    """
    layout = self.get_option("layout_settings", None)
    splitsettings = layout.get("splitsettings")
    index_first_file = 0
    reordered_splitsettings = []
    for index, (is_vertical, cfname, clines) in enumerate(splitsettings):
        # the first element of filenames is now the one that last had focus
        if index == 0:
            if cfname in filenames:
                index_first_file = filenames.index(cfname)
                filenames.pop(index_first_file)
                filenames.insert(0, cfname)
            else:
                cfname = filenames[0]
                index_first_file = 0
        if index_first_file != 0:
            clines_0 = clines[0]
            clines.pop(index_first_file)
            clines.insert(0, clines_0)
        reordered_splitsettings.append((is_vertical, cfname, clines))
    layout["splitsettings"] = reordered_splitsettings
    self.set_option("layout_settings", layout)
    return filenames
# Buggy code
def execute_code(self, lines, clear_variables):
    """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 (TypeError)
Traceback (most recent call last):
File "C:\dev\packages\spyder\spyder\app\mainwindow.py", line 2415, in execute_in_external_console
console.execute_code(lines)
TypeError: execute_code() missing 1 required positional argument: 'clear_variables'

# Fixed 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()
# Buggy code
def toggle_hscrollbar(self, checked):
    """Toggle horizontal scrollbar"""
    self.parent_widget.sig_option_changed.emit("show_hscrollbar", checked)
    self.show_hscrollbar = checked
    self.header().setStretchLastSection(not checked)
    self.header().setHorizontalScrollMode(QAbstractItemView.ScrollPerPixel)
    if PYQT5:
        self.header().setSectionResizeMode(QHeaderView.ResizeToContents)
    else:
        self.header().setResizeMode(QHeaderView.ResizeToContents)


# Traceback (Exception)
File "/home/developer/.virtualenvs/dev3/lib/python3.5/site-packages/spyder/app/mainwindow.py", line 3001, in main
mainwindow = run_spyder(app, options, args)
File "/home/developer/.virtualenvs/dev3/lib/python3.5/site-packages/spyder/app/mainwindow.py", line 2905, in run_spyder
main.setup()
File "/home/developer/.virtualenvs/dev3/lib/python3.5/site-packages/spyder/app/mainwindow.py", line 869, in setup
self.projects = Projects(self)
File "/home/developer/.virtualenvs/dev3/lib/python3.5/site-packages/spyder/plugins/projects.py", line 71, in init
self.setup_project(self.get_active_project_path())
File "/home/developer/.virtualenvs/dev3/lib/python3.5/site-packages/spyder/widgets/projects/explorer.py", line 226, in setup_project
show_all=self.show_all)
File "/home/developer/.virtualenvs/dev3/lib/python3.5/site-packages/spyder/widgets/explorer.py", line 195, in setup
self.common_actions = self.setup_common_actions()
File "/home/developer/.virtualenvs/dev3/lib/python3.5/site-packages/spyder/widgets/projects/explorer.py", line 55, in setup_common_actions
self.toggle_hscrollbar(self.show_hscrollbar)
File "/home/developer/.virtualenvs/dev3/lib/python3.5/site-packages/spyder/widgets/projects/explorer.py", line 70, in toggle_hscrollbar
self.header().setResizeMode(QHeaderView.ResizeToContents)
File "/home/developer/.virtualenvs/dev3/lib/python3.5/site-packages/qtpy/_patch/qheaderview.py", line 83, in setResizeMode
raise Exception('setResizeMode is only available in Qt4. Use '
Exception: setResizeMode is only available in Qt4. Use setSectionResizeMode instead.

# Fixed code
def toggle_hscrollbar(self, checked):
    """Toggle horizontal scrollbar"""
    self.parent_widget.sig_option_changed.emit("show_hscrollbar", checked)
    self.show_hscrollbar = checked
    self.header().setStretchLastSection(not checked)
    self.header().setHorizontalScrollMode(QAbstractItemView.ScrollPerPixel)
    try:
        self.header().setSectionResizeMode(QHeaderView.ResizeToContents)
    except:  # support for qtpy<1.2.0
        self.header().setResizeMode(QHeaderView.ResizeToContents)
# Buggy code
def restart(self):
    """
    Restart the console

    This is needed when we switch projects to update PYTHONPATH
    and the selected interpreter
    """
    self.master_clients = 0
    self.create_new_client_if_empty = False
    for i in range(len(self.clients)):
        client = self.clients[-1]
        client.shutdown()
        self.close_client(client=client, force=True)
    self.create_new_client(give_focus=False)
    self.create_new_client_if_empty = True


# Traceback (AttributeError)
Traceback (most recent call last):
File "/usr/local/lib/python3.5/site-packages/spyder/plugins/projects.py", line 226, in create_new_project
self.restart_consoles()
File "/usr/local/lib/python3.5/site-packages/spyder/plugins/projects.py", line 385, in restart_consoles
self.main.ipyconsole.restart()
File "/usr/local/lib/python3.5/site-packages/spyder/plugins/ipythonconsole.py", line 1165, in restart
client.shutdown()
File "/usr/local/lib/python3.5/site-packages/spyder/widgets/ipythonconsole/client.py", line 300, in shutdown
self.shellwidget.kernel_manager.shutdown_kernel()
File "/usr/local/lib/python3.5/site-packages/jupyter_client/manager.py", line 302, in shutdown_kernel
self.request_shutdown(restart=restart)
File "/usr/local/lib/python3.5/site-packages/jupyter_client/manager.py", line 252, in request_shutdown
self.session.send(self._control_socket, msg)
File "/usr/local/lib/python3.5/site-packages/jupyter_client/session.py", line 684, in send
stream.send_multipart(to_send, copy=copy)
AttributeError: 'NoneType' object has no attribute 'send_multipart'

# Fixed code
def restart(self):
    """
    Restart the console

    This is needed when we switch projects to update PYTHONPATH
    and the selected interpreter
    """
    self.master_clients = 0
    self.create_new_client_if_empty = False
    for i in range(len(self.clients)):
        client = self.clients[-1]
        try:
            client.shutdown()
        except Exception as e:
            QMessageBox.warning(
                self,
                _("Warning"),
                _(
                    "It was not possible to restart the IPython console "
                    "when switching to this project. "
                    "The error was {0}".format(e)
                ),
                QMessageBox.Ok,
            )
        self.close_client(client=client, force=True)
    self.create_new_client(give_focus=False)
    self.create_new_client_if_empty = True
# Buggy code
def _handle_execute_reply(self, msg):
    """
    Reimplemented to handle communications between Spyder
    and the kernel
    """
    msg_id = msg["parent_header"]["msg_id"]
    info = self._request_info["execute"].get(msg_id)
    # unset reading flag, because if execute finished, raw_input can't
    # still be pending.
    self._reading = False

    # Refresh namespacebrowser after the kernel starts running
    exec_count = msg["content"]["execution_count"]
    if exec_count == 0 and self._kernel_is_starting:
        self.set_namespace_view_settings()
        self.refresh_namespacebrowser()
        self._kernel_is_starting = False

    # Handle silent execution of kernel methods
    if info and info.kind == "silent_exec_method" and not self._hidden:
        self.handle_exec_method(msg)
        self._request_info["execute"].pop(msg_id)
    else:
        super(NamepaceBrowserWidget, self)._handle_execute_reply(msg)


# Traceback (AttributeError)
Spyder Internal Console

This console is used to report application
internal errors and to inspect Spyder
internals with the following commands:
spy.app, spy.window, dir(spy)

Please don't use it to run your code

WARNING:traitlets:kernel died: 3.0032799243927
Traceback (most recent call last):
File "/Users/HWJ/anaconda3/lib/python3.5/site-packages/qtconsole/base_frontend_mixin.py", line 163, in _dispatch
handler(msg)
File "/Users/HWJ/anaconda3/lib/python3.5/site-packages/spyder/widgets/ipythonconsole/namespacebrowser.py", line 182, in _handle_execute_reply
self.set_namespace_view_settings()
File "/Users/HWJ/anaconda3/lib/python3.5/site-packages/spyder/widgets/ipythonconsole/namespacebrowser.py", line 68, in set_namespace_view_settings
settings = to_text_string(self.namespacebrowser.get_view_settings())
AttributeError: 'NoneType' object has no attribute 'get_view_settings'

# Fixed code
def _handle_execute_reply(self, msg):
    """
    Reimplemented to handle communications between Spyder
    and the kernel
    """
    msg_id = msg["parent_header"]["msg_id"]
    info = self._request_info["execute"].get(msg_id)
    # unset reading flag, because if execute finished, raw_input can't
    # still be pending.
    self._reading = False

    # Refresh namespacebrowser after the kernel starts running
    exec_count = msg["content"]["execution_count"]
    if exec_count == 0 and self._kernel_is_starting:
        if self.namespacebrowser is not None:
            self.set_namespace_view_settings()
            self.refresh_namespacebrowser()
        self._kernel_is_starting = False

    # Handle silent execution of kernel methods
    if info and info.kind == "silent_exec_method" and not self._hidden:
        self.handle_exec_method(msg)
        self._request_info["execute"].pop(msg_id)
    else:
        super(NamepaceBrowserWidget, self)._handle_execute_reply(msg)
# Buggy code
def keyPressEvent(self, event):
    """Reimplement Qt Method - Basic keypress event handler"""
    event, text, key, ctrl, shift = restore_keyevent(event)
    if key == Qt.Key_Question and not self.has_selected_text():
        self._key_question(text, force=True)
    elif key == Qt.Key_ParenLeft and not self.has_selected_text() and self.help_enabled:
        self._key_question(text)
    else:
        # Let the parent widget handle the key press event
        QTextEdit.keyPressEvent(self, event)


# Traceback (TypeError)
Traceback (most recent call last):
File "C:\Python\lib\site-packages\qtconsole\base_frontend_mixin.py", line 163, in _dispatch
handler(msg)
File "C:\dev\packages\spyder\spyder\widgets\ipythonconsole\namespacebrowser.py", line 188, in _handle_execute_reply
self.handle_exec_method(msg)
File "C:\dev\packages\spyder\spyder\widgets\ipythonconsole\shell.py", line 229, in handle_exec_method
self._kernel_reply = ast.literal_eval(data['text/plain'])
TypeError: 'NoneType' object is not subscriptable

# Fixed code
def keyPressEvent(self, event):
    """Reimplement Qt Method - Basic keypress event handler"""
    event, text, key, ctrl, shift = restore_keyevent(event)
    if key == Qt.Key_ParenLeft and not self.has_selected_text() and self.help_enabled:
        self._key_paren_left(text)
    else:
        # Let the parent widget handle the key press event
        QTextEdit.keyPressEvent(self, event)
# Buggy code
def _post_exec_input(self, line):
    """Commands to be run after writing to stdin"""
    pdb_commands = ["next", "continue", "step", "return"]
    if any([x == line for x in pdb_commands]):
        # To open the file where the current pdb frame points to
        self.silent_exec_input("!get_ipython().kernel.get_pdb_step()")

        # To refresh the Variable Explorer
        self.silent_exec_input("!get_ipython().kernel.get_namespace_view()")
        self.silent_exec_input("!get_ipython().kernel.get_var_properties()")


# Traceback (TypeError)
Traceback (most recent call last):
File "C:\Python\lib\site-packages\qtconsole\base_frontend_mixin.py", line 163, in _dispatch
handler(msg)
File "C:\dev\packages\spyder\spyder\widgets\ipythonconsole\namespacebrowser.py", line 188, in _handle_execute_reply
self.handle_exec_method(msg)
File "C:\dev\packages\spyder\spyder\widgets\ipythonconsole\shell.py", line 229, in handle_exec_method
self._kernel_reply = ast.literal_eval(data['text/plain'])
TypeError: 'NoneType' object is not subscriptable

# Fixed code
def _post_exec_input(self, line):
    """Commands to be run after writing to stdin"""
    if self._reading:
        pdb_commands = ["next", "continue", "step", "return"]
        if any([x == line for x in pdb_commands]):
            # To open the file where the current pdb frame points to
            self.silent_exec_input("!get_ipython().kernel.get_pdb_step()")

            # To refresh the Variable Explorer
            self.silent_exec_input("!get_ipython().kernel.get_namespace_view()")
            self.silent_exec_input("!get_ipython().kernel.get_var_properties()")
# Buggy code
def get_value(self, name):
    """Ask kernel for a value"""
    # Don't ask for values while reading (ipdb) is active
    if self._reading:
        raise ValueError(
            _(
                "Inspecting and setting values while debugging "
                "in IPython consoles is not supported yet by "
                "Spyder."
            )
        )

    # Wait until the kernel returns the value
    wait_loop = QEventLoop()
    self.sig_get_value.connect(wait_loop.quit)
    self.silent_execute("get_ipython().kernel.get_value('%s')" % name)
    wait_loop.exec_()

    # Remove loop connection and loop
    self.sig_get_value.disconnect(wait_loop.quit)
    wait_loop = None

    # Handle exceptions
    if self._kernel_value is None:
        if self._kernel_reply:
            msg = self._kernel_reply[:]
            self._kernel_reply = None
            raise ValueError(msg)

    return self._kernel_value


# Traceback (TypeError)
Traceback (most recent call last):
File "C:\Python\lib\site-packages\qtconsole\base_frontend_mixin.py", line 163, in _dispatch
handler(msg)
File "C:\dev\packages\spyder\spyder\widgets\ipythonconsole\namespacebrowser.py", line 188, in _handle_execute_reply
self.handle_exec_method(msg)
File "C:\dev\packages\spyder\spyder\widgets\ipythonconsole\shell.py", line 229, in handle_exec_method
self._kernel_reply = ast.literal_eval(data['text/plain'])
TypeError: 'NoneType' object is not subscriptable

# Fixed code
def get_value(self, name):
    """Ask kernel for a value"""
    # Don't ask for values while reading (ipdb) is active
    if self._reading:
        raise ValueError(
            _(
                "Inspecting and setting values while debugging "
                "in IPython consoles is not supported yet by "
                "Spyder."
            )
        )

    # Wait until the kernel returns the value
    wait_loop = QEventLoop()
    self.sig_got_reply.connect(wait_loop.quit)
    self.silent_execute("get_ipython().kernel.get_value('%s')" % name)
    wait_loop.exec_()

    # Remove loop connection and loop
    self.sig_got_reply.disconnect(wait_loop.quit)
    wait_loop = None

    # Handle exceptions
    if self._kernel_value is None:
        if self._kernel_reply:
            msg = self._kernel_reply[:]
            self._kernel_reply = None
            raise ValueError(msg)

    return self._kernel_value
# Buggy code
def _handle_data_message(self, msg):
    """
    Handle raw (serialized) data sent by the kernel

    We only handle data asked by Spyder, in case people use
    publish_data for other purposes.
    """
    # Deserialize data
    try:
        data = deserialize_object(msg["buffers"])[0]
    except Exception as msg:
        self._kernel_value = None
        self._kernel_reply = msg
        self.sig_get_value.emit()
        return

    # We only handle data asked by Spyder
    value = data.get("__spy_data__", None)
    if value is not None:
        if isinstance(value, CannedObject):
            value = value.get_object()
        self._kernel_value = value
        self.sig_get_value.emit()


# Traceback (TypeError)
Traceback (most recent call last):
File "C:\Python\lib\site-packages\qtconsole\base_frontend_mixin.py", line 163, in _dispatch
handler(msg)
File "C:\dev\packages\spyder\spyder\widgets\ipythonconsole\namespacebrowser.py", line 188, in _handle_execute_reply
self.handle_exec_method(msg)
File "C:\dev\packages\spyder\spyder\widgets\ipythonconsole\shell.py", line 229, in handle_exec_method
self._kernel_reply = ast.literal_eval(data['text/plain'])
TypeError: 'NoneType' object is not subscriptable

# Fixed code
def _handle_data_message(self, msg):
    """
    Handle raw (serialized) data sent by the kernel

    We only handle data asked by Spyder, in case people use
    publish_data for other purposes.
    """
    # Deserialize data
    try:
        data = deserialize_object(msg["buffers"])[0]
    except Exception as msg:
        self._kernel_value = None
        self._kernel_reply = repr(msg)
        self.sig_got_reply.emit()
        return

    # We only handle data asked by Spyder
    value = data.get("__spy_data__", None)
    if value is not None:
        if isinstance(value, CannedObject):
            value = value.get_object()
        self._kernel_value = value
        self.sig_got_reply.emit()
# Buggy code
def handle_exec_method(self, msg):
    """
    Handle data returned by silent executions of kernel methods

    This is based on the _handle_exec_callback of RichJupyterWidget.
    Therefore this is licensed BSD.
    """
    user_exp = msg["content"].get("user_expressions")
    if not user_exp:
        return
    for expression in user_exp:
        if expression in self._kernel_methods:
            # Process kernel reply
            method = self._kernel_methods[expression]
            reply = user_exp[expression]
            data = reply.get("data")
            if "get_namespace_view" in method:
                view = ast.literal_eval(data["text/plain"])
                self.sig_namespace_view.emit(view)
            elif "get_var_properties" in method:
                properties = ast.literal_eval(data["text/plain"])
                self.sig_var_properties.emit(properties)
            else:
                self._kernel_reply = ast.literal_eval(data["text/plain"])
                self.sig_got_reply.emit()

            # Remove method after being processed
            self._kernel_methods.pop(expression)


# Traceback (TypeError)
Traceback (most recent call last):
File "C:\Python\lib\site-packages\qtconsole\base_frontend_mixin.py", line 163, in _dispatch
handler(msg)
File "C:\dev\packages\spyder\spyder\widgets\ipythonconsole\namespacebrowser.py", line 188, in _handle_execute_reply
self.handle_exec_method(msg)
File "C:\dev\packages\spyder\spyder\widgets\ipythonconsole\shell.py", line 229, in handle_exec_method
self._kernel_reply = ast.literal_eval(data['text/plain'])
TypeError: 'NoneType' object is not subscriptable

# Fixed code
def handle_exec_method(self, msg):
    """
    Handle data returned by silent executions of kernel methods

    This is based on the _handle_exec_callback of RichJupyterWidget.
    Therefore this is licensed BSD.
    """
    user_exp = msg["content"].get("user_expressions")
    if not user_exp:
        return
    for expression in user_exp:
        if expression in self._kernel_methods:
            # Process kernel reply
            method = self._kernel_methods[expression]
            reply = user_exp[expression]
            data = reply.get("data")
            if "get_namespace_view" in method:
                view = ast.literal_eval(data["text/plain"])
                self.sig_namespace_view.emit(view)
            elif "get_var_properties" in method:
                properties = ast.literal_eval(data["text/plain"])
                self.sig_var_properties.emit(properties)
            else:
                if data is not None:
                    self._kernel_reply = ast.literal_eval(data["text/plain"])
                else:
                    self._kernel_reply = None
                self.sig_got_reply.emit()

            # Remove method after being processed
            self._kernel_methods.pop(expression)
# Buggy code
def global_max(col_vals, index):
    """Returns the global maximum and minimum"""
    max_col, min_col = zip(*col_vals)
    return max(max_col), min(min_col)


# Traceback (ValueError)
Traceback (most recent call last):
File "C:\Anaconda2\lib\site-packages\spyderlib\widgets\variableexplorer\collectionseditor.py", line 464, in createEditor
if not editor.setup_and_check(value, title=key):
File "C:\Anaconda2\lib\site-packages\spyderlib\widgets\variableexplorer\dataframeeditor.py", line 523, in setup_and_check
self.dataModel = DataFrameModel(data, parent=self)
File "C:\Anaconda2\lib\site-packages\spyderlib\widgets\variableexplorer\dataframeeditor.py", line 93, in __init__
self.max_min_col_update()
File "C:\Anaconda2\lib\site-packages\spyderlib\widgets\variableexplorer\dataframeeditor.py", line 132, in max_min_col_update
df_abs = self.df[self.complex_intran].abs()
File "C:\Anaconda2\lib\site-packages\pandas\core\frame.py", line 1993, in __getitem__
return self._getitem_frame(key)
File "C:\Anaconda2\lib\site-packages\pandas\core\frame.py", line 2069, in _getitem_frame
return self.where(key)
File "C:\Anaconda2\lib\site-packages\pandas\core\generic.py", line 4491, in where
transpose=self._AXIS_REVERSED)
File "C:\Anaconda2\lib\site-packages\pandas\core\internals.py", line 2908, in where
return self.apply('where', **kwargs)
File "C:\Anaconda2\lib\site-packages\pandas\core\internals.py", line 2890, in apply
applied = getattr(b, f)(**kwargs)
File "C:\Anaconda2\lib\site-packages\pandas\core\internals.py", line 1240, in where
return self.make_block(result)
File "C:\Anaconda2\lib\site-packages\pandas\core\internals.py", line 181, in make_block
return make_block(values, placement=placement, ndim=ndim, **kwargs)
File "C:\Anaconda2\lib\site-packages\pandas\core\internals.py", line 2518, in make_block
return klass(values, ndim=ndim, fastpath=fastpath, placement=placement)
File "C:\Anaconda2\lib\site-packages\pandas\core\internals.py", line 1663, in __init__
placement=placement, **kwargs)
File "C:\Anaconda2\lib\site-packages\pandas\core\internals.py", line 81, in __init__
raise ValueError('Wrong number of dimensions')
ValueError: Wrong number of dimensions

# Fixed code
def global_max(col_vals, index):
    """Returns the global maximum and minimum"""
    col_vals_without_None = [x for x in col_vals if x is not None]
    max_col, min_col = zip(*col_vals_without_None)
    return max(max_col), min(min_col)
# Buggy code
def __init__(self, parent):
    QWidget.__init__(self, parent)

    self.webview = FrameWebView(self)
    self.find_widget = FindReplace(self)
    self.find_widget.set_editor(self.webview)
    self.find_widget.hide()

    layout = QVBoxLayout()
    layout.setContentsMargins(0, 0, 0, 0)
    layout.addWidget(self.webview)
    layout.addWidget(self.find_widget)
    self.setLayout(layout)


# Traceback (AttributeError)
Traceback (most recent call last):
File "/home/drmccloy/Builds/spyder/spyderlib/widgets/findreplace.py", line 203, in show
text = self.editor.get_selected_text()
AttributeError: 'FrameWebView' object has no attribute 'get_selected_text'

# Fixed code
def __init__(self, parent):
    QWidget.__init__(self, parent)

    self.webview = FrameWebView(self)
    self.find_widget = FindReplace(self)
    self.find_widget.set_editor(self.webview.web_widget)
    self.find_widget.hide()

    layout = QVBoxLayout()
    layout.setContentsMargins(0, 0, 0, 0)
    layout.addWidget(self.webview)
    layout.addWidget(self.find_widget)
    self.setLayout(layout)
# Buggy code
def find_text(
    self, text, changed=True, forward=True, case=False, words=False, regexp=False
):
    """Find text"""
    findflag = QWebEnginePage.FindWrapsAroundDocument
    if not forward:
        findflag = findflag | QWebEnginePage.FindBackward
    if case:
        findflag = findflag | QWebEnginePage.FindCaseSensitively
    return self.findText(text, findflag)


# Traceback (AttributeError)
Traceback (most recent call last):
File "/home/drmccloy/Builds/spyder/spyderlib/widgets/findreplace.py", line 203, in show
text = self.editor.get_selected_text()
AttributeError: 'FrameWebView' object has no attribute 'get_selected_text'

# Fixed code
def find_text(
    self, text, changed=True, forward=True, case=False, words=False, regexp=False
):
    """Find text"""
    if not WEBENGINE:
        findflag = QWebEnginePage.FindWrapsAroundDocument
    else:
        findflag = 0

    if not forward:
        findflag = findflag | QWebEnginePage.FindBackward
    if case:
        findflag = findflag | QWebEnginePage.FindCaseSensitively

    return self.findText(text, QWebEnginePage.FindFlags(findflag))
# Buggy code
def set_font(self, font, fixed_font=None):
    self._webview.set_font(font, fixed_font=fixed_font)


# Traceback (AttributeError)
Traceback (most recent call last):
File "/home/drmccloy/Builds/spyder/spyderlib/widgets/findreplace.py", line 203, in show
text = self.editor.get_selected_text()
AttributeError: 'FrameWebView' object has no attribute 'get_selected_text'

# Fixed code
def set_font(self, font, fixed_font=None):
    settings = self.page().settings()
    for fontfamily in (
        settings.StandardFont,
        settings.SerifFont,
        settings.SansSerifFont,
        settings.CursiveFont,
        settings.FantasyFont,
    ):
        settings.setFontFamily(fontfamily, font.family())
    if fixed_font is not None:
        settings.setFontFamily(settings.FixedFont, fixed_font.family())
    size = font.pointSize()
    settings.setFontSize(settings.DefaultFontSize, size)
    settings.setFontSize(settings.DefaultFixedFontSize, size)
# Buggy code
def show(self):
    """Overrides Qt Method"""
    QWidget.show(self)
    self.visibility_changed.emit(True)
    if self.editor is not None:
        text = self.editor.get_selected_text()

        # If no text is highlighted for search, use whatever word is under the cursor
        if not text:
            cursor = self.editor.textCursor()
            cursor.select(QTextCursor.WordUnderCursor)
            text = to_text_string(cursor.selectedText())

        # Now that text value is sorted out, use it for the search
        if text:
            self.search_text.setEditText(text)
            self.search_text.lineEdit().selectAll()
            self.refresh()
        else:
            self.search_text.lineEdit().selectAll()
        self.search_text.setFocus()


# Traceback (AttributeError)
Traceback (most recent call last):
File "/home/drmccloy/Builds/spyder/spyderlib/widgets/findreplace.py", line 203, in show
text = self.editor.get_selected_text()
AttributeError: 'FrameWebView' object has no attribute 'get_selected_text'

# Fixed code
def show(self):
    """Overrides Qt Method"""
    QWidget.show(self)
    self.visibility_changed.emit(True)
    if self.editor is not None:
        text = self.editor.get_selected_text()

        # If no text is highlighted for search, use whatever word is under
        # the cursor
        if not text:
            try:
                cursor = self.editor.textCursor()
                cursor.select(QTextCursor.WordUnderCursor)
                text = to_text_string(cursor.selectedText())
            except AttributeError:
                # We can't do this for all widgets, e.g. WebView's
                pass

        # Now that text value is sorted out, use it for the search
        if text:
            self.search_text.setEditText(text)
            self.search_text.lineEdit().selectAll()
            self.refresh()
        else:
            self.search_text.lineEdit().selectAll()
        self.search_text.setFocus()
# Buggy code
def find(
    self, changed=True, forward=True, rehighlight=True, start_highlight_timer=False
):
    """Call the find function"""
    text = self.search_text.currentText()
    if len(text) == 0:
        self.search_text.lineEdit().setStyleSheet("")
        return None
    else:
        case = self.case_button.isChecked()
        words = self.words_button.isChecked()
        regexp = self.re_button.isChecked()
        found = self.editor.find_text(
            text, changed, forward, case=case, words=words, regexp=regexp
        )
        self.search_text.lineEdit().setStyleSheet(self.STYLE[found])
        if self.is_code_editor and found:
            if rehighlight or not self.editor.found_results:
                self.highlight_timer.stop()
                if start_highlight_timer:
                    self.highlight_timer.start()
                else:
                    self.highlight_matches()
        else:
            self.clear_matches()
        return found


# Traceback (AttributeError)
Traceback (most recent call last):
File "/home/drmccloy/Builds/spyder/spyderlib/widgets/findreplace.py", line 203, in show
text = self.editor.get_selected_text()
AttributeError: 'FrameWebView' object has no attribute 'get_selected_text'

# Fixed code
def find(
    self, changed=True, forward=True, rehighlight=True, start_highlight_timer=False
):
    """Call the find function"""
    text = self.search_text.currentText()
    if len(text) == 0:
        self.search_text.lineEdit().setStyleSheet("")
        if not self.is_code_editor:
            # Clears the selection for WebEngine
            self.editor.find_text("")
        return None
    else:
        case = self.case_button.isChecked()
        words = self.words_button.isChecked()
        regexp = self.re_button.isChecked()
        found = self.editor.find_text(
            text, changed, forward, case=case, words=words, regexp=regexp
        )
        self.search_text.lineEdit().setStyleSheet(self.STYLE[found])
        if self.is_code_editor and found:
            if rehighlight or not self.editor.found_results:
                self.highlight_timer.stop()
                if start_highlight_timer:
                    self.highlight_timer.start()
                else:
                    self.highlight_matches()
        else:
            self.clear_matches()
        return found
# Buggy code
def load_pickle(filename):
    """Load a pickle file as a dictionary"""
    try:
        if pd:
            return pd.read_pickle(data), None
        else:
            with open(filename, "rb") as fid:
                data = pickle.load(fid)
            return data, None
    except Exception as err:
        return None, str(err)


# Traceback (ValueError)
Traceback (most recent call last):
File "/opt/anaconda2/bin/spyder", line 2, in <module>
from spyderlib import start_app
File "/opt/anaconda2/lib/python2.7/site-packages/spyderlib/start_app.py", line 13, in <module>
from spyderlib.config import CONF
File "/opt/anaconda2/lib/python2.7/site-packages/spyderlib/config.py", line 22, in <module>
from spyderlib.utils import iofuncs, codeanalysis
File "/opt/anaconda2/lib/python2.7/site-packages/spyderlib/utils/iofuncs.py", line 163, in <module>
import scipy.io as spio
File "/opt/anaconda2/lib/python2.7/site-packages/scipy/io/__init__.py", line 85, in <module>
from .matlab import loadmat, savemat, whosmat, byteordercodes
File "/opt/anaconda2/lib/python2.7/site-packages/scipy/io/matlab/__init__.py", line 13, in <module>
from .mio import loadmat, savemat, whosmat
File "/opt/anaconda2/lib/python2.7/site-packages/scipy/io/matlab/mio.py", line 12, in <module>
from .miobase import get_matfile_version, docfiller
File "/opt/anaconda2/lib/python2.7/site-packages/scipy/io/matlab/miobase.py", line 22, in <module>
from scipy.misc import doccer
File "/opt/anaconda2/lib/python2.7/site-packages/scipy/misc/__init__.py", line 49, in <module>
from scipy.special import comb, factorial, factorial2, factorialk
File "/opt/anaconda2/lib/python2.7/site-packages/scipy/special/__init__.py", line 601, in <module>
from ._ufuncs import *
File "__init__.pxd", line 155, in init scipy.special._ufuncs (scipy/special/_ufuncs.c:27221)
ValueError: numpy.dtype has the wrong size, try recompiling

# Fixed code
def load_pickle(filename):
    """Load a pickle file as a dictionary"""
    try:
        if pd:
            return pd.read_pickle(filename), None
        else:
            with open(filename, "rb") as fid:
                data = pickle.load(fid)
            return data, None
    except Exception as err:
        return None, str(err)
# Buggy code
def sympy_config(mpl_backend):
    """Sympy configuration"""
    lines = """
from sympy.interactive import init_session
init_session()
%matplotlib {0}
""".format(mpl_backend)
    return lines


# Traceback (UnboundLocalError)
An error ocurred while starting the kernel
Traceback (most recent call last):
File "C:\Users\Dani\Anaconda3\lib\site‑packages\spyderlib\widgets\externalshell\start_ipython_kernel.py", line 169, in
ipk_temp.config = kernel_config()
File "C:\Users\Dani\Anaconda3\lib\site‑packages\spyderlib\widgets\externalshell\start_ipython_kernel.py", line 119, in kernel_config
lines = sympy_config(mpl_backend)
UnboundLocalError: local variable 'mpl_backend' referenced before assignment

# Fixed code
def sympy_config(mpl_backend):
    """Sympy configuration"""
    if mpl_backend is not None:
        lines = """
from sympy.interactive import init_session
init_session()
%matplotlib {0}
""".format(mpl_backend)
    else:
        lines = """
from sympy.interactive import init_session
init_session()
"""

    return lines
# Buggy code
def execute_in_external_console(self, lines, focus_to_editor):
    """Execute lines in external or IPython console
    and eventually set focus to editor"""
    console = self.extconsole
    if self.ipyconsole is None or self.last_console_plugin_focus_was_python:
        console = self.extconsole
    else:
        console = self.ipyconsole
    console.visibility_changed(True)
    console.raise_()
    console.execute_python_code(lines)
    if focus_to_editor:
        self.editor.visibility_changed(True)


# Traceback (UnicodeEncodeError)
Traceback (most recent call last):
File "C:\Anaconda\Scripts\spyder-script.py", line 2, in <module>
start_app.main()
File "C:\Anaconda\lib\site-packages\spyderlib\start_app.py", line 79, in main
if not lock.lock():
File "C:\Anaconda\lib\site-packages\spyderlib\utils\external\lockfile.py", line 174, in lock
kill(int(pid), 0)
UnicodeEncodeError: 'decimal' codec can't encode characters in position 0-3: invalid decimal Unicode string

# Fixed code
def execute_in_external_console(self, lines, focus_to_editor):
    """
    Execute lines in external or IPython console and eventually set focus
    to the editor
    """
    console = self.extconsole
    if self.ipyconsole is None or self.last_console_plugin_focus_was_python:
        console = self.extconsole
    else:
        console = self.ipyconsole
    console.visibility_changed(True)
    console.raise_()
    console.execute_python_code(lines)
    if focus_to_editor:
        self.editor.visibility_changed(True)
# Buggy code
def kill(pid, signal):
    if not _is_pid_running(pid):
        raise OSError(errno.ESRCH, None)
    else:
        return


# Traceback (UnicodeEncodeError)
Traceback (most recent call last):
File "C:\Anaconda\Scripts\spyder-script.py", line 2, in <module>
start_app.main()
File "C:\Anaconda\lib\site-packages\spyderlib\start_app.py", line 79, in main
if not lock.lock():
File "C:\Anaconda\lib\site-packages\spyderlib\utils\external\lockfile.py", line 174, in lock
kill(int(pid), 0)
UnicodeEncodeError: 'decimal' codec can't encode characters in position 0-3: invalid decimal Unicode string

# Fixed code
def kill(pid, signal):  # analysis:ignore
    if not _is_pid_running(pid):
        raise OSError(errno.ESRCH, None)
    else:
        return
# Buggy code
def flush(self, error=False, prompt=False):
    """Flush buffer, write text to console"""
    text = "".join(self.__buffer)
    self.__buffer = []
    self.insert_text(text, at_end=True, error=error, prompt=prompt)
    QCoreApplication.processEvents()
    self.repaint()
    # Clear input buffer:
    self.new_input_line = True


# Traceback (TypeError)
Traceback (most recent call last):
File "C:\Program Files\WinPython-64bit-3.4.3.3\python-3.4.3.amd64\lib\site-packages\spyderlib\widgets\externalshell\baseshell.py", line 285, in write_output
self.shell.write(self.get_stdout(), flush=True)
File "C:\Program Files\WinPython-64bit-3.4.3.3\python-3.4.3.amd64\lib\site-packages\spyderlib\widgets\shell.py", line 572, in write
self.flush(error=error, prompt=prompt)
File "C:\Program Files\WinPython-64bit-3.4.3.3\python-3.4.3.amd64\lib\site-packages\spyderlib\widgets\shell.py", line 581, in flush
text = "".join(self.__buffer)
TypeError: sequence item 0: expected str instance, bytes found

# Fixed code
def flush(self, error=False, prompt=False):
    """Flush buffer, write text to console"""
    # Fix for Issue 2452
    if PY3:
        try:
            text = "".join(self.__buffer)
        except TypeError:
            text = b"".join(self.__buffer)
            text = text.decode(locale.getdefaultlocale()[1])
    else:
        text = "".join(self.__buffer)

    self.__buffer = []
    self.insert_text(text, at_end=True, error=error, prompt=prompt)
    QCoreApplication.processEvents()
    self.repaint()
    # Clear input buffer:
    self.new_input_line = True
# Buggy code
def _get_docstring(self):
    """Find the docstring we are currently in"""
    left = self.position
    while left:
        if self.source_code[left : left + 3] in ['"""', "'''"]:
            left += 3
            break
        left -= 1
    right = self.position
    while right < len(self.source_code):
        if self.source_code[right - 3 : right] in ['"""', "'''"]:
            right -= 3
            break
        right += 1
    if left and right < len(self.source_code):
        return self.source_code[left:right]


# Traceback (TypeError)
Traceback (most recent call last):
File "/usr/local/anaconda/lib/python2.7/site-packages/spyderlib/utils/introspection/plugin_manager.py", line 342, in _introspection_complete
Traceback (most recent call last):
threads  File "/usr/local/anaconda/lib/python2.7/site-packages/spyderlib/utils/introspection/plugin_manager.py", line 342, in _introspection_complete
result = self.plugins['fallback'].get_definition(info)
File "/usr/local/anaconda/lib/python2.7/site-packages/spyderlib/utils/introspection/fallback_plugin.py", line 72, in get_definition
if '.' in token:
TypeError: argument of type 'NoneType' is not iterable
result = self.plugins['fallback'].get_definition(info)
File "/usr/local/anaconda/lib/python2.7/site-packages/spyderlib/utils/introspection/fallback_plugin.py", line 72, in get_definition
if '.' in token:
TypeError: argument of type 'NoneType' is not iterable

# Fixed code
def _get_docstring(self):
    """Find the docstring we are currently in"""
    left = self.position
    while left:
        if self.source_code[left : left + 3] in ['"""', "'''"]:
            left += 3
            break
        left -= 1
    right = self.position
    while right < len(self.source_code):
        if self.source_code[right - 3 : right] in ['"""', "'''"]:
            right -= 3
            break
        right += 1
    if left and right < len(self.source_code):
        return self.source_code[left:right]
    return ""