gurudesh/pytracebugs huggingface dataset:
# Buggy code
def get_balance(self):
    """
    Return the balance of the wallet.
    """
    if self.created:
        options = {
            "nolnet": False,
            "password": None,
            "verbose": False,
            "cmd": "getbalance",
            "wallet_path": self.wallet_file,
            "testnet": self.TESTNET,
            "segwit": False,
            "cwd": self.wallet_dir,
            "portable": False,
        }
        config = SimpleConfig(options)

        server = self.get_daemon().get_server(config)
        result = server.run_cmdline(options)

        confirmed = float(result["confirmed"])
        unconfirmed = float(result["unconfirmed"]) if "unconfirmed" in result else 0
        unconfirmed += float(result["unmatured"]) if "unmatured" in result else 0

        return succeed(
            {"available": confirmed, "pending": unconfirmed, "currency": "BTC"}
        )
    else:
        return succeed({"available": 0, "pending": 0, "currency": "BTC"})


# Traceback (EOFError)
Gkr-Message: secret service operation failed: The name org.freedesktop.secrets was not provided by any .service files
Exception in thread tribler-pipe-read:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 754, in run
self.__target(*self.__args, **self.__kwargs)
File "/home/bram/git/tribler/TriblerGUI/core_manager.py", line 173, in <lambda>
pipe_thread = Thread(target=lambda: self.pipe_wait(parent_conn), name="tribler-pipe-read")
File "/home/bram/git/tribler/TriblerGUI/core_manager.py", line 158, in pipe_wait
cmd, arg = child_conn.recv()
EOFError

# Fixed code
def get_balance(self):
    """
    Return the balance of the wallet.
    """
    if self.created and self.unlocked:
        options = {
            "nolnet": False,
            "password": None,
            "verbose": False,
            "cmd": "getbalance",
            "wallet_path": self.wallet_file,
            "testnet": self.TESTNET,
            "segwit": False,
            "cwd": self.wallet_dir,
            "portable": False,
        }
        config = SimpleConfig(options)

        server = self.get_daemon().get_server(config)
        result = server.run_cmdline(options)

        confirmed = float(result["confirmed"])
        unconfirmed = float(result["unconfirmed"]) if "unconfirmed" in result else 0
        unconfirmed += float(result["unmatured"]) if "unmatured" in result else 0

        return succeed(
            {"available": confirmed, "pending": unconfirmed, "currency": "BTC"}
        )

    return succeed({"available": 0, "pending": 0, "currency": "BTC"})
# Buggy code
def get_address(self):
    if not self.created:
        return ""
    return str(self.wallet.get_receiving_address())


# Traceback (EOFError)
Gkr-Message: secret service operation failed: The name org.freedesktop.secrets was not provided by any .service files
Exception in thread tribler-pipe-read:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 754, in run
self.__target(*self.__args, **self.__kwargs)
File "/home/bram/git/tribler/TriblerGUI/core_manager.py", line 173, in <lambda>
pipe_thread = Thread(target=lambda: self.pipe_wait(parent_conn), name="tribler-pipe-read")
File "/home/bram/git/tribler/TriblerGUI/core_manager.py", line 158, in pipe_wait
cmd, arg = child_conn.recv()
EOFError

# Fixed code
def get_address(self):
    if not self.created or not self.unlocked:
        return ""
    return str(self.wallet.get_receiving_address())
# Buggy code
def __init__(self):
    super(BaseDummyWallet, self).__init__()

    self.balance = 1000
    self.created = True
    self.address = "".join([choice(string.lowercase) for _ in xrange(10)])
    self.transaction_history = []


# Traceback (EOFError)
Gkr-Message: secret service operation failed: The name org.freedesktop.secrets was not provided by any .service files
Exception in thread tribler-pipe-read:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 754, in run
self.__target(*self.__args, **self.__kwargs)
File "/home/bram/git/tribler/TriblerGUI/core_manager.py", line 173, in <lambda>
pipe_thread = Thread(target=lambda: self.pipe_wait(parent_conn), name="tribler-pipe-read")
File "/home/bram/git/tribler/TriblerGUI/core_manager.py", line 158, in pipe_wait
cmd, arg = child_conn.recv()
EOFError

# Fixed code
def __init__(self):
    super(BaseDummyWallet, self).__init__()

    self.balance = 1000
    self.created = True
    self.unlocked = True
    self.address = "".join([choice(string.lowercase) for _ in xrange(10)])
    self.transaction_history = []
# Buggy code
def __init__(self, tc_community):
    super(TrustchainWallet, self).__init__()

    self.tc_community = tc_community
    self.created = True
    self.check_negative_balance = False
    self.transaction_history = []


# Traceback (EOFError)
Gkr-Message: secret service operation failed: The name org.freedesktop.secrets was not provided by any .service files
Exception in thread tribler-pipe-read:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 754, in run
self.__target(*self.__args, **self.__kwargs)
File "/home/bram/git/tribler/TriblerGUI/core_manager.py", line 173, in <lambda>
pipe_thread = Thread(target=lambda: self.pipe_wait(parent_conn), name="tribler-pipe-read")
File "/home/bram/git/tribler/TriblerGUI/core_manager.py", line 158, in pipe_wait
cmd, arg = child_conn.recv()
EOFError

# Fixed code
def __init__(self, tc_community):
    super(TrustchainWallet, self).__init__()

    self.tc_community = tc_community
    self.created = True
    self.unlocked = True
    self.check_negative_balance = False
    self.transaction_history = []
# Buggy code
def __init__(self):
    super(Wallet, self).__init__()
    self._logger = logging.getLogger(self.__class__.__name__)

    # When there is no available keyring backend, we use an unencrypted keyring on Linux since an encrypted keyring
    # requires input from stdin.
    if sys.platform.startswith("linux"):
        from keyrings.alt.file import EncryptedKeyring, PlaintextKeyring

        if isinstance(keyring.get_keyring(), EncryptedKeyring):
            for new_keyring in keyring.backend.get_all_keyring():
                if isinstance(new_keyring, PlaintextKeyring):
                    keyring.set_keyring(new_keyring)


# Traceback (EOFError)
Gkr-Message: secret service operation failed: The name org.freedesktop.secrets was not provided by any .service files
Exception in thread tribler-pipe-read:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 754, in run
self.__target(*self.__args, **self.__kwargs)
File "/home/bram/git/tribler/TriblerGUI/core_manager.py", line 173, in <lambda>
pipe_thread = Thread(target=lambda: self.pipe_wait(parent_conn), name="tribler-pipe-read")
File "/home/bram/git/tribler/TriblerGUI/core_manager.py", line 158, in pipe_wait
cmd, arg = child_conn.recv()
EOFError

# Fixed code
def __init__(self):
    super(Wallet, self).__init__()
    self._logger = logging.getLogger(self.__class__.__name__)
    self.created = False
    self.unlocked = False

    # When there is no available keyring backend, we use an unencrypted keyring on Linux since an encrypted keyring
    # requires input from stdin.
    if sys.platform.startswith("linux"):
        from keyrings.alt.file import EncryptedKeyring, PlaintextKeyring

        if isinstance(keyring.get_keyring(), EncryptedKeyring):
            for new_keyring in keyring.backend.get_all_keyring():
                if isinstance(new_keyring, PlaintextKeyring):
                    keyring.set_keyring(new_keyring)
# Buggy code
def start_tribler():
    config = TriblerConfig()
    patch_wallet_methods()
    patch_iom_methods()

    config.set_http_api_port(api_port)
    config.set_http_api_enabled(True)

    # Check if we are already running a Tribler instance
    process_checker = ProcessChecker(config.get_state_dir())
    if process_checker.already_running:
        return
    else:
        process_checker.create_lock_file()

    session = Session(config)

    signal.signal(
        signal.SIGTERM, lambda signum, stack: shutdown(session, signum, stack)
    )
    session.start()


# Traceback (EOFError)
Gkr-Message: secret service operation failed: The name org.freedesktop.secrets was not provided by any .service files
Exception in thread tribler-pipe-read:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 754, in run
self.__target(*self.__args, **self.__kwargs)
File "/home/bram/git/tribler/TriblerGUI/core_manager.py", line 173, in <lambda>
pipe_thread = Thread(target=lambda: self.pipe_wait(parent_conn), name="tribler-pipe-read")
File "/home/bram/git/tribler/TriblerGUI/core_manager.py", line 158, in pipe_wait
cmd, arg = child_conn.recv()
EOFError

# Fixed code
def start_tribler():
    config = TriblerConfig()

    if sys.platform == "darwin":
        # Due to a bug when using the keyring from a forked subprocess on MacOS, we have to patch these methods.
        patch_wallet_methods()
        patch_iom_methods()

    config.set_http_api_port(api_port)
    config.set_http_api_enabled(True)

    # Check if we are already running a Tribler instance
    process_checker = ProcessChecker(config.get_state_dir())
    if process_checker.already_running:
        return
    else:
        process_checker.create_lock_file()

    session = Session(config)

    signal.signal(
        signal.SIGTERM, lambda signum, stack: shutdown(session, signum, stack)
    )
    session.start()
# Buggy code
def pipe_wait(self, child_conn):
    """
    This method is executed in a separate thread and is only here since there are some calls that are crashing on
    macOS in a subprocess (due to libdispatch.dylib).
    """
    while True:
        cmd, arg = child_conn.recv()
        if cmd == "get_keyring_password":
            child_conn.send(keyring.get_password("tribler", arg["username"]))
        elif cmd == "set_keyring_password":
            keyring.set_password("tribler", arg["username"], arg["password"])
            child_conn.send("done")


# Traceback (EOFError)
Gkr-Message: secret service operation failed: The name org.freedesktop.secrets was not provided by any .service files
Exception in thread tribler-pipe-read:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 754, in run
self.__target(*self.__args, **self.__kwargs)
File "/home/bram/git/tribler/TriblerGUI/core_manager.py", line 173, in <lambda>
pipe_thread = Thread(target=lambda: self.pipe_wait(parent_conn), name="tribler-pipe-read")
File "/home/bram/git/tribler/TriblerGUI/core_manager.py", line 158, in pipe_wait
cmd, arg = child_conn.recv()
EOFError

# Fixed code
def pipe_wait(self, child_conn):
    """
    This method is executed in a separate thread and is only here since there are some calls that are crashing on
    macOS in a subprocess (due to libdispatch.dylib).
    """
    while True:
        try:
            cmd, arg = child_conn.recv()
            if cmd == "get_keyring_password":
                child_conn.send(keyring.get_password("tribler", arg["username"]))
            elif cmd == "set_keyring_password":
                keyring.set_password("tribler", arg["username"], arg["password"])
                child_conn.send("done")
        except EOFError:
            time.sleep(2)  # We can safely do this since we're on a separate thread
# Buggy code
def on_explore_files(self):
    path = os.path.normpath(
        os.path.join(
            self.window().tribler_settings["downloadconfig"]["saveas"],
            self.selected_item.download_info["destination"],
        )
    )
    QDesktopServices.openUrl(QUrl.fromLocalFile(path))


# Traceback (EOFError)
Gkr-Message: secret service operation failed: The name org.freedesktop.secrets was not provided by any .service files
Exception in thread tribler-pipe-read:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 754, in run
self.__target(*self.__args, **self.__kwargs)
File "/home/bram/git/tribler/TriblerGUI/core_manager.py", line 173, in <lambda>
pipe_thread = Thread(target=lambda: self.pipe_wait(parent_conn), name="tribler-pipe-read")
File "/home/bram/git/tribler/TriblerGUI/core_manager.py", line 158, in pipe_wait
cmd, arg = child_conn.recv()
EOFError

# Fixed code
def on_explore_files(self):
    path = os.path.normpath(
        os.path.join(
            self.window().tribler_settings["download_defaults"]["saveas"],
            self.selected_item.download_info["destination"],
        )
    )
    QDesktopServices.openUrl(QUrl.fromLocalFile(path))
# Buggy code
def on_new_version_available(self, version):
    if version == str(self.gui_settings.value("last_reported_version")):
        return

    self.dialog = ConfirmationDialog(
        self,
        "New version available",
        "Version %s of Tribler is available.Do you want to visit the website to "
        "download the newest version?" % version,
        [
            ("IGNORE", BUTTON_TYPE_NORMAL),
            ("LATER", BUTTON_TYPE_NORMAL),
            ("OK", BUTTON_TYPE_NORMAL),
        ],
    )
    self.dialog.button_clicked.connect(
        lambda action: self.on_new_version_dialog_done(version, action)
    )
    self.dialog.show()


# Traceback (RuntimeError)
Traceback (most recent call last):
File "TriblerGUI\event_request_manager.py", line 99, in on_read_data
RuntimeError: Unhandled Error
Traceback (most recent call last):
File "lib\multiprocessing\process.py", line 114, in run

File "TriblerGUI\core_manager.py", line 63, in start_tribler_core

File "lib\site-packages\twisted\internet\base.py", line 1243, in run

File "lib\site-packages\twisted\internet\base.py", line 1252, in mainLoop

--- <exception caught here> ---
File "lib\site-packages\twisted\internet\base.py", line 851, in runUntilCurrent

File "Tribler\Core\TFTP\handler.py", line 233, in data_came_in

File "Tribler\Core\TFTP\handler.py", line 301, in _handle_new_request

File "Tribler\Core\TFTP\handler.py", line 345, in _load_torrent

File "lib\_abcoll.py", line 382, in get

File "Tribler\Core\leveldbstore.py", line 86, in __getitem__

exceptions.AttributeError: 'LevelDbStore' object has no attribute '_db'

# Fixed code
def on_new_version_available(self, version):
    if version == str(self.gui_settings.value("last_reported_version")):
        return

    self.new_version_dialog = ConfirmationDialog(
        self,
        "New version available",
        "Version %s of Tribler is available.Do you want to visit the "
        "website to download the newest version?" % version,
        [
            ("IGNORE", BUTTON_TYPE_NORMAL),
            ("LATER", BUTTON_TYPE_NORMAL),
            ("OK", BUTTON_TYPE_NORMAL),
        ],
    )
    self.new_version_dialog.button_clicked.connect(
        lambda action: self.on_new_version_dialog_done(version, action)
    )
    self.new_version_dialog.show()
# Buggy code
def on_new_version_dialog_done(self, version, action):
    if action == 0:  # ignore
        self.gui_settings.setValue("last_reported_version", version)
    elif action == 2:  # ok
        import webbrowser

        webbrowser.open("https://tribler.org")

    self.dialog.setParent(None)
    self.dialog = None


# Traceback (RuntimeError)
Traceback (most recent call last):
File "TriblerGUI\event_request_manager.py", line 99, in on_read_data
RuntimeError: Unhandled Error
Traceback (most recent call last):
File "lib\multiprocessing\process.py", line 114, in run

File "TriblerGUI\core_manager.py", line 63, in start_tribler_core

File "lib\site-packages\twisted\internet\base.py", line 1243, in run

File "lib\site-packages\twisted\internet\base.py", line 1252, in mainLoop

--- <exception caught here> ---
File "lib\site-packages\twisted\internet\base.py", line 851, in runUntilCurrent

File "Tribler\Core\TFTP\handler.py", line 233, in data_came_in

File "Tribler\Core\TFTP\handler.py", line 301, in _handle_new_request

File "Tribler\Core\TFTP\handler.py", line 345, in _load_torrent

File "lib\_abcoll.py", line 382, in get

File "Tribler\Core\leveldbstore.py", line 86, in __getitem__

exceptions.AttributeError: 'LevelDbStore' object has no attribute '_db'

# Fixed code
def on_new_version_dialog_done(self, version, action):
    if action == 0:  # ignore
        self.gui_settings.setValue("last_reported_version", version)
    elif action == 2:  # ok
        import webbrowser

        webbrowser.open("https://tribler.org")

    self.new_version_dialog.setParent(None)
    self.new_version_dialog = None
# Buggy code
def http_get(uri):
    def _on_response(response):
        if response.code == http.OK:
            return readBody(response)
        raise HttpError(response)

    agent = Agent(reactor)
    deferred = agent.request(
        "GET", uri, Headers({"User-Agent": ["Tribler " + version_id]}), None
    )
    deferred.addCallback(_on_response)
    return deferred


# Traceback (RuntimeError)
Traceback (most recent call last):
File "TriblerGUI\event_request_manager.py", line 99, in on_read_data
RuntimeError: Unhandled Error
Traceback (most recent call last):
File "lib\multiprocessing\process.py", line 114, in run

File "TriblerGUI\core_manager.py", line 65, in start_tribler_core

File "lib\site-packages\twisted\internet\base.py", line 1243, in run

File "lib\site-packages\twisted\internet\base.py", line 1252, in mainLoop

--- <exception caught here> ---
File "lib\site-packages\twisted\internet\base.py", line 878, in runUntilCurrent

File "Tribler\Core\Modules\channel\channel_rss.py", line 114, in _task_scrape

File "Tribler\Core\Modules\channel\channel_rss.py", line 111, in parse_feed

File "Tribler\Core\Modules\channel\channel_rss.py", line 267, in parse

File "Tribler\Core\Utilities\utilities.py", line 215, in http_get

File "lib\site-packages\twisted\web\client.py", line 1633, in request

File "lib\site-packages\twisted\web\client.py", line 1617, in _getEndpoint

File "lib\site-packages\twisted\web\client.py", line 1494, in endpointForURI

File "lib\site-packages\twisted\web\client.py", line 857, in raiseNotImplemented

exceptions.NotImplementedError: SSL support unavailable

# Fixed code
def http_get(uri):
    def _on_response(response):
        if response.code == http.OK:
            return readBody(response)
        raise HttpError(response)

    treq_deferred = treq.get(uri, persistent=False)
    treq_deferred.addCallback(_on_response)
    return treq_deferred
# Buggy code
def on_rss_feeds_remove_selected_clicked(self):
    self.dialog = ConfirmationDialog(
        self,
        "Remove RSS feed",
        "Are you sure you want to remove the selected RSS feed?",
        [("REMOVE", BUTTON_TYPE_NORMAL), ("CANCEL", BUTTON_TYPE_CONFIRM)],
    )
    self.dialog.button_clicked.connect(self.on_rss_feed_dialog_removed)
    self.dialog.show()


# Traceback (IndexError)
Traceback (most recent call last):
File "TriblerGUI\widgets\editchannelpage.py", line 535, in on_rss_feed_dialog_removed
IndexError: list index out of range

# Fixed code
def on_rss_feeds_remove_selected_clicked(self):
    if len(self.window().edit_channel_rss_feeds_list.selectedItems()) == 0:
        ConfirmationDialog.show_message(
            self,
            "Remove RSS Feeds",
            "Selection is empty. Please select the feeds to remove.",
            "OK",
        )
        return
    self.dialog = ConfirmationDialog(
        self,
        "Remove RSS feed",
        "Are you sure you want to remove the selected RSS feed?",
        [("REMOVE", BUTTON_TYPE_NORMAL), ("CANCEL", BUTTON_TYPE_CONFIRM)],
    )
    self.dialog.button_clicked.connect(self.on_rss_feed_dialog_removed)
    self.dialog.show()
# Buggy code
def __init__(self, session):
    super(ResourceMonitor, self).__init__()

    self._logger = logging.getLogger(self.__class__.__name__)
    self.session = session
    self.check_interval = 5
    self.cpu_data = []
    self.memory_data = []
    self.process = psutil.Process()
    self.history_size = session.get_resource_monitor_history_size()


# Traceback (RuntimeError)
Traceback (most recent call last):
File "TriblerGUI\event_request_manager.py", line 99, in on_read_data
RuntimeError: [Failure instance: Traceback: <type 'exceptions.IOError'>: [Errno 28] No space left on device
lib\site-packages\twisted\internet\base.py:1243:run
lib\site-packages\twisted\internet\base.py:1252:mainLoop
lib\site-packages\twisted\internet\base.py:878:runUntilCurrent
lib\site-packages\twisted\internet\task.py:239:__call__
--- <exception caught here> ---
lib\site-packages\twisted\internet\defer.py:150:maybeDeferred
Tribler\dispersy\discovery\community.py:809:clean_and_save
]

# Fixed code
def __init__(self, session):
    super(ResourceMonitor, self).__init__()

    self._logger = logging.getLogger(self.__class__.__name__)
    self.session = session
    self.check_interval = 5
    self.cpu_data = []
    self.memory_data = []
    self.disk_usage_data = []
    self.process = psutil.Process()
    self.history_size = session.get_resource_monitor_history_size()
# Buggy code
def on_cancel_health_check(self):
    """
    The request for torrent health could not be queued.
    Go back to the intial state.
    """
    self.health_text.setText("unknown health")
    self.set_health_indicator(STATUS_UNKNOWN)
    self.is_health_checking = False
    self.has_health = False


# Traceback (RuntimeError)
Traceback (most recent call last):
File "TriblerGUI\tribler_request_manager.py", line 197, in <lambda>
File "TriblerGUI\tribler_request_manager.py", line 287, in on_finished
File "TriblerGUI\tribler_request_manager.py", line 58, in parse_queue
File "TriblerGUI\tribler_request_manager.py", line 337, in cancel_request
File "TriblerGUI\widgets\channel_torrent_list_item.py", line 111, in on_cancel_health_check
RuntimeError: wrapped C/C++ object of type QLabel has been deleted

# Fixed code
def on_cancel_health_check(self):
    """
    The request for torrent health could not be queued.
    Go back to the intial state.
    """
    try:
        self.health_text.setText("unknown health")
        self.set_health_indicator(STATUS_UNKNOWN)
        self.is_health_checking = False
        self.has_health = False
    except RuntimeError:
        self._logger.error("The underlying GUI widget has already been removed.")
# Buggy code
def __init__(self, parent):
    QTreeWidgetItem.__init__(self, parent)
    self.download_info = None

    bar_container = QWidget()
    bar_container.setLayout(QVBoxLayout())
    bar_container.setStyleSheet("background-color: transparent;")

    self.progress_slider = QProgressBar()
    self.progress_slider.setStyleSheet("""
        QProgressBar {
            background-color: white;
            color: black;
            font-size: 12px;
            text-align: center;
        }

        QProgressBar::chunk {
            background-color: #e67300;
        }
        """)

    bar_container.layout().addWidget(self.progress_slider)
    bar_container.layout().setContentsMargins(4, 4, 8, 4)

    parent.setItemWidget(self, 2, bar_container)
    self.progress_slider.setAutoFillBackground(True)


# Traceback (RuntimeError)
Traceback (most recent call last):
File "TriblerGUI\tribler_request_manager.py", line 197, in <lambda>
File "TriblerGUI\tribler_request_manager.py", line 287, in on_finished
File "TriblerGUI\tribler_request_manager.py", line 58, in parse_queue
File "TriblerGUI\tribler_request_manager.py", line 337, in cancel_request
File "TriblerGUI\widgets\channel_torrent_list_item.py", line 111, in on_cancel_health_check
RuntimeError: wrapped C/C++ object of type QLabel has been deleted

# Fixed code
def __init__(self, parent):
    QTreeWidgetItem.__init__(self, parent)
    self.download_info = None
    self._logger = logging.getLogger("TriblerGUI")

    bar_container = QWidget()
    bar_container.setLayout(QVBoxLayout())
    bar_container.setStyleSheet("background-color: transparent;")

    self.progress_slider = QProgressBar()
    self.progress_slider.setStyleSheet("""
        QProgressBar {
            background-color: white;
            color: black;
            font-size: 12px;
            text-align: center;
        }

        QProgressBar::chunk {
            background-color: #e67300;
        }
        """)

    bar_container.layout().addWidget(self.progress_slider)
    bar_container.layout().setContentsMargins(4, 4, 8, 4)

    parent.setItemWidget(self, 2, bar_container)
    self.progress_slider.setAutoFillBackground(True)
# Buggy code
def update_item(self):
    self.setText(0, self.download_info["name"])
    self.setText(1, format_size(float(self.download_info["size"])))

    try:
        self.progress_slider.setValue(int(self.download_info["progress"] * 100))
    except RuntimeError:
        pass

    if self.download_info["vod_mode"]:
        self.setText(3, "Streaming")
    else:
        self.setText(3, DLSTATUS_STRINGS[eval(self.download_info["status"])])
    self.setText(4, str(self.download_info["num_seeds"]))
    self.setText(5, str(self.download_info["num_peers"]))
    self.setText(6, format_speed(self.download_info["speed_down"]))
    self.setText(7, format_speed(self.download_info["speed_up"]))
    self.setText(8, "%.3f" % float(self.download_info["ratio"]))
    self.setText(9, "yes" if self.download_info["anon_download"] else "no")
    self.setText(
        10,
        str(self.download_info["hops"]) if self.download_info["anon_download"] else "-",
    )
    self.setText(
        12,
        datetime.fromtimestamp(int(self.download_info["time_added"])).strftime(
            "%Y-%m-%d %H:%M"
        ),
    )

    eta_text = "-"
    if self.get_raw_download_status() == DLSTATUS_DOWNLOADING:
        eta_text = duration_to_string(self.download_info["eta"])
    self.setText(11, eta_text)


# Traceback (RuntimeError)
Traceback (most recent call last):
File "TriblerGUI\tribler_request_manager.py", line 197, in <lambda>
File "TriblerGUI\tribler_request_manager.py", line 287, in on_finished
File "TriblerGUI\tribler_request_manager.py", line 58, in parse_queue
File "TriblerGUI\tribler_request_manager.py", line 337, in cancel_request
File "TriblerGUI\widgets\channel_torrent_list_item.py", line 111, in on_cancel_health_check
RuntimeError: wrapped C/C++ object of type QLabel has been deleted

# Fixed code
def update_item(self):
    self.setText(0, self.download_info["name"])
    self.setText(1, format_size(float(self.download_info["size"])))

    try:
        self.progress_slider.setValue(int(self.download_info["progress"] * 100))
    except RuntimeError:
        self._logger.error("The underlying GUI widget has already been removed.")

    if self.download_info["vod_mode"]:
        self.setText(3, "Streaming")
    else:
        self.setText(3, DLSTATUS_STRINGS[eval(self.download_info["status"])])
    self.setText(4, str(self.download_info["num_seeds"]))
    self.setText(5, str(self.download_info["num_peers"]))
    self.setText(6, format_speed(self.download_info["speed_down"]))
    self.setText(7, format_speed(self.download_info["speed_up"]))
    self.setText(8, "%.3f" % float(self.download_info["ratio"]))
    self.setText(9, "yes" if self.download_info["anon_download"] else "no")
    self.setText(
        10,
        str(self.download_info["hops"]) if self.download_info["anon_download"] else "-",
    )
    self.setText(
        12,
        datetime.fromtimestamp(int(self.download_info["time_added"])).strftime(
            "%Y-%m-%d %H:%M"
        ),
    )

    eta_text = "-"
    if self.get_raw_download_status() == DLSTATUS_DOWNLOADING:
        eta_text = duration_to_string(self.download_info["eta"])
    self.setText(11, eta_text)
# Buggy code
def load_requests_tab(self):
    self.window().requests_tree_widget.clear()
    for endpoint, method, data, timestamp, status_code in sorted(
        tribler_performed_requests.values(), key=lambda x: x[3]
    ):
        item = QTreeWidgetItem(self.window().requests_tree_widget)
        item.setText(0, "%s %s %s" % (method, endpoint, data))
        item.setText(1, ("%d" % status_code) if status_code else "unknown")
        item.setText(2, "%s" % strftime("%H:%M:%S", localtime(timestamp)))
        self.window().requests_tree_widget.addTopLevelItem(item)


# Traceback (RuntimeError)
Traceback (most recent call last):
File "/usr/share/tribler/TriblerGUI/event_request_manager.py", line 99, in on_read_data
raise RuntimeError(json_dict["event"]["text"])
RuntimeError: [Failure instance: Traceback: <type 'exceptions.IOError'>: [Errno 24] Too many open files: u'/home/dsk/.Tribler/peercache.txt'
/usr/lib/python2.7/dist-packages/twisted/internet/base.py:1194:run
/usr/lib/python2.7/dist-packages/twisted/internet/base.py:1203:mainLoop
/usr/lib/python2.7/dist-packages/twisted/internet/base.py:825:runUntilCurrent
/usr/lib/python2.7/dist-packages/twisted/internet/task.py:239:__call__
--- <exception caught here> ---
/usr/lib/python2.7/dist-packages/twisted/internet/defer.py:150:maybeDeferred
/usr/share/tribler/Tribler/dispersy/discovery/community.py:801:clean_and_save
]

# Fixed code
def load_requests_tab(self):
    self.window().requests_tree_widget.clear()
    for endpoint, method, data, timestamp, status_code in sorted(
        tribler_performed_requests, key=lambda x: x[3]
    ):
        item = QTreeWidgetItem(self.window().requests_tree_widget)
        item.setText(0, "%s %s %s" % (method, endpoint, data))
        item.setText(1, ("%d" % status_code()) if status_code() else "unknown")
        item.setText(2, "%s" % strftime("%H:%M:%S", localtime(timestamp)))
        self.window().requests_tree_widget.addTopLevelItem(item)
# Buggy code
def __init__(self):
    QNetworkAccessManager.__init__(self)
    self.request_id = None
    self.base_url = "http://localhost:%d/" % API_PORT
    self.reply = None
    self.generate_request_id()


# Traceback (RuntimeError)
Traceback (most recent call last):
File "/usr/share/tribler/TriblerGUI/event_request_manager.py", line 99, in on_read_data
raise RuntimeError(json_dict["event"]["text"])
RuntimeError: [Failure instance: Traceback: <type 'exceptions.IOError'>: [Errno 24] Too many open files: u'/home/dsk/.Tribler/peercache.txt'
/usr/lib/python2.7/dist-packages/twisted/internet/base.py:1194:run
/usr/lib/python2.7/dist-packages/twisted/internet/base.py:1203:mainLoop
/usr/lib/python2.7/dist-packages/twisted/internet/base.py:825:runUntilCurrent
/usr/lib/python2.7/dist-packages/twisted/internet/task.py:239:__call__
--- <exception caught here> ---
/usr/lib/python2.7/dist-packages/twisted/internet/defer.py:150:maybeDeferred
/usr/share/tribler/Tribler/dispersy/discovery/community.py:801:clean_and_save
]

# Fixed code
def __init__(self):
    QNetworkAccessManager.__init__(self)
    self.base_url = "http://localhost:%d/" % API_PORT
    self.reply = None
    self.status_code = -1
    self.dispatch_map = {
        "GET": self.perform_get,
        "PATCH": self.perform_patch,
        "PUT": self.perform_put,
        "DELETE": self.perform_delete,
        "POST": self.perform_post,
    }
    self.on_cancel = lambda: None
# Buggy code
def on_finished(self, reply, capture_errors):
    status_code = reply.attribute(QNetworkRequest.HttpStatusCodeAttribute)
    if not reply.isOpen() or not status_code:
        self.received_json.emit(None, reply.error())
        return

    if self.request_id in performed_requests:
        performed_requests[self.request_id][4] = status_code

    data = reply.readAll()
    try:
        json_result = json.loads(str(data), encoding="latin_1")

        if "error" in json_result and capture_errors:
            self.show_error(TriblerRequestManager.get_message_from_error(json_result))
        else:
            self.received_json.emit(json_result, reply.error())
    except ValueError:
        self.received_json.emit(None, reply.error())
        logging.error("No json object could be decoded from data: %s" % data)

    # We disconnect the slot since we want the finished only to be emitted once. This allows us to reuse the
    # request manager.
    try:
        self.finished.disconnect()
        self.received_json.disconnect()
    except TypeError:
        pass  # We probably didn't have any connected slots.


# Traceback (RuntimeError)
Traceback (most recent call last):
File "/usr/share/tribler/TriblerGUI/event_request_manager.py", line 99, in on_read_data
raise RuntimeError(json_dict["event"]["text"])
RuntimeError: [Failure instance: Traceback: <type 'exceptions.IOError'>: [Errno 24] Too many open files: u'/home/dsk/.Tribler/peercache.txt'
/usr/lib/python2.7/dist-packages/twisted/internet/base.py:1194:run
/usr/lib/python2.7/dist-packages/twisted/internet/base.py:1203:mainLoop
/usr/lib/python2.7/dist-packages/twisted/internet/base.py:825:runUntilCurrent
/usr/lib/python2.7/dist-packages/twisted/internet/task.py:239:__call__
--- <exception caught here> ---
/usr/lib/python2.7/dist-packages/twisted/internet/defer.py:150:maybeDeferred
/usr/share/tribler/Tribler/dispersy/discovery/community.py:801:clean_and_save
]

# Fixed code
def on_finished(self, reply, capture_errors):
    self.status_code = reply.attribute(QNetworkRequest.HttpStatusCodeAttribute)
    request_queue.parse_queue()

    if not reply.isOpen() or not self.status_code:
        self.received_json.emit(None, reply.error())
        return

    data = reply.readAll()
    try:
        json_result = json.loads(str(data), encoding="latin_1")

        if "error" in json_result and capture_errors:
            self.show_error(TriblerRequestManager.get_message_from_error(json_result))
        else:
            self.received_json.emit(json_result, reply.error())
    except ValueError:
        self.received_json.emit(None, reply.error())
        logging.error("No json object could be decoded from data: %s" % data)

    # We disconnect the slot since we want the finished only to be emitted once. This allows us to reuse the
    # request manager.
    try:
        self.finished.disconnect()
        self.received_json.disconnect()
    except TypeError:
        pass  # We probably didn't have any connected slots.
# Buggy code
def cancel_request(self):
    if self.reply:
        self.reply.abort()


# Traceback (RuntimeError)
Traceback (most recent call last):
File "/usr/share/tribler/TriblerGUI/event_request_manager.py", line 99, in on_read_data
raise RuntimeError(json_dict["event"]["text"])
RuntimeError: [Failure instance: Traceback: <type 'exceptions.IOError'>: [Errno 24] Too many open files: u'/home/dsk/.Tribler/peercache.txt'
/usr/lib/python2.7/dist-packages/twisted/internet/base.py:1194:run
/usr/lib/python2.7/dist-packages/twisted/internet/base.py:1203:mainLoop
/usr/lib/python2.7/dist-packages/twisted/internet/base.py:825:runUntilCurrent
/usr/lib/python2.7/dist-packages/twisted/internet/task.py:239:__call__
--- <exception caught here> ---
/usr/lib/python2.7/dist-packages/twisted/internet/defer.py:150:maybeDeferred
/usr/share/tribler/Tribler/dispersy/discovery/community.py:801:clean_and_save
]

# Fixed code
def cancel_request(self):
    if self.reply:
        self.reply.abort()
    self.on_cancel()
# Buggy code
def close_tribler(self):
    if not self.core_manager.shutting_down:
        if self.tray_icon:
            self.tray_icon.deleteLater()
        self.show_loading_screen()
        self.loading_text_label.setText("Shutting down...")

        self.gui_settings.setValue("pos", self.pos())
        self.gui_settings.setValue("size", self.size())

        if self.core_manager.use_existing_core:
            # Don't close the core that we are using
            QApplication.quit()

        self.core_manager.stop()
        self.core_manager.shutting_down = True
        self.downloads_page.stop_loading_downloads()


# Traceback (RuntimeError)
Traceback (most recent call last):
File "/usr/share/tribler/TriblerGUI/event_request_manager.py", line 99, in on_read_data
raise RuntimeError(json_dict["event"]["text"])
RuntimeError: [Failure instance: Traceback: <type 'exceptions.IOError'>: [Errno 24] Too many open files: u'/home/dsk/.Tribler/peercache.txt'
/usr/lib/python2.7/dist-packages/twisted/internet/base.py:1194:run
/usr/lib/python2.7/dist-packages/twisted/internet/base.py:1203:mainLoop
/usr/lib/python2.7/dist-packages/twisted/internet/base.py:825:runUntilCurrent
/usr/lib/python2.7/dist-packages/twisted/internet/task.py:239:__call__
--- <exception caught here> ---
/usr/lib/python2.7/dist-packages/twisted/internet/defer.py:150:maybeDeferred
/usr/share/tribler/Tribler/dispersy/discovery/community.py:801:clean_and_save
]

# Fixed code
def close_tribler(self):
    if not self.core_manager.shutting_down:
        if self.tray_icon:
            self.tray_icon.deleteLater()
        self.show_loading_screen()
        self.loading_text_label.setText("Shutting down...")

        self.gui_settings.setValue("pos", self.pos())
        self.gui_settings.setValue("size", self.size())

        if self.core_manager.use_existing_core:
            # Don't close the core that we are using
            QApplication.quit()

        self.core_manager.stop()
        self.core_manager.shutting_down = True
        self.downloads_page.stop_loading_downloads()
        request_queue.clear()
# Buggy code
def check_health(self):
    """
    Perform a request to check the health of the torrent that is represented by this widget.
    Don't do this if we are already checking the health or if we have the health info.
    """
    if self.is_health_checking or self.has_health:  # Don't check health again
        return

    self.health_text.setText("checking health...")
    self.set_health_indicator(STATUS_UNKNOWN)
    self.is_health_checking = True
    self.health_request_mgr = TriblerRequestManager()
    self.health_request_mgr.perform_request(
        "torrents/%s/health?timeout=15" % self.torrent_info["infohash"],
        self.on_health_response,
        capture_errors=False,
    )


# Traceback (RuntimeError)
Traceback (most recent call last):
File "/usr/share/tribler/TriblerGUI/event_request_manager.py", line 99, in on_read_data
raise RuntimeError(json_dict["event"]["text"])
RuntimeError: [Failure instance: Traceback: <type 'exceptions.IOError'>: [Errno 24] Too many open files: u'/home/dsk/.Tribler/peercache.txt'
/usr/lib/python2.7/dist-packages/twisted/internet/base.py:1194:run
/usr/lib/python2.7/dist-packages/twisted/internet/base.py:1203:mainLoop
/usr/lib/python2.7/dist-packages/twisted/internet/base.py:825:runUntilCurrent
/usr/lib/python2.7/dist-packages/twisted/internet/task.py:239:__call__
--- <exception caught here> ---
/usr/lib/python2.7/dist-packages/twisted/internet/defer.py:150:maybeDeferred
/usr/share/tribler/Tribler/dispersy/discovery/community.py:801:clean_and_save
]

# Fixed code
def check_health(self):
    """
    Perform a request to check the health of the torrent that is represented by this widget.
    Don't do this if we are already checking the health or if we have the health info.
    """
    if self.is_health_checking or self.has_health:  # Don't check health again
        return

    self.health_text.setText("checking health...")
    self.set_health_indicator(STATUS_UNKNOWN)
    self.is_health_checking = True
    self.health_request_mgr = TriblerRequestManager()
    self.health_request_mgr.perform_request(
        "torrents/%s/health?timeout=15" % self.torrent_info["infohash"],
        self.on_health_response,
        capture_errors=False,
        priority="LOW",
        on_cancel=self.on_cancel_health_check,
    )
# Buggy code
def __init__(self):
    QWidget.__init__(self)
    self.export_dir = None
    self.filter = DOWNLOADS_FILTER_ALL
    self.download_widgets = {}  # key: infohash, value: QTreeWidgetItem
    self.downloads = None
    self.downloads_timer = QTimer()
    self.downloads_timeout_timer = QTimer()
    self.selected_item = None
    self.dialog = None
    self.downloads_request_mgr = TriblerRequestManager()
    self.request_mgr = None


# Traceback (RuntimeError)
Traceback (most recent call last):
File "/usr/share/tribler/TriblerGUI/event_request_manager.py", line 99, in on_read_data
raise RuntimeError(json_dict["event"]["text"])
RuntimeError: [Failure instance: Traceback: <type 'exceptions.IOError'>: [Errno 24] Too many open files: u'/home/dsk/.Tribler/peercache.txt'
/usr/lib/python2.7/dist-packages/twisted/internet/base.py:1194:run
/usr/lib/python2.7/dist-packages/twisted/internet/base.py:1203:mainLoop
/usr/lib/python2.7/dist-packages/twisted/internet/base.py:825:runUntilCurrent
/usr/lib/python2.7/dist-packages/twisted/internet/task.py:239:__call__
--- <exception caught here> ---
/usr/lib/python2.7/dist-packages/twisted/internet/defer.py:150:maybeDeferred
/usr/share/tribler/Tribler/dispersy/discovery/community.py:801:clean_and_save
]

# Fixed code
def __init__(self):
    QWidget.__init__(self)
    self.export_dir = None
    self.filter = DOWNLOADS_FILTER_ALL
    self.download_widgets = {}  # key: infohash, value: QTreeWidgetItem
    self.downloads = None
    self.downloads_timer = QTimer()
    self.downloads_timeout_timer = QTimer()
    self.downloads_last_update = 0
    self.selected_item = None
    self.dialog = None
    self.downloads_request_mgr = TriblerRequestManager()
    self.request_mgr = None
# Buggy code
def load_downloads(self):
    url = "downloads?get_pieces=1"
    if self.window().download_details_widget.currentIndex() == 3:
        url = "downloads?get_peers=1&get_pieces=1"

    self.downloads_request_mgr.generate_request_id()
    self.downloads_request_mgr.perform_request(url, self.on_received_downloads)


# Traceback (RuntimeError)
Traceback (most recent call last):
File "/usr/share/tribler/TriblerGUI/event_request_manager.py", line 99, in on_read_data
raise RuntimeError(json_dict["event"]["text"])
RuntimeError: [Failure instance: Traceback: <type 'exceptions.IOError'>: [Errno 24] Too many open files: u'/home/dsk/.Tribler/peercache.txt'
/usr/lib/python2.7/dist-packages/twisted/internet/base.py:1194:run
/usr/lib/python2.7/dist-packages/twisted/internet/base.py:1203:mainLoop
/usr/lib/python2.7/dist-packages/twisted/internet/base.py:825:runUntilCurrent
/usr/lib/python2.7/dist-packages/twisted/internet/task.py:239:__call__
--- <exception caught here> ---
/usr/lib/python2.7/dist-packages/twisted/internet/defer.py:150:maybeDeferred
/usr/share/tribler/Tribler/dispersy/discovery/community.py:801:clean_and_save
]

# Fixed code
def load_downloads(self):
    url = "downloads?get_pieces=1"
    if self.window().download_details_widget.currentIndex() == 3:
        url = "downloads?get_peers=1&get_pieces=1"

    if not self.isHidden() or (time.time() - self.downloads_last_update > 30):
        # Update if the downloads page is visible or if we haven't updated for longer than 30 seconds
        self.downloads_last_update = time.time()
        priority = "LOW" if self.isHidden() else "HIGH"
        self.downloads_request_mgr.cancel_request()
        self.downloads_request_mgr = TriblerRequestManager()
        self.downloads_request_mgr.perform_request(
            url, self.on_received_downloads, priority=priority
        )
# Buggy code
def on_exception(self, *exc_info):
    if self.tray_icon:
        self.tray_icon.deleteLater()

    # Stop the download loop
    self.downloads_page.stop_loading_downloads()

    # Add info about whether we are stopping Tribler or not
    os.environ["TRIBLER_SHUTTING_DOWN"] = str(self.core_manager.shutting_down)

    if not self.core_manager.shutting_down:
        self.core_manager.stop(stop_app_on_shutdown=False)

    self.setHidden(True)

    if self.debug_window:
        self.debug_window.setHidden(True)

    exception_text = "".join(traceback.format_exception(*exc_info))
    logging.error(exception_text)

    if not self.feedback_dialog_is_open:
        dialog = FeedbackDialog(
            self,
            exception_text,
            self.core_manager.events_manager.tribler_version,
            self.start_time,
        )
        self.feedback_dialog_is_open = True
        _ = dialog.exec_()


# Traceback (RuntimeError)
Traceback (most recent call last):
File "C:\Users\goqs\Documents\tribler\TriblerGUI\tribler_window.py", line 61, in on_exception
self.tray_icon.deleteLater()
RuntimeError: wrapped C/C++ object of type QSystemTrayIcon has been deleted

# Fixed code
def on_exception(self, *exc_info):
    if self.exception_handler_called:
        # We only show one feedback dialog, even when there are two consecutive exceptions.
        return

    self.exception_handler_called = True

    if self.tray_icon:
        self.tray_icon.deleteLater()

    # Stop the download loop
    self.downloads_page.stop_loading_downloads()

    # Add info about whether we are stopping Tribler or not
    os.environ["TRIBLER_SHUTTING_DOWN"] = str(self.core_manager.shutting_down)

    if not self.core_manager.shutting_down:
        self.core_manager.stop(stop_app_on_shutdown=False)

    self.setHidden(True)

    if self.debug_window:
        self.debug_window.setHidden(True)

    exception_text = "".join(traceback.format_exception(*exc_info))
    logging.error(exception_text)

    if not self.feedback_dialog_is_open:
        dialog = FeedbackDialog(
            self,
            exception_text,
            self.core_manager.events_manager.tribler_version,
            self.start_time,
        )
        self.feedback_dialog_is_open = True
        _ = dialog.exec_()
# Buggy code
def on_start_download_action(self, action):
    if action == 1:
        self.window().perform_start_download_request(
            self.download_uri,
            self.dialog.dialog_widget.anon_download_checkbox.isChecked(),
            self.dialog.dialog_widget.safe_seed_checkbox.isChecked(),
            self.dialog.dialog_widget.destination_input.currentText(),
            self.dialog.get_selected_files(),
            self.dialog.dialog_widget.files_list_view.topLevelItemCount(),
        )

    self.dialog.request_mgr.cancel_request()  # To abort the torrent info request
    self.dialog.setParent(None)
    self.dialog = None
    self.start_download_dialog_active = False

    if (
        action == 0
    ):  # We do this after removing the dialog since process_uri_request is blocking
        self.process_uri_request()


# Traceback (AttributeError)
Traceback (most recent call last):
File "TriblerGUI\tribler_window.py", line 419, in on_start_download_action
AttributeError: 'NoneType' object has no attribute 'dialog_widget'

# Fixed code
def on_start_download_action(self, action):
    if action == 1:
        if self.dialog and self.dialog.dialog_widget:
            self.window().perform_start_download_request(
                self.download_uri,
                self.dialog.dialog_widget.anon_download_checkbox.isChecked(),
                self.dialog.dialog_widget.safe_seed_checkbox.isChecked(),
                self.dialog.dialog_widget.destination_input.currentText(),
                self.dialog.get_selected_files(),
                self.dialog.dialog_widget.files_list_view.topLevelItemCount(),
            )
        else:
            ConfirmationDialog.show_error(
                self, "Tribler UI Error", "Something went wrong. Please try again."
            )
            logging.exception(
                "Error while trying to download. Either dialog or dialog.dialog_widget is None"
            )

    self.dialog.request_mgr.cancel_request()  # To abort the torrent info request
    self.dialog.setParent(None)
    self.dialog = None
    self.start_download_dialog_active = False

    if (
        action == 0
    ):  # We do this after removing the dialog since process_uri_request is blocking
        self.process_uri_request()
# Buggy code
def refresh_all_feeds(self):
    [feed.parse_feed() for feed in self._rss_feed_dict.itervalues()]


# Traceback (TypeError)
Traceback (most recent call last):
File "TriblerGUI/widgets/editchannelpage.py", line 556, in on_rss_feeds_refreshed
TypeError: 'NoneType' object has no attribute '__getitem__'

# Fixed code
def refresh_all_feeds(self):
    deferreds = [feed.parse_feed() for feed in self._rss_feed_dict.itervalues()]
    return DeferredList(deferreds, consumeErrors=True)