gurudesh/pytracebugs huggingface dataset:
# Buggy code
def check_channels_updates(self):
    """
    Check whether there are channels that are updated. If so, download the new version of the channel.
    """
    # FIXME: These naughty try-except-pass workarounds are necessary to keep the loop going in all circumstances

    with db_session:
        channels_queue = list(
            self.session.lm.mds.ChannelMetadata.get_updated_channels()
        )

    for channel in channels_queue:
        try:
            if not self.session.has_download(str(channel.infohash)):
                self._logger.info(
                    "Downloading new channel version %s ver %i->%i",
                    hexlify(str(channel.public_key)),
                    channel.local_version,
                    channel.timestamp,
                )
                self.download_channel(channel)
        except Exception:
            self._logger.exception(
                "Error when tried to download a newer version of channel %s",
                hexlify(channel.public_key),
            )


# Traceback (RuntimeError)
ERROR   1560869708.24            tribler_window:74   (root)  Traceback (most recent call last):
File "/home/quinten/Documents/tribler/TriblerGUI/event_request_manager.py", line 136, in <lambda>
self.reply.error.connect(lambda error: self.on_error(error, reschedule_on_err=reschedule_on_err))
File "/home/quinten/Documents/tribler/TriblerGUI/event_request_manager.py", line 81, in on_error
raise RuntimeError("Could not connect with the Tribler Core within 20 seconds")
RuntimeError: Could not connect with the Tribler Core within 20 seconds

# Fixed code
def check_channels_updates(self):
    """
    Check whether there are channels that are updated. If so, download the new version of the channel.
    """
    # FIXME: These naughty try-except-pass workarounds are necessary to keep the loop going in all circumstances

    with db_session:
        channels = list(self.session.lm.mds.ChannelMetadata.get_updated_channels())

    for channel in channels:
        try:
            if not self.session.has_download(str(channel.infohash)):
                self._logger.info(
                    "Downloading new channel version %s ver %i->%i",
                    hexlify(str(channel.public_key)),
                    channel.local_version,
                    channel.timestamp,
                )
                self.download_channel(channel)
            elif (
                self.session.get_download(str(channel.infohash))
                .get_state()
                .get_status()
                == DLSTATUS_SEEDING
            ):
                self._logger.info(
                    "Processing previously downloaded, but unprocessed channel torrent %s ver %i->%i",
                    hexlify(str(channel.public_key)),
                    channel.local_version,
                    channel.timestamp,
                )
                self.channels_processing_queue.append(channel)
        except Exception:
            self._logger.exception(
                "Error when tried to download a newer version of channel %s",
                hexlify(channel.public_key),
            )
    return self.process_queued_channels()
# Buggy code
def download_channel(self, channel):
    """
    Download a channel with a given infohash and title.
    :param channel: The channel metadata ORM object.
    """
    dcfg = DownloadStartupConfig(state_dir=self.session.config.get_state_dir())
    dcfg.set_dest_dir(self.session.lm.mds.channels_dir)
    dcfg.set_channel_download(True)
    tdef = TorrentDefNoMetainfo(infohash=str(channel.infohash), name=channel.dir_name)
    download = self.session.start_download_from_tdef(tdef, dcfg)

    def on_channel_download_finished(dl):
        channel_dirname = os.path.join(
            self.session.lm.mds.channels_dir, dl.get_def().get_name()
        )
        self.session.lm.mds.process_channel_dir(
            channel_dirname, channel.public_key, channel.id_, external_thread=True
        )
        self.session.lm.mds._db.disconnect()

    def _on_failure(failure):
        self._logger.error("Error when processing channel dir download: %s", failure)

    def _on_success(_):
        with db_session:
            channel_upd = self.session.lm.mds.ChannelMetadata.get(
                public_key=channel.public_key, id_=channel.id_
            )
            channel_upd_dict = channel_upd.to_simple_dict()
        self.session.notifier.notify(
            NTFY_CHANNEL_ENTITY,
            NTFY_UPDATE,
            "%s:%s".format(hexlify(channel.public_key), str(channel.id_)),
            channel_upd_dict,
        )

    finished_deferred = download.finished_deferred.addCallback(
        lambda dl: deferToThread(on_channel_download_finished, dl)
    )
    finished_deferred.addCallbacks(_on_success, _on_failure)

    return download, finished_deferred


# Traceback (RuntimeError)
ERROR   1560869708.24            tribler_window:74   (root)  Traceback (most recent call last):
File "/home/quinten/Documents/tribler/TriblerGUI/event_request_manager.py", line 136, in <lambda>
self.reply.error.connect(lambda error: self.on_error(error, reschedule_on_err=reschedule_on_err))
File "/home/quinten/Documents/tribler/TriblerGUI/event_request_manager.py", line 81, in on_error
raise RuntimeError("Could not connect with the Tribler Core within 20 seconds")
RuntimeError: Could not connect with the Tribler Core within 20 seconds

# Fixed code
def download_channel(self, channel):
    """
    Download a channel with a given infohash and title.
    :param channel: The channel metadata ORM object.
    """
    dcfg = DownloadStartupConfig(state_dir=self.session.config.get_state_dir())
    dcfg.set_dest_dir(self.session.lm.mds.channels_dir)
    dcfg.set_channel_download(True)
    tdef = TorrentDefNoMetainfo(infohash=str(channel.infohash), name=channel.dir_name)
    download = self.session.start_download_from_tdef(tdef, dcfg)

    def _add_channel_to_processing_queue(_):
        self.channels_processing_queue.append(channel)

    finished_deferred = download.finished_deferred.addCallback(
        _add_channel_to_processing_queue
    )

    return download, finished_deferred
# Buggy code
def _on_failure(failure):
    self._logger.error("Error when processing channel dir download: %s", failure)


# Traceback (RuntimeError)
ERROR   1560869708.24            tribler_window:74   (root)  Traceback (most recent call last):
File "/home/quinten/Documents/tribler/TriblerGUI/event_request_manager.py", line 136, in <lambda>
self.reply.error.connect(lambda error: self.on_error(error, reschedule_on_err=reschedule_on_err))
File "/home/quinten/Documents/tribler/TriblerGUI/event_request_manager.py", line 81, in on_error
raise RuntimeError("Could not connect with the Tribler Core within 20 seconds")
RuntimeError: Could not connect with the Tribler Core within 20 seconds

# Fixed code
def _on_failure(failure):
    self._logger.error("Error when processing channel dir download: %s", failure)
    self.processing = False
# Buggy code
def _on_success(_):
    with db_session:
        channel_upd = self.session.lm.mds.ChannelMetadata.get(
            public_key=channel.public_key, id_=channel.id_
        )
        channel_upd_dict = channel_upd.to_simple_dict()
    self.session.notifier.notify(
        NTFY_CHANNEL_ENTITY,
        NTFY_UPDATE,
        "%s:%s".format(hexlify(channel.public_key), str(channel.id_)),
        channel_upd_dict,
    )


# Traceback (RuntimeError)
ERROR   1560869708.24            tribler_window:74   (root)  Traceback (most recent call last):
File "/home/quinten/Documents/tribler/TriblerGUI/event_request_manager.py", line 136, in <lambda>
self.reply.error.connect(lambda error: self.on_error(error, reschedule_on_err=reschedule_on_err))
File "/home/quinten/Documents/tribler/TriblerGUI/event_request_manager.py", line 81, in on_error
raise RuntimeError("Could not connect with the Tribler Core within 20 seconds")
RuntimeError: Could not connect with the Tribler Core within 20 seconds

# Fixed code
def _on_success(_):
    with db_session:
        channel_upd = self.session.lm.mds.ChannelMetadata.get(
            public_key=channel.public_key, id_=channel.id_
        )
        channel_upd_dict = channel_upd.to_simple_dict()
    self.session.notifier.notify(
        NTFY_CHANNEL_ENTITY,
        NTFY_UPDATE,
        "%s:%s".format(hexlify(channel.public_key), str(channel.id_)),
        channel_upd_dict,
    )
    self.processing = False
# Buggy code
def get_state_dir(self):
    return cast_to_unicode_utf8(self._state_dir)


# Traceback (RuntimeError)
Traceback (most recent call last):
File "TriblerGUI\core_manager.py", line 118, in on_received_state
RuntimeError: [Failure instance: Traceback: <type 'exceptions.ValueError'>: The filename, directory name, or volume label syntax is incorrect
run_tribler.py:85:start_tribler
Tribler\Core\Session.py:432:start
lib\site-packages\twisted\internet\defer.py:321:addCallback
lib\site-packages\twisted\internet\defer.py:310:addCallbacks
--- <exception caught here> ---
lib\site-packages\twisted\internet\defer.py:653:_runCallbacks
Tribler\Core\Session.py:429:load_checkpoint
Tribler\Core\Session.py:384:load_checkpoint
Tribler\Core\APIImplementation\LaunchManyCore.py:570:load_checkpoint
Tribler\Core\APIImplementation\LaunchManyCore.py:567:do_load_checkpoint
Tribler\Core\APIImplementation\LaunchManyCore.py:599:resume_download
Tribler\Core\TorrentDef.py:115:load_from_dict
Tribler\Core\TorrentDef.py:68:__init__
]

# Fixed code
def get_state_dir(self):
    return ensure_unicode(self._state_dir, "utf-8")
# Buggy code
def on_file_renamed_alert(self, alert):
    unwanteddir_abs = os.path.join(
        self.get_save_path().decode("utf-8"), self.unwanted_directory_name
    )
    if os.path.exists(unwanteddir_abs) and all(self.handle.file_priorities()):
        shutil.rmtree(unwanteddir_abs, ignore_errors=True)


# Traceback (RuntimeError)
Traceback (most recent call last):
File "TriblerGUI\core_manager.py", line 118, in on_received_state
RuntimeError: [Failure instance: Traceback: <type 'exceptions.ValueError'>: The filename, directory name, or volume label syntax is incorrect
run_tribler.py:85:start_tribler
Tribler\Core\Session.py:432:start
lib\site-packages\twisted\internet\defer.py:321:addCallback
lib\site-packages\twisted\internet\defer.py:310:addCallbacks
--- <exception caught here> ---
lib\site-packages\twisted\internet\defer.py:653:_runCallbacks
Tribler\Core\Session.py:429:load_checkpoint
Tribler\Core\Session.py:384:load_checkpoint
Tribler\Core\APIImplementation\LaunchManyCore.py:570:load_checkpoint
Tribler\Core\APIImplementation\LaunchManyCore.py:567:do_load_checkpoint
Tribler\Core\APIImplementation\LaunchManyCore.py:599:resume_download
Tribler\Core\TorrentDef.py:115:load_from_dict
Tribler\Core\TorrentDef.py:68:__init__
]

# Fixed code
def on_file_renamed_alert(self, alert):
    unwanteddir_abs = os.path.join(
        ensure_unicode(self.get_save_path(), "utf-8"), self.unwanted_directory_name
    )
    if os.path.exists(unwanteddir_abs) and all(self.handle.file_priorities()):
        shutil.rmtree(unwanteddir_abs, ignore_errors=True)
# Buggy code
def __init__(self, metainfo=None, torrent_parameters=None):
    """
    Create a new TorrentDef object, possibly based on existing data.
    :param metainfo: A dictionary with metainfo, i.e. from a .torrent file.
    :param torrent_parameters: User-defined parameters for the new TorrentDef.
    """
    self._logger = logging.getLogger(self.__class__.__name__)
    self.torrent_parameters = {}
    self.metainfo = metainfo
    self.files_list = []
    self.infohash = None
    if metainfo is not None:
        # First, make sure the passed metainfo is valid
        try:
            lt.torrent_info(metainfo)
        except RuntimeError as exc:
            raise ValueError(str(exc))

        self.infohash = sha1(bencode(metainfo[b"info"])).digest()
        self.copy_metainfo_to_torrent_parameters()

    elif torrent_parameters:
        self.torrent_parameters.update(torrent_parameters)


# Traceback (RuntimeError)
Traceback (most recent call last):
File "TriblerGUI\core_manager.py", line 118, in on_received_state
RuntimeError: [Failure instance: Traceback: <type 'exceptions.ValueError'>: The filename, directory name, or volume label syntax is incorrect
run_tribler.py:85:start_tribler
Tribler\Core\Session.py:432:start
lib\site-packages\twisted\internet\defer.py:321:addCallback
lib\site-packages\twisted\internet\defer.py:310:addCallbacks
--- <exception caught here> ---
lib\site-packages\twisted\internet\defer.py:653:_runCallbacks
Tribler\Core\Session.py:429:load_checkpoint
Tribler\Core\Session.py:384:load_checkpoint
Tribler\Core\APIImplementation\LaunchManyCore.py:570:load_checkpoint
Tribler\Core\APIImplementation\LaunchManyCore.py:567:do_load_checkpoint
Tribler\Core\APIImplementation\LaunchManyCore.py:599:resume_download
Tribler\Core\TorrentDef.py:115:load_from_dict
Tribler\Core\TorrentDef.py:68:__init__
]

# Fixed code
def __init__(self, metainfo=None, torrent_parameters=None):
    """
    Create a new TorrentDef object, possibly based on existing data.
    :param metainfo: A dictionary with metainfo, i.e. from a .torrent file.
    :param torrent_parameters: User-defined parameters for the new TorrentDef.
    """
    self._logger = logging.getLogger(self.__class__.__name__)
    self.torrent_parameters = {}
    self.metainfo = metainfo
    self.files_list = []
    self.infohash = None

    if metainfo is not None:
        # This is a workaround to avoid feeding unicode objects to Libtorrent.
        # In fact, this conforms to the 'Unicode Sandwich' model for handling unicode in Python.
        # However, it is too bad that the low-level Libtorrent wrapper does not handle unicode.
        metainfo = convert_dict_unicode_to_bytes(metainfo)

        # First, make sure the passed metainfo is valid
        try:
            lt.torrent_info(metainfo)
        except RuntimeError as exc:
            raise ValueError(str(exc))

        self.infohash = sha1(bencode(metainfo[b"info"])).digest()
        self.copy_metainfo_to_torrent_parameters()

    elif torrent_parameters:
        self.torrent_parameters.update(torrent_parameters)
# Buggy code
def is_torrent_item(self, row_id):
    data_item = self.data_item.data_items[row_id]
    if "infohash" in data_item or (
        "type" in data_item and data_item["type"] == "torrent"
    ):
        return True
    return False


# Traceback (AttributeError)
ERROR   1560332300.05            tribler_window:74   (root)  Traceback (most recent call last):
File "/home/user/Tribler/TriblerGUI/widgets/triblertablecontrollers.py", line 190, in _show_context_menu
if self.selection_has_torrents():
File "/home/user/Tribler/TriblerGUI/widgets/triblertablecontrollers.py", line 205, in selection_has_torrents
if row.model().is_torrent_item(row.row()):
File "/home/user/Tribler/TriblerGUI/widgets/tablecontentmodel.py", line 95, in is_torrent_item
data_item = self.data_item.data_items[row_id]
AttributeError: 'TorrentsContentModel' object has no attribute 'data_item'

# Fixed code
def is_torrent_item(self, row_id):
    data_item = self.data_items[row_id]
    if "infohash" in data_item or (
        "type" in data_item and data_item["type"] == "torrent"
    ):
        return True
    return False
# Buggy code
def is_channel_item(self, row_id):
    data_item = self.data_item.data_items[row_id]
    if "infohash" in data_item or (
        "type" in data_item and data_item["type"] == "torrent"
    ):
        return True
    return False


# Traceback (AttributeError)
ERROR   1560332300.05            tribler_window:74   (root)  Traceback (most recent call last):
File "/home/user/Tribler/TriblerGUI/widgets/triblertablecontrollers.py", line 190, in _show_context_menu
if self.selection_has_torrents():
File "/home/user/Tribler/TriblerGUI/widgets/triblertablecontrollers.py", line 205, in selection_has_torrents
if row.model().is_torrent_item(row.row()):
File "/home/user/Tribler/TriblerGUI/widgets/tablecontentmodel.py", line 95, in is_torrent_item
data_item = self.data_item.data_items[row_id]
AttributeError: 'TorrentsContentModel' object has no attribute 'data_item'

# Fixed code
def is_channel_item(self, row_id):
    data_item = self.data_items[row_id]
    if "infohash" in data_item or (
        "type" in data_item and data_item["type"] == "torrent"
    ):
        return True
    return False
# Buggy code
def consolidate_channel_torrent(self):
    """
    Delete the channel dir contents and create it anew.
    Use it to consolidate fragmented channel torrent directories.
    :param key: The public/private key, used to sign the data
    """

    self.commit_channel_torrent()

    folder = os.path.join(self._channels_dir, self.dir_name)
    for filename in os.listdir(folder):
        file_path = os.path.join(folder, filename)
        # We only remove mdblobs and leave the rest as it is
        if filename.endswith(BLOB_EXTENSION) or filename.endswith(
            BLOB_EXTENSION + ".lz4"
        ):
            os.unlink(file_path)

    # Channel should get a new starting timestamp and its contents should get higher timestamps
    start_timestamp = self._clock.tick()
    for g in self.contents:
        if g.status == COMMITTED:
            g.status = UPDATED
            g.timestamp = self._clock.tick()
            g.sign()

    return self.commit_channel_torrent(new_start_timestamp=start_timestamp)


# Traceback (OSError)
ERROR   1560252155.72       gigachannel_manager:54   (GigaChannelManager)  Error when tried to resume personal channel seeding on GigaChannel Manager startup
Traceback (most recent call last):
File "/home/tribler/tudelft/tribler/Tribler/Core/Modules/gigachannel_manager.py", line 51, in start
TorrentDef.load_from_dict(my_channel.consolidate_channel_torrent())
File "/home/tribler/tudelft/tribler/Tribler/Core/Modules/MetadataStore/OrmBindings/channel_metadata.py", line 169, in consolidate_channel_torrent
for filename in os.listdir(folder):
OSError: [Errno 2] No such file or directory: '/home/tribler/.Tribler/channels/45bc...6'

# Fixed code
def consolidate_channel_torrent(self):
    """
    Delete the channel dir contents and create it anew.
    Use it to consolidate fragmented channel torrent directories.
    :param key: The public/private key, used to sign the data
    """

    self.commit_channel_torrent()

    folder = os.path.join(self._channels_dir, self.dir_name)
    # We check if we need to re-create the channel dir in case it was deleted for some reason
    if not os.path.isdir(folder):
        os.makedirs(folder)
    for filename in os.listdir(folder):
        file_path = os.path.join(folder, filename)
        # We only remove mdblobs and leave the rest as it is
        if filename.endswith(BLOB_EXTENSION) or filename.endswith(
            BLOB_EXTENSION + ".lz4"
        ):
            os.unlink(file_path)

    # Channel should get a new starting timestamp and its contents should get higher timestamps
    start_timestamp = self._clock.tick()
    for g in self.contents:
        if g.status == COMMITTED:
            g.status = UPDATED
            g.timestamp = self._clock.tick()
            g.sign()

    return self.commit_channel_torrent(new_start_timestamp=start_timestamp)
# Buggy code
def get_ui_file_path(filename):
    return os.path.join(get_base_path(), "qt_resources/%s" % filename)


# Traceback (KeyError)
ERROR   1559931217.22            tribler_window:74   (root)  Traceback (most recent call last):
File "/home/vader/src/TRIBLER/Tribler/TriblerGUI/widgets/triblertablecontrollers.py", line 199, in <lambda>
action.triggered.connect(lambda _: callback(item_index))
File "/home/vader/src/TRIBLER/Tribler/TriblerGUI/widgets/lazytableview.py", line 172, in on_add_to_channel_button_clicked
post_data = {"uri": index2uri(row)}
File "/home/vader/src/TRIBLER/Tribler/TriblerGUI/utilities.py", line 20, in index2uri
infohash = index.model().data_items[index.row()][u'infohash']
KeyError: u'infohash'

# Fixed code
def get_ui_file_path(filename):
    return os.path.join(get_base_path(), "qt_resources", filename)
# Buggy code
def get_image_path(filename):
    return os.path.join(get_base_path(), "images/%s" % filename)


# Traceback (KeyError)
ERROR   1559931217.22            tribler_window:74   (root)  Traceback (most recent call last):
File "/home/vader/src/TRIBLER/Tribler/TriblerGUI/widgets/triblertablecontrollers.py", line 199, in <lambda>
action.triggered.connect(lambda _: callback(item_index))
File "/home/vader/src/TRIBLER/Tribler/TriblerGUI/widgets/lazytableview.py", line 172, in on_add_to_channel_button_clicked
post_data = {"uri": index2uri(row)}
File "/home/vader/src/TRIBLER/Tribler/TriblerGUI/utilities.py", line 20, in index2uri
infohash = index.model().data_items[index.row()][u'infohash']
KeyError: u'infohash'

# Fixed code
def get_image_path(filename):
    return os.path.join(get_base_path(), "images", filename)
# Buggy code
def get_checkbox_style(color="#B5B5B5"):
    return """QCheckBox { color: %s; }
            QCheckBox::indicator:checked {image: url('%s'); width:16px; height:16px}
            QCheckBox::indicator:unchecked {image: url('%s'); width:16px; height:16px}
            """ % (
        color,
        get_image_path("checked-yes.png"),
        get_image_path("checked-no.png"),
    )


# Traceback (KeyError)
ERROR   1559931217.22            tribler_window:74   (root)  Traceback (most recent call last):
File "/home/vader/src/TRIBLER/Tribler/TriblerGUI/widgets/triblertablecontrollers.py", line 199, in <lambda>
action.triggered.connect(lambda _: callback(item_index))
File "/home/vader/src/TRIBLER/Tribler/TriblerGUI/widgets/lazytableview.py", line 172, in on_add_to_channel_button_clicked
post_data = {"uri": index2uri(row)}
File "/home/vader/src/TRIBLER/Tribler/TriblerGUI/utilities.py", line 20, in index2uri
infohash = index.model().data_items[index.row()][u'infohash']
KeyError: u'infohash'

# Fixed code
def get_checkbox_style(color="#B5B5B5"):
    return (
        """QCheckBox { color: %s; }
                QCheckBox::indicator:unchecked {border: 1px solid #555;}
                """
        % color
    )
# Buggy code
def on_add_to_channel_button_clicked(self, _):
    for row in self.selectionModel().selectedRows():
        post_data = {"uri": index2uri(row)}
        request_mgr = TriblerRequestManager()
        request_mgr.perform_request(
            "mychannel/torrents", self.on_torrent_added, method="PUT", data=post_data
        )


# Traceback (KeyError)
ERROR   1559931217.22            tribler_window:74   (root)  Traceback (most recent call last):
File "/home/vader/src/TRIBLER/Tribler/TriblerGUI/widgets/triblertablecontrollers.py", line 199, in <lambda>
action.triggered.connect(lambda _: callback(item_index))
File "/home/vader/src/TRIBLER/Tribler/TriblerGUI/widgets/lazytableview.py", line 172, in on_add_to_channel_button_clicked
post_data = {"uri": index2uri(row)}
File "/home/vader/src/TRIBLER/Tribler/TriblerGUI/utilities.py", line 20, in index2uri
infohash = index.model().data_items[index.row()][u'infohash']
KeyError: u'infohash'

# Fixed code
def on_add_to_channel_button_clicked(self, _):
    for row in self.selectionModel().selectedRows():
        if not row.model().is_torrent_item(row.row()):
            continue

        post_data = {"uri": index2uri(row)}
        request_mgr = TriblerRequestManager()
        request_mgr.perform_request(
            "mychannel/torrents", self.on_torrent_added, method="PUT", data=post_data
        )
# Buggy code
def on_subscribe_button_click(self):
    if self.channel_info["state"] == "Personal" or self.channel_info["status"] == 1000:
        return
    self.request_mgr = TriblerRequestManager()
    self.request_mgr.perform_request(
        "metadata/channels/%s" % self.channel_info["public_key"],
        lambda data: self.update_subscribe_button(remote_response=data),
        data={"subscribe": int(not self.channel_info["subscribed"])},
        method="POST",
    )


# Traceback (KeyError)
ERROR   1559931217.22            tribler_window:74   (root)  Traceback (most recent call last):
File "/home/vader/src/TRIBLER/Tribler/TriblerGUI/widgets/triblertablecontrollers.py", line 199, in <lambda>
action.triggered.connect(lambda _: callback(item_index))
File "/home/vader/src/TRIBLER/Tribler/TriblerGUI/widgets/lazytableview.py", line 172, in on_add_to_channel_button_clicked
post_data = {"uri": index2uri(row)}
File "/home/vader/src/TRIBLER/Tribler/TriblerGUI/utilities.py", line 20, in index2uri
infohash = index.model().data_items[index.row()][u'infohash']
KeyError: u'infohash'

# Fixed code
def on_subscribe_button_click(self):
    if self.channel_info["state"] == "Personal" or self.channel_info["status"] == 1000:
        return
    self.request_mgr = TriblerRequestManager()
    self.request_mgr.perform_request(
        "metadata/channels/%s/%i"
        % (self.channel_info["public_key"], self.channel_info["id"]),
        lambda data: self.update_subscribe_button(remote_response=data),
        data={"subscribe": int(not self.channel_info["subscribed"])},
        method="POST",
    )
# Buggy code
def _show_context_menu(self, pos):
    if not self.table_view:
        return

    item_index = self.table_view.indexAt(pos)
    if not item_index or item_index.row() < 0:
        return

    menu = TriblerActionMenu(self.table_view)

    # Single selection menu items
    num_selected = len(self.table_view.selectionModel().selectedRows())
    if num_selected == 1:
        self.add_menu_item(
            menu, " Download ", item_index, self.table_view.on_download_button_clicked
        )
        self.add_menu_item(
            menu, " Play ", item_index, self.table_view.on_play_button_clicked
        )

    if not isinstance(self, MyTorrentsTableViewController):
        self.add_menu_item(
            menu,
            " Add to My Channel ",
            item_index,
            self.table_view.on_add_to_channel_button_clicked,
        )
    else:
        self.add_menu_item(
            menu,
            " Remove from My Channel ",
            item_index,
            self.table_view.on_delete_button_clicked,
        )

    menu.exec_(QCursor.pos())


# Traceback (KeyError)
ERROR   1559931217.22            tribler_window:74   (root)  Traceback (most recent call last):
File "/home/vader/src/TRIBLER/Tribler/TriblerGUI/widgets/triblertablecontrollers.py", line 199, in <lambda>
action.triggered.connect(lambda _: callback(item_index))
File "/home/vader/src/TRIBLER/Tribler/TriblerGUI/widgets/lazytableview.py", line 172, in on_add_to_channel_button_clicked
post_data = {"uri": index2uri(row)}
File "/home/vader/src/TRIBLER/Tribler/TriblerGUI/utilities.py", line 20, in index2uri
infohash = index.model().data_items[index.row()][u'infohash']
KeyError: u'infohash'

# Fixed code
def _show_context_menu(self, pos):
    if not self.table_view:
        return

    item_index = self.table_view.indexAt(pos)
    if not item_index or item_index.row() < 0:
        return

    menu = TriblerActionMenu(self.table_view)

    # Single selection menu items
    num_selected = len(self.table_view.selectionModel().selectedRows())
    if num_selected == 1:
        self.add_menu_item(
            menu, " Download ", item_index, self.table_view.on_download_button_clicked
        )
        self.add_menu_item(
            menu, " Play ", item_index, self.table_view.on_play_button_clicked
        )

    if not isinstance(self, MyTorrentsTableViewController):
        if self.selection_has_torrents():
            self.add_menu_item(
                menu,
                " Add to My Channel ",
                item_index,
                self.table_view.on_add_to_channel_button_clicked,
            )
    else:
        self.add_menu_item(
            menu,
            " Remove from My Channel ",
            item_index,
            self.table_view.on_delete_button_clicked,
        )

    menu.exec_(QCursor.pos())
# Buggy code
def take_step(self):
    """
    We are asked to update, see if we have enough peers to start culling them.
    If we do have enough peers, select a suitable peer to remove.

    :returns: None
    """
    with self.walk_lock:
        peer_count = len(self.overlay.get_peers())
        if peer_count > self.target_peers:
            exit_count = len(self.overlay.exit_candidates)
            ratio = 1.0 - exit_count / peer_count  # Peer count is > 0 per definition
            exit_peers = set(self.overlay.exit_candidates.values())
            if ratio < self.golden_ratio:
                self.overlay.network.remove_peer(sample(exit_peers, 1)[0])
            elif ratio > self.golden_ratio:
                self.overlay.network.remove_peer(
                    sample(set(self.overlay.get_peers()) - exit_peers, 1)[0]
                )


# Traceback (AttributeError)
ERROR   1560247763.36              ipv8_service:144  (root)  Exception occurred while trying to walk!
Traceback (most recent call last):
File "/home/vader/src/TRIBLER/Tribler/Tribler/pyipv8/ipv8_service.py", line 141, in on_tick
strategy.take_step()
File "/home/vader/src/TRIBLER/Tribler/Tribler/community/triblertunnel/discovery.py", line 47, in take_step
exit_count = len(self.overlay.exit_candidates)
AttributeError: 'TriblerTunnelCommunity' object has no attribute 'exit_candidates'

# Fixed code
def take_step(self):
    """
    We are asked to update, see if we have enough peers to start culling them.
    If we do have enough peers, select a suitable peer to remove.

    :returns: None
    """
    with self.walk_lock:
        peer_count = len(self.overlay.get_peers())
        if peer_count > self.target_peers:
            exit_peers = set(self.overlay.get_candidates(PEER_FLAG_EXIT_ANY))
            exit_count = len(exit_peers)
            ratio = 1.0 - exit_count / peer_count  # Peer count is > 0 per definition
            if ratio < self.golden_ratio:
                self.overlay.network.remove_peer(sample(exit_peers, 1)[0])
            elif ratio > self.golden_ratio:
                self.overlay.network.remove_peer(
                    sample(set(self.overlay.get_peers()) - exit_peers, 1)[0]
                )
# Buggy code
def _task_process_alerts(self):
    for hops, ltsession in self.ltsessions.items():
        if ltsession:
            for alert in ltsession.pop_alerts():
                self.process_alert(alert, hops=hops)

    # We have a separate session for metainfo requests.
    # For this session we are only interested in the metadata_received_alert.
    if self.ltsession_metainfo:
        for alert in self.ltsession_metainfo.pop_alerts():
            if isinstance(alert, lt.metadata_received_alert):
                self.got_metainfo(str(alert.handle.info_hash()))
            elif alert.__class__.__name__ == "dht_pkt_alert":
                # We received a raw DHT message - decode it and check whether it is a BEP33 message.
                decoded = bdecode(alert.pkt_buf)
                if "r" in decoded:
                    if "BFsd" in decoded["r"] and "BFpe" in decoded["r"]:
                        self.dht_health_manager.received_bloomfilters(
                            decoded["r"]["id"],
                            bytearray(decoded["r"]["BFsd"]),
                            bytearray(decoded["r"]["BFpe"]),
                        )


# Traceback (RuntimeError)
Traceback (most recent call last):
File "TriblerGUI/event_request_manager.py", line 114, in on_read_data
RuntimeError: [Failure instance: Traceback: <type 'exceptions.TypeError'>: argument of type 'NoneType' is not iterable
twisted/internet/base.py:1199:run
twisted/internet/base.py:1208:mainLoop
twisted/internet/base.py:828:runUntilCurrent
twisted/internet/task.py:239:__call__
--- <exception caught here> ---
twisted/internet/defer.py:150:maybeDeferred
Tribler/Core/Libtorrent/LibtorrentMgr.py:603:_task_process_alerts
]

# Fixed code
def _task_process_alerts(self):
    for hops, ltsession in self.ltsessions.items():
        if ltsession:
            for alert in ltsession.pop_alerts():
                self.process_alert(alert, hops=hops)

    # We have a separate session for metainfo requests.
    # For this session we are only interested in the metadata_received_alert.
    if self.ltsession_metainfo:
        for alert in self.ltsession_metainfo.pop_alerts():
            if isinstance(alert, lt.metadata_received_alert):
                self.got_metainfo(str(alert.handle.info_hash()))
            elif alert.__class__.__name__ == "dht_pkt_alert":
                # We received a raw DHT message - decode it and check whether it is a BEP33 message.
                decoded = bdecode(alert.pkt_buf)
                if decoded and "r" in decoded:
                    if "BFsd" in decoded["r"] and "BFpe" in decoded["r"]:
                        self.dht_health_manager.received_bloomfilters(
                            decoded["r"]["id"],
                            bytearray(decoded["r"]["BFsd"]),
                            bytearray(decoded["r"]["BFpe"]),
                        )
# Buggy code
def data(self, index, role):
    # Return tooltip for state indicator column
    if role == Qt.ToolTipRole:
        if index.column() == self.column_position["state"]:
            return self.data_items[index.row()]["state"]
        return None
    else:
        return super(StateTooltipMixin, self).data(index, role)


# Traceback (KeyError)
Aggregate stacktrace (# of reports: 1) More details
Traceback (most recent call last):
File "TriblerGUI\widgets\tablecontentmodel.py", line 153, in data
KeyError: u'state'

# Fixed code
def data(self, index, role):
    # Return tooltip for state indicator column
    if role == Qt.ToolTipRole:
        if index.column() == self.column_position["state"]:
            return self.data_items[index.row()].get("state")
        return None
    else:
        return super(StateTooltipMixin, self).data(index, role)
# Buggy code
def on_mouse_press_event(self, event):
    self.selected_node = dict()
    enclosing_nodes = self.scatter_nodes.contains(event)
    # Example value for enclosing nodes: (True, {'ind': array([ 71, 340], dtype=int32)})
    if enclosing_nodes[0]:
        index = enclosing_nodes[1]["ind"][-1]
        self.selected_node["public_key"] = self.node_positions.keys()[index]
        self.redraw = True


# Traceback (AttributeError)
Traceback (most recent call last):
File "lib\site-packages\matplotlib\backends\backend_qt5.py", line 289, in mousePressEvent
File     "lib\site-packages\matplotlib\backend_bases.py", line 1917, in button_press_event
File "lib\site-packages\matplotlib\cbook.py", line 554, in process
File "lib\site-packages\matplotlib\cbook.py", line 416, in __call__
File     "TriblerGUI\widgets\trustgraphpage.py", line 207, in on_mouse_press_event
AttributeError: 'list' object has no attribute 'contains'

# Fixed code
def on_mouse_press_event(self, event):
    if not self.scatter_nodes:
        return
    self.selected_node = dict()
    enclosing_nodes = self.scatter_nodes.contains(event)
    # Example value for enclosing nodes: (True, {'ind': array([ 71, 340], dtype=int32)})
    if enclosing_nodes[0]:
        index = enclosing_nodes[1]["ind"][-1]
        self.selected_node["public_key"] = self.node_positions.keys()[index]
        self.redraw = True
# Buggy code
def consolidate_channel_torrent(self):
    """
    Delete the channel dir contents and create it anew.
    Use it to consolidate fragmented channel torrent directories.
    :param key: The public/private key, used to sign the data
    """

    self.commit_channel_torrent()

    folder = os.path.join(self._channels_dir, self.dir_name)
    for filename in os.listdir(folder):
        file_path = os.path.join(folder, filename)
        # We only remove mdblobs and leave the rest as it is
        if filename.endswith(BLOB_EXTENSION) or filename.endswith(
            BLOB_EXTENSION + ".lz4"
        ):
            os.unlink(file_path)

    # Channel should get a new starting timestamp and its contents should get higher timestamps
    start_timestamp = self._clock.tick()
    for g in self.contents:
        if g.status == COMMITTED:
            g.status = UPDATED
            g.timestamp = self._clock.tick()
            g.sign()

    self.commit_channel_torrent(new_start_timestamp=start_timestamp)


# Traceback (IOError)
Traceback (most recent call last):
File "/home/tribler/tudelft/tribler2/Tribler/Core/Modules/gigachannel_manager.py", line 42, in start
self.updated_my_channel(TorrentDef.load(torrent_path))
File "/home/tribler/tudelft/tribler2/Tribler/Core/TorrentDef.py", line 96, in load
with open(filepath, "rb") as torrent_file:
IOError: [Errno 2] No such file or directory: u'/home/tribler/.Tribler/channels/930eb3fd3a776932e4c74bb64bed9128.torrent'

# Fixed code
def consolidate_channel_torrent(self):
    """
    Delete the channel dir contents and create it anew.
    Use it to consolidate fragmented channel torrent directories.
    :param key: The public/private key, used to sign the data
    """

    self.commit_channel_torrent()

    folder = os.path.join(self._channels_dir, self.dir_name)
    for filename in os.listdir(folder):
        file_path = os.path.join(folder, filename)
        # We only remove mdblobs and leave the rest as it is
        if filename.endswith(BLOB_EXTENSION) or filename.endswith(
            BLOB_EXTENSION + ".lz4"
        ):
            os.unlink(file_path)

    # Channel should get a new starting timestamp and its contents should get higher timestamps
    start_timestamp = self._clock.tick()
    for g in self.contents:
        if g.status == COMMITTED:
            g.status = UPDATED
            g.timestamp = self._clock.tick()
            g.sign()

    return self.commit_channel_torrent(new_start_timestamp=start_timestamp)
# Buggy code
def cleanup_pony_experimental_db(new_database_path):
    # Check for the old experimental version database
    # ACHTUNG!!! NUCLEAR OPTION!!! DO NOT MESS WITH IT!!!
    connection = sqlite3.connect(new_database_path)
    with connection:
        cursor = connection.cursor()
        cursor.execute(
            "SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'MiscData'"
        )
        result = cursor.fetchone()
        delete_old_pony_db = not bool(result[0] if result else False)
    connection.close()
    # We're looking at the old experimental version database. Delete it.
    if delete_old_pony_db:
        os.unlink(new_database_path)


# Traceback (IOError)
Traceback (most recent call last):
File "/home/tribler/tudelft/tribler2/Tribler/Core/Modules/gigachannel_manager.py", line 42, in start
self.updated_my_channel(TorrentDef.load(torrent_path))
File "/home/tribler/tudelft/tribler2/Tribler/Core/TorrentDef.py", line 96, in load
with open(filepath, "rb") as torrent_file:
IOError: [Errno 2] No such file or directory: u'/home/tribler/.Tribler/channels/930eb3fd3a776932e4c74bb64bed9128.torrent'

# Fixed code
def cleanup_pony_experimental_db(new_database_path):
    # Check for the old experimental version database
    # ACHTUNG!!! NUCLEAR OPTION!!! DO NOT MESS WITH IT!!!
    connection = sqlite3.connect(new_database_path)
    with connection:
        cursor = connection.cursor()
        cursor.execute(
            "SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'MiscData'"
        )
        result = cursor.fetchone()
        delete_old_pony_db = not bool(result[0] if result else False)
        if not delete_old_pony_db:
            cursor.execute('SELECT value FROM MiscData WHERE name == "db_version"')
            version = int(cursor.fetchone()[0])
            delete_old_pony_db = (
                version in BETA_DB_VERSIONS
            )  # Delete the older betas DB
    connection.close()
    # We're looking at the old experimental version database. Delete it.
    if delete_old_pony_db:
        os.unlink(new_database_path)
# Buggy code
def new_db_version_ok(new_database_path):
    # Let's check if we converted all/some entries before
    connection = sqlite3.connect(new_database_path)
    with connection:
        cursor = connection.cursor()
        cursor.execute('SELECT value FROM MiscData WHERE name == "db_version"')
        version = int(cursor.fetchone()[0])
        if version != 0:
            return False
    connection.close()
    return True


# Traceback (IOError)
Traceback (most recent call last):
File "/home/tribler/tudelft/tribler2/Tribler/Core/Modules/gigachannel_manager.py", line 42, in start
self.updated_my_channel(TorrentDef.load(torrent_path))
File "/home/tribler/tudelft/tribler2/Tribler/Core/TorrentDef.py", line 96, in load
with open(filepath, "rb") as torrent_file:
IOError: [Errno 2] No such file or directory: u'/home/tribler/.Tribler/channels/930eb3fd3a776932e4c74bb64bed9128.torrent'

# Fixed code
def new_db_version_ok(new_database_path):
    # Let's check if we converted all/some entries before
    connection = sqlite3.connect(new_database_path)
    with connection:
        cursor = connection.cursor()
        cursor.execute('SELECT value FROM MiscData WHERE name == "db_version"')
        version = int(cursor.fetchone()[0])
        if version != CURRENT_DB_VERSION:
            return False
    connection.close()
    return True
# Buggy code
def should_upgrade(old_database_path, new_database_path, logger=None):
    """
    Decide if we can migrate data from old DB to Pony
    :return: False if something goes wrong, or we don't need/cannot migrate data
    """
    if not os.path.exists(old_database_path):
        # no old DB to upgrade
        return False

    try:
        if not old_db_version_ok(old_database_path):
            return False
    except:
        logger.error("Can't open the old tribler.sdb file")
        return False

    if os.path.exists(new_database_path):
        try:
            cleanup_pony_experimental_db(new_database_path)
            if not new_db_version_ok(new_database_path):
                return False
            if already_upgraded(new_database_path):
                return False
        except:
            logger.error("Error while trying to open Pony DB file ", new_database_path)
            return False

    return True


# Traceback (IOError)
Traceback (most recent call last):
File "/home/tribler/tudelft/tribler2/Tribler/Core/Modules/gigachannel_manager.py", line 42, in start
self.updated_my_channel(TorrentDef.load(torrent_path))
File "/home/tribler/tudelft/tribler2/Tribler/Core/TorrentDef.py", line 96, in load
with open(filepath, "rb") as torrent_file:
IOError: [Errno 2] No such file or directory: u'/home/tribler/.Tribler/channels/930eb3fd3a776932e4c74bb64bed9128.torrent'

# Fixed code
def should_upgrade(old_database_path, new_database_path, logger=None):
    """
    Decide if we can migrate data from old DB to Pony
    :return: False if something goes wrong, or we don't need/cannot migrate data
    """
    if not os.path.exists(old_database_path):
        # no old DB to upgrade
        return False

    try:
        if not old_db_version_ok(old_database_path):
            return False
    except:
        logger.error("Can't open the old tribler.sdb file")
        return False

    if os.path.exists(new_database_path):
        try:
            if not new_db_version_ok(new_database_path):
                return False
            if already_upgraded(new_database_path):
                return False
        except:
            logger.error(
                "Error while trying to open Pony DB file %s", new_database_path
            )
            return False

    return True
# Buggy code
def upgrade_72_to_pony(self):
    old_database_path = os.path.join(
        self.session.config.get_state_dir(), "sqlite", "tribler.sdb"
    )
    new_database_path = os.path.join(
        self.session.config.get_state_dir(), "sqlite", "metadata.db"
    )
    channels_dir = os.path.join(self.session.config.get_chant_channels_dir())

    self._dtp72 = DispersyToPonyMigration(
        old_database_path, self.update_status, logger=self._logger
    )
    if not should_upgrade(old_database_path, new_database_path, logger=self._logger):
        self._dtp72 = None
        return succeed(None)
    # This thing is here mostly for the skip upgrade test to work...
    self._dtp72.shutting_down = self.skip_upgrade_called
    self.notify_starting()
    # We have to create the Metadata Store object because the LaunchManyCore has not been started yet
    mds = MetadataStore(
        new_database_path,
        channels_dir,
        self.session.trustchain_keypair,
        disable_sync=True,
    )
    self._dtp72.initialize(mds)

    def finish_migration(_):
        mds.shutdown()
        self.notify_done()

    def log_error(failure):
        self._logger.error("Error in Upgrader callback chain: %s", failure)

    return self._dtp72.do_migration().addCallbacks(finish_migration, log_error)


# Traceback (IOError)
Traceback (most recent call last):
File "/home/tribler/tudelft/tribler2/Tribler/Core/Modules/gigachannel_manager.py", line 42, in start
self.updated_my_channel(TorrentDef.load(torrent_path))
File "/home/tribler/tudelft/tribler2/Tribler/Core/TorrentDef.py", line 96, in load
with open(filepath, "rb") as torrent_file:
IOError: [Errno 2] No such file or directory: u'/home/tribler/.Tribler/channels/930eb3fd3a776932e4c74bb64bed9128.torrent'

# Fixed code
def upgrade_72_to_pony(self):
    old_database_path = os.path.join(
        self.session.config.get_state_dir(), "sqlite", "tribler.sdb"
    )
    new_database_path = os.path.join(
        self.session.config.get_state_dir(), "sqlite", "metadata.db"
    )
    channels_dir = os.path.join(self.session.config.get_chant_channels_dir())

    if os.path.exists(new_database_path):
        cleanup_pony_experimental_db(new_database_path)

    self._dtp72 = DispersyToPonyMigration(
        old_database_path, self.update_status, logger=self._logger
    )
    if not should_upgrade(old_database_path, new_database_path, logger=self._logger):
        self._dtp72 = None
        return succeed(None)
    # This thing is here mostly for the skip upgrade test to work...
    self._dtp72.shutting_down = self.skip_upgrade_called
    self.notify_starting()
    # We have to create the Metadata Store object because the LaunchManyCore has not been started yet
    mds = MetadataStore(
        new_database_path,
        channels_dir,
        self.session.trustchain_keypair,
        disable_sync=True,
    )
    self._dtp72.initialize(mds)

    def finish_migration(_):
        mds.shutdown()
        self.notify_done()

    def log_error(failure):
        self._logger.error("Error in Upgrader callback chain: %s", failure)

    return self._dtp72.do_migration().addCallbacks(finish_migration, log_error)
# Buggy code
def to_simple_dict(self):
    """
    Return a basic dictionary with information about the channel.
    """
    return {
        "id": self.rowid,
        "public_key": hexlify(self.public_key),
        "name": self.title,
        "torrents": self.contents_len,
        "subscribed": self.subscribed,
        "votes": self.votes,
        "status": self.status,
        "updated": self.timestamp,
        # TODO: optimize this?
        "my_channel": database_blob(self._my_key.pub().key_to_bin()[10:])
        == database_blob(self.public_key),
    }


# Traceback (ValueError)
ERROR   1551977540.15            tribler_window:67   (root)  Traceback (most recent call last):
File "/home/vader/src/TRIBLER/tribler_ichorid/TriblerGUI/widgets/tablecontentmodel.py", line 91, in data
if column in self.column_display_filters else data
File "/home/vader/src/TRIBLER/tribler_ichorid/TriblerGUI/widgets/tablecontentmodel.py", line 168, in <lambda>
u'updated': lambda date: pretty_date(date // 1000),
File "/home/vader/src/TRIBLER/tribler_ichorid/TriblerGUI/utilities.py", line 96, in pretty_date
diff = now - datetime.fromtimestamp(time)
ValueError: year is out of range

# Fixed code
def to_simple_dict(self):
    """
    Return a basic dictionary with information about the channel.
    """
    epoch = datetime.utcfromtimestamp(0)

    return {
        "id": self.rowid,
        "public_key": hexlify(self.public_key),
        "name": self.title,
        "torrents": self.contents_len,
        "subscribed": self.subscribed,
        "votes": self.votes,
        "status": self.status,
        "updated": int((self.torrent_date - epoch).total_seconds()),
        # TODO: optimize this?
        "my_channel": database_blob(self._my_key.pub().key_to_bin()[10:])
        == database_blob(self.public_key),
    }