gurudesh/pytracebugs huggingface dataset:
# Buggy code
def __init__(self, parent, name, series, **kargs):
    axisItems = {"bottom": DateAxisItem("bottom")}
    super(TimeSeriesPlot, self).__init__(
        parent=parent, title=name, axisItems=axisItems, **kargs
    )
    self.getPlotItem().showGrid(x=True, y=True)
    self.setBackground("#202020")
    self.setAntialiasing(True)
    self.setMenuEnabled(False)

    self.series = None
    self.plot_data = [[], []]
    self.plots = []
    self.series = series
    self.last_timestamp = 0

    legend = pg.LegendItem((150, 25 * len(series)), offset=(150, 30))
    legend.setParentItem(self.graphicsItem())

    for serie in series:
        self.plot_data[1].append([])

        plot = self.plot(**serie)
        self.plots.append(plot)
        legend.addItem(plot, serie["name"])

    # Limit the date range
    self.setLimits(xMin=BITTORRENT_BIRTHDAY, xMax=time.time() + YEAR_SPACING)


# Traceback (TypeError)
ERROR   1571752934.05            tribler_window:108  (root)  Traceback (most recent call last):
File "/home/quinten/.local/lib/python2.7/site-packages/pyqtgraph/graphicsItems/PlotCurveItem.py", line 175, in boundingRect
(ymn, ymx) = self.dataBounds(ax=1)
File "/home/quinten/.local/lib/python2.7/site-packages/pyqtgraph/graphicsItems/PlotCurveItem.py", line 132, in dataBounds
if any(np.isinf(b)):
TypeError: ufunc 'isinf' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

# Fixed code
def __init__(self, parent, name, series, **kargs):
    axisItems = {"bottom": DateAxisItem("bottom")}
    super(TimeSeriesPlot, self).__init__(
        parent=parent, title=name, axisItems=axisItems, **kargs
    )
    self.getPlotItem().showGrid(x=True, y=True)
    self.setBackground("#202020")
    self.setAntialiasing(True)
    self.setMenuEnabled(False)

    self.plot_data = {}
    self.plots = []
    self.series = series
    self.last_timestamp = 0

    legend = pg.LegendItem((150, 25 * len(series)), offset=(150, 30))
    legend.setParentItem(self.graphicsItem())

    for serie in series:
        plot = self.plot(**serie)
        self.plots.append(plot)
        legend.addItem(plot, serie["name"])

    # Limit the date range
    self.setLimits(xMin=BITTORRENT_BIRTHDAY, xMax=time.time() + YEAR_SPACING)
# Buggy code
def reset_plot(self):
    self.plot_data = [[], [[] for _ in self.plots]]


# Traceback (TypeError)
ERROR   1571752934.05            tribler_window:108  (root)  Traceback (most recent call last):
File "/home/quinten/.local/lib/python2.7/site-packages/pyqtgraph/graphicsItems/PlotCurveItem.py", line 175, in boundingRect
(ymn, ymx) = self.dataBounds(ax=1)
File "/home/quinten/.local/lib/python2.7/site-packages/pyqtgraph/graphicsItems/PlotCurveItem.py", line 132, in dataBounds
if any(np.isinf(b)):
TypeError: ufunc 'isinf' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

# Fixed code
def reset_plot(self):
    self.plot_data = {}
# Buggy code
def add_data(self, timestamp, data, skip_old=False):
    if skip_old and timestamp < self.last_timestamp:
        return
    self.plot_data[0].append(timestamp)
    for i, data_item in enumerate(data):
        self.plot_data[1][i].append(data_item)
    self.last_timestamp = timestamp


# Traceback (TypeError)
ERROR   1571752934.05            tribler_window:108  (root)  Traceback (most recent call last):
File "/home/quinten/.local/lib/python2.7/site-packages/pyqtgraph/graphicsItems/PlotCurveItem.py", line 175, in boundingRect
(ymn, ymx) = self.dataBounds(ax=1)
File "/home/quinten/.local/lib/python2.7/site-packages/pyqtgraph/graphicsItems/PlotCurveItem.py", line 132, in dataBounds
if any(np.isinf(b)):
TypeError: ufunc 'isinf' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

# Fixed code
def add_data(self, timestamp, data):
    self.plot_data[timestamp] = data
# Buggy code
def render_plot(self):
    for i, plot in enumerate(self.plots):
        plot.setData(
            y=pg.np.array(self.plot_data[1][i]), x=pg.np.array(self.plot_data[0])
        )


# Traceback (TypeError)
ERROR   1571752934.05            tribler_window:108  (root)  Traceback (most recent call last):
File "/home/quinten/.local/lib/python2.7/site-packages/pyqtgraph/graphicsItems/PlotCurveItem.py", line 175, in boundingRect
(ymn, ymx) = self.dataBounds(ax=1)
File "/home/quinten/.local/lib/python2.7/site-packages/pyqtgraph/graphicsItems/PlotCurveItem.py", line 132, in dataBounds
if any(np.isinf(b)):
TypeError: ufunc 'isinf' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

# Fixed code
def render_plot(self):
    for i, plot in enumerate(self.plots):
        plot.setData(
            x=pg.np.array(list(self.plot_data.keys())),
            y=pg.np.array([data[i] for data in self.plot_data.values()]),
        )
# Buggy code
def get_node_size(self, node):
    # User root node is bigger than normal nodes
    min_size = 0.01 if node["key"] != self.root_public_key else 0.05

    diff = abs(node.get("total_up", 0) - node.get("total_down", 0))
    if diff == 0:
        return min_size

    # magic function to set the node size based on their balance
    return math.log(diff / (1024 * 1024), 2) / 512 + min_size


# Traceback (TypeError)
ERROR   1571752934.05            tribler_window:108  (root)  Traceback (most recent call last):
File "/home/quinten/.local/lib/python2.7/site-packages/pyqtgraph/graphicsItems/PlotCurveItem.py", line 175, in boundingRect
(ymn, ymx) = self.dataBounds(ax=1)
File "/home/quinten/.local/lib/python2.7/site-packages/pyqtgraph/graphicsItems/PlotCurveItem.py", line 132, in dataBounds
if any(np.isinf(b)):
TypeError: ufunc 'isinf' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

# Fixed code
def get_node_size(self, node):
    # User root node is bigger than normal nodes
    min_size = 0.01 if node["key"] != self.root_public_key else 0.05

    diff = abs(node.get("total_up", 0) - node.get("total_down", 0))
    if diff == 0:
        return min_size
    elif diff > 10 * TB:  # max token balance limit
        return 0.06  # max node size in graph
    elif diff > TB:
        return 0.05 + 0.005 * diff / TB  # 0.005 for each extra TB of balance
    return math.log(diff / (1024 * 1024), 2) / 512 + min_size
# Buggy code
def start_bootstrap_download(self):
    if self.session.config.get_bootstrap_enabled():
        if not self.payout_manager:
            self._logger.warn("Running bootstrap without payout enabled")
        self.bootstrap = Bootstrap(
            self.session.config.get_state_dir(), dht=self.dht_community
        )
        if os.path.exists(self.bootstrap.bootstrap_file):
            self.bootstrap.start_initial_seeder(
                self.session.start_download_from_tdef,
                self.bootstrap.bootstrap_file,
                self.session.config.get_bootstrap_infohash(),
            )
        else:
            self.bootstrap.start_by_infohash(
                self.session.start_download_from_tdef,
                self.session.config.get_bootstrap_infohash(),
            )


# Traceback (RuntimeError)
Traceback (most recent call last):
File "TriblerGUI\event_request_manager.py", line 114, in on_read_data
RuntimeError: [Failure instance: Traceback: <class 'sqlite3.OperationalError'>: no such table: `locks
lib\threading.py:801:__bootstrap_inner
lib\threading.py:754:run
lib\site-packages\twisted\_threads\_threadworker.py:46:work
lib\site-packages\twisted\_threads\_team.py:190:doWork
--- <exception caught here> ---
lib\site-packages\twisted\python\threadpool.py:250:inContext
lib\site-packages\twisted\python\threadpool.py:266:<lambda>
lib\site-packages\twisted\python\context.py:122:callWithContext
lib\site-packages\twisted\python\context.py:85:callWithContext
Tribler\Core\APIImplementation\LaunchManyCore.py:547:sesscb_states_callback
ipv8\database.py:56:wrapper
ipv8\database.py:333:executescript
]

# Fixed code
def start_bootstrap_download(self):
    if self.session.config.get_bootstrap_enabled():
        if not self.payout_manager:
            self._logger.warn("Running bootstrap without payout enabled")
        self.bootstrap = Bootstrap(
            self.session.config.get_state_dir(), dht=self.dht_community
        )
        self.bootstrap.start_by_infohash(
            self.session.start_download_from_tdef,
            self.session.config.get_bootstrap_infohash(),
        )
# Buggy code
def reset_player(self):
    """
    Reset the video player, i.e. when a download is removed that was being played.
    """
    self.active_infohash = ""
    self.active_index = -1
    self.window().left_menu_playlist.clear()
    self.window().video_player_header_label.setText("")
    self.mediaplayer.stop()
    self.mediaplayer.set_media(None)
    self.media = None
    self.window().video_player_play_pause_button.setIcon(self.play_icon)
    self.window().video_player_play_pause_button.setEnabled(False)
    self.window().video_player_position_slider.setValue(0)
    self.window().video_player_info_button.hide()


# Traceback (AttributeError)
Traceback (most recent call last):
File "TriblerGUI\widgets\downloadspage.py", line 342, in on_remove_download_dialog
File "TriblerGUI\widgets\videoplayerpage.py", line 239, in reset_player
AttributeError: 'NoneType' object has no attribute 'stop'

# Fixed code
def reset_player(self):
    """
    Reset the video player, i.e. when a download is removed that was being played.
    """
    self.active_infohash = ""
    self.active_index = -1
    self.window().left_menu_playlist.clear()
    self.window().video_player_header_label.setText("")

    if self.mediaplayer:
        self.mediaplayer.stop()
        self.mediaplayer.set_media(None)
    self.media = None
    self.window().video_player_play_pause_button.setIcon(self.play_icon)
    self.window().video_player_play_pause_button.setEnabled(False)
    self.window().video_player_position_slider.setValue(0)
    self.window().video_player_info_button.hide()
# Buggy code
def _do_popup(title, text):
    """
    Create a native pop-up without any third party dependency.

    :param title: the pop-up title
    :param text: the pop-up body
    """
    try:
        import win32api

        win32api.MessageBox(0, text, title)
    except ImportError:
        os.system('xmessage -center "$(printf "%s")"' % (text))
    sep = "*" * 20
    print("\n".join([sep, title, sep, text, sep]), file=sys.stderr)


# Traceback (AttributeError)
Traceback (most recent call last):
File "TriblerGUI\widgets\downloadspage.py", line 342, in on_remove_download_dialog
File "TriblerGUI\widgets\videoplayerpage.py", line 239, in reset_player
AttributeError: 'NoneType' object has no attribute 'stop'

# Fixed code
def _do_popup(title, text):
    """
    Create a native pop-up without any third party dependency.

    :param title: the pop-up title
    :param text: the pop-up body
    """
    try:
        import win32api

        win32api.MessageBox(0, text, title)
    except ImportError:
        import subprocess

        subprocess.Popen(["xmessage", "-center", text], shell=False)
    sep = "*" * 20
    print("\n".join([sep, title, sep, text, sep]), file=sys.stderr)
# Buggy code
def update_channel_commit_views(self, deleted_index=None):
    if self.channel_dirty and self.autocommit_enabled:
        self.commit_timer.stop()
        self.commit_timer.start(CHANNEL_COMMIT_DELAY)
        if deleted_index:
            # TODO: instead of reloading the whole table, just remove the deleted row and update start and end
            self.load_my_torrents()

    self.window().commit_control_bar.setHidden(
        not self.channel_dirty or self.autocommit_enabled
    )


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

# Fixed code
def update_channel_commit_views(self, reload_view=False):
    if self.channel_dirty and self.autocommit_enabled:
        self.commit_timer.stop()
        self.commit_timer.start(CHANNEL_COMMIT_DELAY)
        if reload_view:
            self.load_my_torrents()

    self.window().commit_control_bar.setHidden(
        not self.channel_dirty or self.autocommit_enabled
    )
# Buggy code
def on_subscribe_control_clicked(self, index):
    item = index.model().data_items[index.row()]
    # skip LEGACY entries, regular torrents and personal channel
    if (
        "subscribed" not in item
        or item["status"] == 1000
        or item["state"] == "Personal"
    ):
        return
    status = int(item["subscribed"])
    public_key = item["public_key"]
    id_ = item["id"]

    def update_item(request_data):
        data_item_dict = index.model().data_items[index.row()]
        for key, _ in data_item_dict.items():
            if key in request_data:
                data_item_dict[key] = request_data[key]

    request_mgr = TriblerRequestManager()
    request_mgr.perform_request(
        "metadata/channels/%s/%i" % (public_key, id_),
        update_item,
        data={"subscribe": int(not status)},
        method="POST",
    )


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

# Fixed code
def on_subscribe_control_clicked(self, index):
    item = index.model().data_items[index.row()]
    # skip LEGACY entries, regular torrents and personal channel
    if (
        "subscribed" not in item
        or item["status"] == 1000
        or item["state"] == "Personal"
    ):
        return
    status = int(item["subscribed"])
    public_key = item["public_key"]
    id_ = item["id"]
    data_item_dict = index.model().data_items[index.row()]

    def update_item(request_data):
        for key, _ in data_item_dict.items():
            if key in request_data:
                data_item_dict[key] = request_data[key]

    request_mgr = TriblerRequestManager()
    request_mgr.perform_request(
        "metadata/channels/%s/%i" % (public_key, id_),
        update_item,
        data={"subscribe": int(not status)},
        method="POST",
    )
# Buggy code
def update_item(request_data):
    data_item_dict = index.model().data_items[index.row()]
    for key, _ in data_item_dict.items():
        if key in request_data:
            data_item_dict[key] = request_data[key]


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

# Fixed code
def update_item(request_data):
    for key, _ in data_item_dict.items():
        if key in request_data:
            data_item_dict[key] = request_data[key]
# Buggy code
def on_commit_control_clicked(self, index):
    infohash = index.model().data_items[index.row()]["infohash"]
    status = index.model().data_items[index.row()]["status"]

    new_status = COMMIT_STATUS_COMMITTED
    if status == COMMIT_STATUS_NEW or status == COMMIT_STATUS_COMMITTED:
        new_status = COMMIT_STATUS_TODELETE

    request_mgr = TriblerRequestManager()
    request_mgr.perform_request(
        "mychannel/torrents/%s" % infohash,
        lambda response: self.on_torrent_status_updated(response, index),
        data={"status": new_status},
        method="PATCH",
    )


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

# Fixed code
def on_commit_control_clicked(self, index):
    data_item = index.model().data_items[index.row()]
    infohash = data_item["infohash"]
    status = data_item["status"]

    new_status = COMMIT_STATUS_COMMITTED
    if status == COMMIT_STATUS_NEW or status == COMMIT_STATUS_COMMITTED:
        new_status = COMMIT_STATUS_TODELETE

    def on_torrent_status_updated(json_result):
        if not json_result:
            return

        if "success" in json_result and json_result["success"]:
            data_item["status"] = json_result["new_status"]
            self.window().edit_channel_page.channel_dirty = (
                self.table_view.window().edit_channel_page.channel_dirty
                or (json_result["new_status"] != COMMIT_STATUS_COMMITTED)
            )
            self.window().edit_channel_page.update_channel_commit_views(
                reload_view=True
            )

    request_mgr = TriblerRequestManager()
    request_mgr.perform_request(
        "mychannel/torrents/%s" % infohash,
        on_torrent_status_updated,
        data={"status": new_status},
        method="PATCH",
    )
# Buggy code
def on_torrent_status_updated(self, json_result, index):
    if not json_result:
        return

    if "success" in json_result and json_result["success"]:
        index.model().data_items[index.row()]["status"] = json_result["new_status"]

        self.window().edit_channel_page.channel_dirty = (
            self.table_view.window().edit_channel_page.channel_dirty
            or (json_result["new_status"] != COMMIT_STATUS_COMMITTED)
        )
        self.window().edit_channel_page.update_channel_commit_views(deleted_index=index)


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

# Fixed code
def on_torrent_status_updated(json_result):
    if not json_result:
        return

    if "success" in json_result and json_result["success"]:
        data_item["status"] = json_result["new_status"]
        self.window().edit_channel_page.channel_dirty = (
            self.table_view.window().edit_channel_page.channel_dirty
            or (json_result["new_status"] != COMMIT_STATUS_COMMITTED)
        )
        self.window().edit_channel_page.update_channel_commit_views(reload_view=True)
# Buggy code
def connect_to_tracker(self):
    """
    Fakely connects to a tracker.
    :return: A deferred that fires with the health information.
    """

    def on_metainfo(metainfo):
        if not metainfo:
            self.result_deferred.errback(Failure(RuntimeError("Metainfo lookup error")))
            return

        self.result_deferred.callback(
            {
                "DHT": [
                    {
                        "infohash": hexlify(self.infohash),
                        "seeders": metainfo["seeders"],
                        "leechers": metainfo["leechers"],
                    }
                ]
            }
        )

    self._session.lm.ltmgr.get_metainfo(
        self.infohash, timeout=self.timeout
    ).addCallback(on_metainfo)
    return self.result_deferred


# Traceback (builtins.KeyError)
Traceback (most recent call last):
File "/home/tribler/tudelft/tribler/Tribler/Core/Libtorrent/LibtorrentMgr.py", line 574, in _task_process_alerts
self.check_metainfo(str(alert.handle.info_hash()))
File "/home/tribler/tudelft/tribler/Tribler/Core/Libtorrent/LibtorrentMgr.py", line 541, in check_metainfo
metainfo_deferred.callback(metainfo)
File "/home/tribler/.local/lib/python3.6/site-packages/twisted/internet/defer.py", line 460, in callback
self._startRunCallbacks(result)
File "/home/tribler/.local/lib/python3.6/site-packages/twisted/internet/defer.py", line 568, in _startRunCallbacks
self._runCallbacks()
--- <exception caught here> ---
File "/home/tribler/.local/lib/python3.6/site-packages/twisted/internet/defer.py", line 654, in _runCallbacks
current.result = callback(current.result, *args, **kw)
File "/home/tribler/tudelft/tribler/Tribler/Core/TorrentChecker/session.py", line 645, in on_metainfo
"seeders": metainfo["seeders"],
builtins.KeyError: 'seeders'

# Fixed code
def connect_to_tracker(self):
    """
    Fakely connects to a tracker.
    :return: A deferred that fires with the health information.
    """

    def on_metainfo(metainfo):
        if not metainfo:
            self.result_deferred.errback(Failure(RuntimeError("Metainfo lookup error")))
            return

        self.result_deferred.callback(
            {
                "DHT": [
                    {
                        "infohash": hexlify(self.infohash),
                        "seeders": metainfo[b"seeders"],
                        "leechers": metainfo[b"leechers"],
                    }
                ]
            }
        )

    self._session.lm.ltmgr.get_metainfo(
        self.infohash, timeout=self.timeout
    ).addCallback(on_metainfo)
    return self.result_deferred
# Buggy code
def on_metainfo(metainfo):
    if not metainfo:
        self.result_deferred.errback(Failure(RuntimeError("Metainfo lookup error")))
        return

    self.result_deferred.callback(
        {
            "DHT": [
                {
                    "infohash": hexlify(self.infohash),
                    "seeders": metainfo["seeders"],
                    "leechers": metainfo["leechers"],
                }
            ]
        }
    )


# Traceback (builtins.KeyError)
Traceback (most recent call last):
File "/home/tribler/tudelft/tribler/Tribler/Core/Libtorrent/LibtorrentMgr.py", line 574, in _task_process_alerts
self.check_metainfo(str(alert.handle.info_hash()))
File "/home/tribler/tudelft/tribler/Tribler/Core/Libtorrent/LibtorrentMgr.py", line 541, in check_metainfo
metainfo_deferred.callback(metainfo)
File "/home/tribler/.local/lib/python3.6/site-packages/twisted/internet/defer.py", line 460, in callback
self._startRunCallbacks(result)
File "/home/tribler/.local/lib/python3.6/site-packages/twisted/internet/defer.py", line 568, in _startRunCallbacks
self._runCallbacks()
--- <exception caught here> ---
File "/home/tribler/.local/lib/python3.6/site-packages/twisted/internet/defer.py", line 654, in _runCallbacks
current.result = callback(current.result, *args, **kw)
File "/home/tribler/tudelft/tribler/Tribler/Core/TorrentChecker/session.py", line 645, in on_metainfo
"seeders": metainfo["seeders"],
builtins.KeyError: 'seeders'

# Fixed code
def on_metainfo(metainfo):
    if not metainfo:
        self.result_deferred.errback(Failure(RuntimeError("Metainfo lookup error")))
        return

    self.result_deferred.callback(
        {
            "DHT": [
                {
                    "infohash": hexlify(self.infohash),
                    "seeders": metainfo[b"seeders"],
                    "leechers": metainfo[b"leechers"],
                }
            ]
        }
    )
# Buggy code
def copy_metainfo_to_torrent_parameters(self):
    """
    Populate the torrent_parameters dictionary with information from the metainfo.
    """
    for key in [
        "comment",
        "created by",
        "creation date",
        "announce",
        "announce-list",
        "nodes",
        "httpseeds",
        "urllist",
    ]:
        if key in self.metainfo:
            self.torrent_parameters[key] = self.metainfo[key]

    infokeys = ["name", "piece length"]
    for key in infokeys:
        if key in self.metainfo[b"info"]:
            self.torrent_parameters[key] = self.metainfo[b"info"][key]


# 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'>: 'NoneType' object has no attribute '__getitem__'
threading.py:810:__bootstrap_inner
threading.py:763:run
twisted/_threads/_threadworker.py:46:work
twisted/_threads/_team.py:190:doWork
--- <exception caught here> ---
twisted/python/threadpool.py:246:inContext
twisted/python/threadpool.py:262:<lambda>
twisted/python/context.py:118:callWithContext
twisted/python/context.py:81:callWithContext
Tribler/Core/APIImplementation/LaunchManyCore.py:525:sesscb_states_callback
Tribler/Core/TorrentDef.py:277:get_name_as_unicode
]

# Fixed code
def copy_metainfo_to_torrent_parameters(self):
    """
    Populate the torrent_parameters dictionary with information from the metainfo.
    """
    for key in [
        "comment",
        "created by",
        "creation date",
        "announce",
        "announce-list",
        "nodes",
        "httpseeds",
        "urllist",
    ]:
        if self.metainfo and key in self.metainfo:
            self.torrent_parameters[key] = self.metainfo[key]

    infokeys = ["name", "piece length"]
    for key in infokeys:
        if self.metainfo and key in self.metainfo[b"info"]:
            self.torrent_parameters[key] = self.metainfo[b"info"][key]
# Buggy code
def get_length(self, selectedfiles=None):
    """Returns the total size of the content in the torrent. If the
    optional selectedfiles argument is specified, the method returns
    the total size of only those files.
    @return A length (long)
    """
    return maketorrent.get_length_from_metainfo(self.metainfo, selectedfiles)


# 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'>: 'NoneType' object has no attribute '__getitem__'
threading.py:810:__bootstrap_inner
threading.py:763:run
twisted/_threads/_threadworker.py:46:work
twisted/_threads/_team.py:190:doWork
--- <exception caught here> ---
twisted/python/threadpool.py:246:inContext
twisted/python/threadpool.py:262:<lambda>
twisted/python/context.py:118:callWithContext
twisted/python/context.py:81:callWithContext
Tribler/Core/APIImplementation/LaunchManyCore.py:525:sesscb_states_callback
Tribler/Core/TorrentDef.py:277:get_name_as_unicode
]

# Fixed code
def get_length(self, selectedfiles=None):
    """Returns the total size of the content in the torrent. If the
    optional selectedfiles argument is specified, the method returns
    the total size of only those files.
    @return A length (long)
    """
    if self.metainfo:
        return maketorrent.get_length_from_metainfo(self.metainfo, selectedfiles)
    return 0
# Buggy code
def get_creation_date(self):
    """
    Returns the creation date of the torrent.
    """
    return self.metainfo.get("creation date", 0)


# 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'>: 'NoneType' object has no attribute '__getitem__'
threading.py:810:__bootstrap_inner
threading.py:763:run
twisted/_threads/_threadworker.py:46:work
twisted/_threads/_team.py:190:doWork
--- <exception caught here> ---
twisted/python/threadpool.py:246:inContext
twisted/python/threadpool.py:262:<lambda>
twisted/python/context.py:118:callWithContext
twisted/python/context.py:81:callWithContext
Tribler/Core/APIImplementation/LaunchManyCore.py:525:sesscb_states_callback
Tribler/Core/TorrentDef.py:277:get_name_as_unicode
]

# Fixed code
def get_creation_date(self):
    """
    Returns the creation date of the torrent.
    """
    return self.metainfo.get("creation date", 0) if self.metainfo else 0
# Buggy code
def is_private(self):
    """
    Returns whether this TorrentDef is a private torrent (and is not announced in the DHT).
    """
    return int(self.metainfo[b"info"].get(b"private", 0)) == 1


# 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'>: 'NoneType' object has no attribute '__getitem__'
threading.py:810:__bootstrap_inner
threading.py:763:run
twisted/_threads/_threadworker.py:46:work
twisted/_threads/_team.py:190:doWork
--- <exception caught here> ---
twisted/python/threadpool.py:246:inContext
twisted/python/threadpool.py:262:<lambda>
twisted/python/context.py:118:callWithContext
twisted/python/context.py:81:callWithContext
Tribler/Core/APIImplementation/LaunchManyCore.py:525:sesscb_states_callback
Tribler/Core/TorrentDef.py:277:get_name_as_unicode
]

# Fixed code
def is_private(self):
    """
    Returns whether this TorrentDef is a private torrent (and is not announced in the DHT).
    """
    return (
        (int(self.metainfo[b"info"].get(b"private", 0)) == 1)
        if self.metainfo
        else False
    )
# Buggy code
def get_index_of_file_in_files(self, file):
    info = self.metainfo[b"info"]

    if file is not None and "files" in info:
        for i in range(len(info["files"])):
            file_dict = info["files"][i]

            if "path.utf-8" in file_dict:
                intorrentpath = maketorrent.pathlist2filename(file_dict["path.utf-8"])
            else:
                intorrentpath = maketorrent.pathlist2filename(file_dict["path"])

            if intorrentpath == file:
                return i
        raise ValueError("File not found in torrent")
    else:
        raise ValueError("File not found in single-file torrent")


# 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'>: 'NoneType' object has no attribute '__getitem__'
threading.py:810:__bootstrap_inner
threading.py:763:run
twisted/_threads/_threadworker.py:46:work
twisted/_threads/_team.py:190:doWork
--- <exception caught here> ---
twisted/python/threadpool.py:246:inContext
twisted/python/threadpool.py:262:<lambda>
twisted/python/context.py:118:callWithContext
twisted/python/context.py:81:callWithContext
Tribler/Core/APIImplementation/LaunchManyCore.py:525:sesscb_states_callback
Tribler/Core/TorrentDef.py:277:get_name_as_unicode
]

# Fixed code
def get_index_of_file_in_files(self, file):
    if not self.metainfo:
        raise ValueError("TorrentDef does not have metainfo")
    info = self.metainfo[b"info"]

    if file is not None and "files" in info:
        for i in range(len(info["files"])):
            file_dict = info["files"][i]

            if "path.utf-8" in file_dict:
                intorrentpath = maketorrent.pathlist2filename(file_dict["path.utf-8"])
            else:
                intorrentpath = maketorrent.pathlist2filename(file_dict["path"])

            if intorrentpath == file:
                return i
        raise ValueError("File not found in torrent")
    else:
        raise ValueError("File not found in single-file torrent")
# Buggy code
def on_received_downloads(self, downloads):
    if not downloads:
        return  # This might happen when closing Tribler

    bytes_max = self.window().tribler_settings["credit_mining"]["max_disk_space"]
    bytes_used = 0
    total_up = total_down = 0
    for download in downloads["downloads"]:
        if download["credit_mining"] and download["status"] in (
            "DLSTATUS_DOWNLOADING",
            "DLSTATUS_SEEDING",
            "DLSTATUS_STOPPED",
            "DLSTATUS_STOPPED_ON_ERROR",
        ):
            bytes_used += download["progress"] * download["size"]
            total_up += download["total_up"]
            total_down += download["total_down"]

    self.window().token_mining_upload_amount_label.setText(format_size(total_up))
    self.window().token_mining_download_amount_label.setText(format_size(total_down))
    self.window().token_mining_disk_usage_label.setText(
        "%s / %s" % (format_size(float(bytes_used)), format_size(float(bytes_max)))
    )

    self.push_data_to_plot(total_up, total_down)
    self.trust_plot.plot_data = self.plot_data
    self.trust_plot.compute_initial_figure()

    self.schedule_downloads_timer()

    # Matplotlib is leaking memory on re-plotting. Refer: https://github.com/matplotlib/matplotlib/issues/8528
    # Note that gc is called every 10 minutes.
    if self.gc_timer == GC_TIMEOUT:
        gc.collect()
        self.gc_timer = 0
    else:
        self.gc_timer += 1


# Traceback (TypeError)
Traceback (most recent call last):
File "TriblerGUI\widgets\triblertablecontrollers.py", line 114, in on_total_count_results
TypeError: argument of type 'NoneType' is not iterable

# Fixed code
def on_received_downloads(self, downloads):
    if not downloads or "downloads" not in downloads:
        return  # This might happen when closing Tribler

    bytes_max = self.window().tribler_settings["credit_mining"]["max_disk_space"]
    bytes_used = 0
    total_up = total_down = 0
    for download in downloads["downloads"]:
        if download["credit_mining"] and download["status"] in (
            "DLSTATUS_DOWNLOADING",
            "DLSTATUS_SEEDING",
            "DLSTATUS_STOPPED",
            "DLSTATUS_STOPPED_ON_ERROR",
        ):
            bytes_used += download["progress"] * download["size"]
            total_up += download["total_up"]
            total_down += download["total_down"]

    self.window().token_mining_upload_amount_label.setText(format_size(total_up))
    self.window().token_mining_download_amount_label.setText(format_size(total_down))
    self.window().token_mining_disk_usage_label.setText(
        "%s / %s" % (format_size(float(bytes_used)), format_size(float(bytes_max)))
    )

    self.push_data_to_plot(total_up, total_down)
    self.trust_plot.plot_data = self.plot_data
    self.trust_plot.compute_initial_figure()

    self.schedule_downloads_timer()

    # Matplotlib is leaking memory on re-plotting. Refer: https://github.com/matplotlib/matplotlib/issues/8528
    # Note that gc is called every 10 minutes.
    if self.gc_timer == GC_TIMEOUT:
        gc.collect()
        self.gc_timer = 0
    else:
        self.gc_timer += 1
# Buggy code
def on_total_count_results(self, response):
    # Workaround for possible race condition between simultaneous requests. Sees query_total_count for details.
    if "total" in response:
        self.count_query_complete.emit(response)
        self.model.total_items = response["total"]
        # TODO unify this label update with the above count_query_complete signal
        if self.num_results_label:
            self.num_results_label.setText("%d results" % self.model.total_items)
        return False


# Traceback (TypeError)
Traceback (most recent call last):
File "TriblerGUI\widgets\triblertablecontrollers.py", line 114, in on_total_count_results
TypeError: argument of type 'NoneType' is not iterable

# Fixed code
def on_total_count_results(self, response):
    # Workaround for possible race condition between simultaneous requests. Sees query_total_count for details.
    if response and "total" in response:
        self.count_query_complete.emit(response)
        self.model.total_items = response["total"]
        # TODO unify this label update with the above count_query_complete signal
        if self.num_results_label:
            self.num_results_label.setText("%d results" % self.model.total_items)
        return False
# Buggy code
def get_files_completion(self):
    """Returns a list of filename, progress tuples indicating the progress
    for every file selected using set_selected_files. Progress is a float
    between 0 and 1
    """
    completion = []

    if self.lt_status:
        files = self.download.get_def().get_files_with_length()
        progress = self.download.handle.file_progress(flags=1)
        for index, (path, size) in enumerate(files):
            completion_frac = (float(progress[index]) / size) if size > 0 else 1
            completion.append((path, completion_frac))

    return completion


# Traceback (AttributeError)
ERROR   1563835718.80                  __init__:1198 (RESTRequest)  [Failure instance: Traceback: <type 'exceptions.AttributeError'>: 'NoneType' object has no attribute 'file_progress'
lib\site-packages\twisted\web\http.py:1752:lineReceived
lib\site-packages\twisted\web\http.py:1845:allContentReceived
lib\site-packages\twisted\web\http.py:766:requestReceived
Tribler\Core\Modules\restapi\rest_manager.py:118:process
--- <exception caught here> ---
lib\site-packages\twisted\web\server.py:190:process
lib\site-packages\twisted\web\server.py:241:render
lib\site-packages\twisted\web\resource.py:250:render
Tribler\Core\Modules\restapi\downloads_endpoint.py:292:render_GET
Tribler\Core\Modules\restapi\downloads_endpoint.py:112:get_files_info_json
Tribler\Core\DownloadState.py:167:get_files_completion
]
Traceback (most recent call last):
File "lib\site-packages\twisted\web\server.py", line 190, in process
File "lib\site-packages\twisted\web\server.py", line 241, in render
File "lib\site-packages\twisted\web\resource.py", line 250, in render
File "Tribler\Core\Modules\restapi\downloads_endpoint.py", line 292, in render_GET
File "Tribler\Core\Modules\restapi\downloads_endpoint.py", line 112, in get_files_info_json
File "Tribler\Core\DownloadState.py", line 167, in get_files_completion
AttributeError: 'NoneType' object has no attribute 'file_progress'

# Fixed code
def get_files_completion(self):
    """Returns a list of filename, progress tuples indicating the progress
    for every file selected using set_selected_files. Progress is a float
    between 0 and 1
    """
    completion = []

    if self.lt_status and self.download.handle:
        files = self.download.get_def().get_files_with_length()
        progress = self.download.handle.file_progress(flags=1)
        for index, (path, size) in enumerate(files):
            completion_frac = (float(progress[index]) / size) if size > 0 else 1
            completion.append((path, completion_frac))

    return completion
# Buggy code
def to_simple_dict(self, include_trackers=False):
    """
    Return a basic dictionary with information about the channel.
    """
    epoch = datetime.utcfromtimestamp(0)
    simple_dict = {
        "id": self.id_,
        "public_key": hexlify(self.public_key),
        "name": self.title,
        "infohash": hexlify(self.infohash),
        "size": self.size,
        "category": self.tags,
        "num_seeders": self.health.seeders,
        "num_leechers": self.health.leechers,
        "last_tracker_check": self.health.last_check,
        "updated": int((self.torrent_date - epoch).total_seconds()),
        "status": self.status,
        "type": {REGULAR_TORRENT: "torrent", CHANNEL_TORRENT: "channel"}[
            self.metadata_type
        ],
    }

    if include_trackers:
        simple_dict["trackers"] = [tracker.url for tracker in self.health.trackers]

    return simple_dict


# Traceback (TypeError)
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/twisted/web/server.py", line 194, in process
resrc = self.site.getResourceFor(self)
File "/usr/lib/python2.7/dist-packages/twisted/web/server.py", line 853, in getResourceFor
return resource.getChildForRequest(self.resource, request)
File "/usr/lib/python2.7/dist-packages/twisted/web/resource.py", line 98, in getChildForRequest
resource = resource.getChildWithDefault(pathElement, request)
File "/usr/lib/python2.7/dist-packages/twisted/web/resource.py", line 201, in getChildWithDefault
return self.getChild(path, request)
File "/home/tribler/tribler/Tribler/Core/Modules/restapi/metadata_endpoint.py", line 110, in getChild
return ChannelPublicKeyEndpoint(self.session, path)
File "/home/tribler/tribler/Tribler/Core/Modules/restapi/metadata_endpoint.py", line 159, in __init__
self.channel_pk = unhexlify(path)
TypeError: Odd-length string

# Fixed code
def to_simple_dict(self, include_trackers=False):
    """
    Return a basic dictionary with information about the channel.
    """
    epoch = datetime.utcfromtimestamp(0)
    simple_dict = {
        "id": self.id_,
        "public_key": hexlify(self.public_key or NULL_KEY_SUBST),
        "name": self.title,
        "infohash": hexlify(self.infohash),
        "size": self.size,
        "category": self.tags,
        "num_seeders": self.health.seeders,
        "num_leechers": self.health.leechers,
        "last_tracker_check": self.health.last_check,
        "updated": int((self.torrent_date - epoch).total_seconds()),
        "status": self.status,
        "type": {REGULAR_TORRENT: "torrent", CHANNEL_TORRENT: "channel"}[
            self.metadata_type
        ],
    }

    if include_trackers:
        simple_dict["trackers"] = [tracker.url for tracker in self.health.trackers]

    return simple_dict
# Buggy code
def perform_query(self, **kwargs):
    if "rest_endpoint_url" not in kwargs:
        kwargs.update(
            {
                "rest_endpoint_url": "metadata/channels/%s/%i/torrents"
                % (self.model.channel_pk, self.model.channel_id)
            }
        )
    super(TorrentsTableViewController, self).perform_query(**kwargs)


# Traceback (TypeError)
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/twisted/web/server.py", line 194, in process
resrc = self.site.getResourceFor(self)
File "/usr/lib/python2.7/dist-packages/twisted/web/server.py", line 853, in getResourceFor
return resource.getChildForRequest(self.resource, request)
File "/usr/lib/python2.7/dist-packages/twisted/web/resource.py", line 98, in getChildForRequest
resource = resource.getChildWithDefault(pathElement, request)
File "/usr/lib/python2.7/dist-packages/twisted/web/resource.py", line 201, in getChildWithDefault
return self.getChild(path, request)
File "/home/tribler/tribler/Tribler/Core/Modules/restapi/metadata_endpoint.py", line 110, in getChild
return ChannelPublicKeyEndpoint(self.session, path)
File "/home/tribler/tribler/Tribler/Core/Modules/restapi/metadata_endpoint.py", line 159, in __init__
self.channel_pk = unhexlify(path)
TypeError: Odd-length string

# Fixed code
def perform_query(self, **kwargs):
    # On some systems, URLs containing double slashes are handled incorrectly.
    # To circumvent this limitation, for empty public key we use a special substitute
    if "rest_endpoint_url" not in kwargs:
        kwargs.update(
            {
                "rest_endpoint_url": "metadata/channels/%s/%i/torrents"
                % (self.model.channel_pk, self.model.channel_id)
            }
        )
    super(TorrentsTableViewController, self).perform_query(**kwargs)
# 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.downloads_last_update = 0
    self.selected_items = None
    self.dialog = None
    self.downloads_request_mgr = TriblerRequestManager()
    self.request_mgr = None
    self.loading_message_widget = None


# Traceback (AttributeError)
Traceback (most recent call last):
File "TriblerGUI\dialogs\startdownloaddialog.py", line 141, in on_received_metainfo
AttributeError: 'NoneType' object has no attribute 'dialog_widget'

# 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_items = []
    self.dialog = None
    self.downloads_request_mgr = TriblerRequestManager()
    self.request_mgr = None
    self.loading_message_widget = None
# Buggy code
def on_channel_subscribed(self, json_result):
    if not json_result:
        return
    if json_result["subscribed"]:
        self.subscribed_channel.emit(self.channel_info)
        self.channel_info["subscribed"] = True
        self.channel_info["votes"] += 1
        self.update_subscribe_button()


# Traceback (AttributeError)
Traceback (most recent call last):
File "TriblerGUI\dialogs\startdownloaddialog.py", line 141, in on_received_metainfo
AttributeError: 'NoneType' object has no attribute 'dialog_widget'

# Fixed code
def on_channel_subscribed(self, json_result):
    if not json_result or not self:
        return
    if json_result["subscribed"]:
        self.subscribed_channel.emit(self.channel_info)
        self.channel_info["subscribed"] = True
        self.channel_info["votes"] += 1
        self.update_subscribe_button()
# Buggy code
def copy(self):
    return DownloadConfigInterface(self.dlconfig.copy())


# Traceback (AttributeError)
ERROR   1561381744.26        downloads_endpoint:499  (DownloadSpecificEndpoint)  [Failure instance: Traceback: <type 'exceptions.AttributeError'>: 'NoneType' object has no attribute 'endswith'
/home/quinten/.local/lib/python2.7/site-packages/twisted/internet/defer.py:460:callback
/home/quinten/.local/lib/python2.7/site-packages/twisted/internet/defer.py:568:_startRunCallbacks
/home/quinten/.local/lib/python2.7/site-packages/twisted/internet/defer.py:654:_runCallbacks
/home/quinten/.local/lib/python2.7/site-packages/twisted/internet/defer.py:1475:gotResult
--- <exception caught here> ---
/home/quinten/.local/lib/python2.7/site-packages/twisted/internet/defer.py:1418:_inlineCallbacks
/home/quinten/Documents/tribler/Tribler/Core/APIImplementation/LaunchManyCore.py:435:update_download_hops
/home/quinten/Documents/tribler/Tribler/Core/Session.py:242:start_download_from_tdef
/home/quinten/Documents/tribler/Tribler/Core/APIImplementation/LaunchManyCore.py:354:add
/home/quinten/Documents/tribler/Tribler/Core/DownloadConfig.py:81:get_dest_dir
/usr/lib/python2.7/posixpath.py:70:join
]
Traceback (most recent call last):
File "/home/quinten/.local/lib/python2.7/site-packages/twisted/internet/defer.py", line 1418, in _inlineCallbacks
result = g.send(result)
File "/home/quinten/Documents/tribler/Tribler/Core/APIImplementation/LaunchManyCore.py", line 435, in update_download_hops
self.session.start_download_from_tdef(download.tdef, dscfg, pstate=pstate)
File "/home/quinten/Documents/tribler/Tribler/Core/Session.py", line 242, in start_download_from_tdef
return self.lm.add(torrent_definition, download_startup_config, pstate=pstate, hidden=hidden)
File "/home/quinten/Documents/tribler/Tribler/Core/APIImplementation/LaunchManyCore.py", line 354, in add
if not os.path.isdir(dscfg.get_dest_dir()):
File "/home/quinten/Documents/tribler/Tribler/Core/DownloadConfig.py", line 81, in get_dest_dir
dest_dir = os.path.join(self.state_dir, dest_dir)
File "/usr/lib/python2.7/posixpath.py", line 70, in join
elif path == '' or path.endswith('/'):
AttributeError: 'NoneType' object has no attribute 'endswith'

# Fixed code
def copy(self):
    return DownloadConfigInterface(
        dlconfig=self.dlconfig.copy(), state_dir=self.state_dir
    )
# Buggy code
def get_updated_channels(cls):
    return select(g for g in cls if g.subscribed and (g.local_version < g.timestamp))


# 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 get_updated_channels(cls):
    return select(
        g
        for g in cls
        if g.subscribed
        and (g.local_version < g.timestamp)
        and g.public_key != database_blob(cls._my_key.pub().key_to_bin()[10:])
    )
# Buggy code
def __init__(self, session):
    super(GigaChannelManager, self).__init__()
    self.session = session
    self.channels_lc = None


# 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 __init__(self, session):
    super(GigaChannelManager, self).__init__()
    self.session = session
    self.channels_lc = None

    # We queue up processing of the channels because we do it in a separate thread, and we don't want
    # to run more that one of these simultaneously
    self.channels_processing_queue = []
    self.processing = False