gurudesh/pytracebugs huggingface dataset:
# Buggy code
def compare(self, iter_a: Gtk.TreeIter, iter_b: Gtk.TreeIter) -> bool:
    if iter_a is not None and iter_b is not None:
        model = self.get_model()
        assert model is not None
        return model.get_path(iter_a) == model.get_path(iter_b)
    else:
        return False


# Traceback (AssertionError)
Traceback (most recent call last):
File "/home/cschramm/src/blueman/blueman/gui/manager/ManagerMenu.py", line 249, in on_adapter_selected
self.blueman.List.set_adapter(adapter_path)
File "/home/cschramm/src/blueman/blueman/gui/DeviceList.py", line 245, in set_adapter
self.clear()
File "/home/cschramm/src/blueman/blueman/gui/DeviceList.py", line 354, in clear
self.device_remove_event(device)
File "/home/cschramm/src/blueman/blueman/gui/manager/ManagerDeviceList.py", line 233, in device_remove_event
super().device_remove_event(device)
File "/home/cschramm/src/blueman/blueman/gui/DeviceList.py", line 237, in device_remove_event
if self.compare(self.selected(), tree_iter):
File "/home/cschramm/src/blueman/blueman/gui/GenericList.py", line 64, in selected
assert tree_iter is not None
AssertionError

# Fixed code
def compare(
    self, iter_a: Optional[Gtk.TreeIter], iter_b: Optional[Gtk.TreeIter]
) -> bool:
    if iter_a is not None and iter_b is not None:
        model = self.get_model()
        assert model is not None
        return model.get_path(iter_a) == model.get_path(iter_b)
    else:
        return False
# Buggy code
def _on_popup_menu(self, _widget: Gtk.Widget) -> bool:
    if self.Blueman is None:
        return False

    if self.menu is None:
        self.menu = ManagerDeviceMenu(self.Blueman)

    window = self.get_window()
    assert window is not None
    rect = self.get_cell_area(
        self.liststore.get_path(self.selected()), self.get_column(1)
    )
    self.menu.popup_at_rect(window, rect, Gdk.Gravity.CENTER, Gdk.Gravity.NORTH)

    return True


# Traceback (AssertionError)
Traceback (most recent call last):
File "/home/cschramm/src/blueman/blueman/gui/manager/ManagerMenu.py", line 249, in on_adapter_selected
self.blueman.List.set_adapter(adapter_path)
File "/home/cschramm/src/blueman/blueman/gui/DeviceList.py", line 245, in set_adapter
self.clear()
File "/home/cschramm/src/blueman/blueman/gui/DeviceList.py", line 354, in clear
self.device_remove_event(device)
File "/home/cschramm/src/blueman/blueman/gui/manager/ManagerDeviceList.py", line 233, in device_remove_event
super().device_remove_event(device)
File "/home/cschramm/src/blueman/blueman/gui/DeviceList.py", line 237, in device_remove_event
if self.compare(self.selected(), tree_iter):
File "/home/cschramm/src/blueman/blueman/gui/GenericList.py", line 64, in selected
assert tree_iter is not None
AssertionError

# Fixed code
def _on_popup_menu(self, _widget: Gtk.Widget) -> bool:
    if self.Blueman is None:
        return False

    if self.menu is None:
        self.menu = ManagerDeviceMenu(self.Blueman)

    window = self.get_window()
    assert window is not None
    selected = self.selected()
    assert selected is not None
    rect = self.get_cell_area(self.liststore.get_path(selected), self.get_column(1))
    self.menu.popup_at_rect(window, rect, Gdk.Gravity.CENTER, Gdk.Gravity.NORTH)

    return True
# Buggy code
def on_selection_changed(self, _selection: Gtk.TreeSelection) -> None:
    tree_iter = self.List.selected()
    if self.List.get_cursor()[0]:
        # GtkTreePath returns row when used as string
        self.Config["services-last-item"] = int(str(self.List.get_cursor()[0]))
    row = self.List.get(tree_iter, "id")
    rowid = row["id"]

    self.set_page(rowid)


# Traceback (AssertionError)
Traceback (most recent call last):
File "/home/cschramm/src/blueman/blueman/gui/manager/ManagerMenu.py", line 249, in on_adapter_selected
self.blueman.List.set_adapter(adapter_path)
File "/home/cschramm/src/blueman/blueman/gui/DeviceList.py", line 245, in set_adapter
self.clear()
File "/home/cschramm/src/blueman/blueman/gui/DeviceList.py", line 354, in clear
self.device_remove_event(device)
File "/home/cschramm/src/blueman/blueman/gui/manager/ManagerDeviceList.py", line 233, in device_remove_event
super().device_remove_event(device)
File "/home/cschramm/src/blueman/blueman/gui/DeviceList.py", line 237, in device_remove_event
if self.compare(self.selected(), tree_iter):
File "/home/cschramm/src/blueman/blueman/gui/GenericList.py", line 64, in selected
assert tree_iter is not None
AssertionError

# Fixed code
def on_selection_changed(self, _selection: Gtk.TreeSelection) -> None:
    tree_iter = self.List.selected()
    assert tree_iter
    if self.List.get_cursor()[0]:
        # GtkTreePath returns row when used as string
        self.Config["services-last-item"] = int(str(self.List.get_cursor()[0]))
    row = self.List.get(tree_iter, "id")
    rowid = row["id"]

    self.set_page(rowid)
# Buggy code
def passkey_dialog_cb(dialog, response_id):
    if response_id == Gtk.ResponseType.ACCEPT:
        ret = pin_entry.get_text()
        if is_numeric:
            ret = GLib.Variant("(u)", int(ret))
        ok(ret)
    else:
        err(BluezErrorRejected("Rejected"))
    dialog.destroy()
    self.dialog = None


# Traceback (TypeError)
(blueman-tray:79548): Gdk-CRITICAL **: 16:36:17.940: gdk_window_thaw_toplevel_updates: assertion 'window->update_and_descendants_freeze_count > 0' failed
blueman-manager version 2.1.1 starting
Stale PID, overwriting
blueman-manager 16.36.23 WARNING  DeviceList:193 monitor_power_levels: Failed to get power levels, probably a LE device.
blueman-manager 16.36.33 WARNING  DeviceList:193 monitor_power_levels: Failed to get power levels, probably a LE device.
/usr/lib/python3.8/site-packages/gi/overrides/Gtk.py:1630: Warning: g_value_get_int: assertion 'G_VALUE_HOLDS_INT (value)' failed
return _Gtk_main(*args, **kwargs)
Traceback (most recent call last):
File "/usr/lib/python3.8/site-packages/gi/overrides/GLib.py", line 130, in _create
iter(value)
TypeError: 'int' object is not iterable

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/usr/lib/python3.8/site-packages/blueman/main/applet/BluezAgent.py", line 172, in passkey_dialog_cb
ret = GLib.Variant('(u)', int(ret))
File "/usr/lib/python3.8/site-packages/gi/overrides/GLib.py", line 189, in __new__
v = creator._create(format_string, value)
File "/usr/lib/python3.8/site-packages/gi/overrides/GLib.py", line 132, in _create
raise TypeError("Could not create array, tuple or dictionary entry from non iterable value %s %s" %
TypeError: Could not create array, tuple or dictionary entry from non iterable value (u) 401704
blueman-manager 16.37.04 ERROR    Manager:201 error_handler:  Authentication Canceled
Traceback (most recent call last):
File "/usr/lib/python3.8/site-packages/blueman/bluez/Base.py", line 81, in callback
value = proxy.call_finish(result).unpack()
gi.repository.GLib.GError: g-io-error-quark: GDBus.Error:org.bluez.Error.AuthenticationCanceled: Authentication Canceled (36)

# Fixed code
def passkey_dialog_cb(dialog, response_id):
    if response_id == Gtk.ResponseType.ACCEPT:
        ret = pin_entry.get_text()
        ok(int(ret) if is_numeric else ret)
    else:
        err(BluezErrorRejected("Rejected"))
    dialog.destroy()
    self.dialog = None
# Buggy code
def __init__(self, plugin_class, module_path, parent):
    super().__init__()
    self.__plugins: Dict[str, T] = {}
    self.__classes: Dict[str, Type[T]] = {}
    self.__deps: Dict[str, str] = {}
    self.__cfls: Dict[str, str] = {}
    self.__loaded: List[str] = []
    self.parent = parent

    self.module_path = module_path
    self.plugin_class = plugin_class


# Traceback (AttributeError)
$ git clone https://github.com/blueman-project/blueman.git
…
$ cd blueman/
$ ./autogen.sh
…
$ make
…
$ PYTHONPATH=$(pwd) python3.6 ./blueman/main/Applet.py
Traceback (most recent call last):
File "./blueman/main/Applet.py", line 3, in <module>
import blueman.bluez as bluez
File "/home/dakkar/src/blueman/blueman/bluez/__init__.py", line 6, in <module>
import blueman.bluez.errors as errors
AttributeError: module 'blueman' has no attribute 'bluez'

# BUT!
$ git checkout 2.1.1
…
$ PYTHONPATH=$(pwd) python3.6 ./blueman/main/Applet.py
$

# Fixed code
def __init__(self, plugin_class, module_path, parent):
    super().__init__()
    self.__deps: Dict[str, str] = {}
    self.__cfls: Dict[str, str] = {}
    self.__plugins: Dict[str, Union[AppletPlugin, ManagerPlugin]] = {}
    self.__classes: Dict[str, Type[Union[AppletPlugin, ManagerPlugin]]] = {}
    self.__loaded: List[str] = []
    self.parent = parent

    self.module_path = module_path
    self.plugin_class = plugin_class
# Buggy code
def __init__(self, applet):
    self._applet = applet
    self._config = Config("org.blueman.transfer")

    self._agent_path = "/org/blueman/obex_agent"

    self._agent = obex.Agent(self._agent_path)
    self._agent.connect("release", self._on_release)
    self._agent.connect("authorize", self._on_authorize)
    self._agent.connect("cancel", self._on_cancel)

    self._allowed_devices = []
    self._notification = None
    self._pending_transfer = None
    self.transfers = {}

    obex.AgentManager().register_agent(self._agent_path)


# Traceback (KeyError)
_________
Unload (/usr/lib64/python3.4/site-packages/blueman/main/PluginManager.py:183)
Unloading TransferService
_________
__load_plugin (/usr/lib64/python3.4/site-packages/blueman/main/PluginManager.py:133)
loading <class 'blueman.plugins.applet.TransferService.TransferService'>
_________
_on_obex_owner_changed (/usr/lib64/python3.4/site-packages/blueman/plugins/applet/TransferService.py:164)
obex owner changed: :1.40
Traceback (most recent call last):
File "/usr/lib64/python3.4/site-packages/dbus/connection.py", line 604, in msg_reply_handler
reply_handler(*message.get_args_list(**get_args_opts))
File "/usr/lib64/python3.4/site-packages/blueman/plugins/applet/TransferService.py", line 169, in _on_obex_owner_changed
self._agent = _Agent(self._applet)
File "/usr/lib64/python3.4/site-packages/blueman/plugins/applet/TransferService.py", line 29, in __init__
self._agent = obex.Agent(self._agent_path)
File "/usr/lib64/python3.4/site-packages/blueman/bluez/obex/Agent.py", line 31, in __init__
dbus.service.Object.__init__(self, dbus.SessionBus(), agent_path)
File "/usr/lib64/python3.4/site-packages/dbus/service.py", line 485, in __init__
self.add_to_connection(conn, object_path)
File "/usr/lib64/python3.4/site-packages/dbus/service.py", line 576, in add_to_connection
self._fallback)
KeyError: "Can't register the object-path handler for '/org/blueman/obex_agent': there is already a handler"

# Fixed code
def __init__(self, applet):
    self._applet = applet
    self._config = Config("org.blueman.transfer")

    self._agent_path = "/org/blueman/obex_agent"

    self._agent = obex.Agent(self._agent_path)
    self._agent.connect("release", self._on_release)
    self._agent.connect("authorize", self._on_authorize)
    self._agent.connect("cancel", self._on_cancel)

    self._allowed_devices = []
    self._notification = None
    self._pending_transfer = None
    self.transfers = {}
# Buggy code
def on_unload(self):
    if self._watch:
        self._watch.cancel()

    self._agent = None


# Traceback (KeyError)
_________
Unload (/usr/lib64/python3.4/site-packages/blueman/main/PluginManager.py:183)
Unloading TransferService
_________
__load_plugin (/usr/lib64/python3.4/site-packages/blueman/main/PluginManager.py:133)
loading <class 'blueman.plugins.applet.TransferService.TransferService'>
_________
_on_obex_owner_changed (/usr/lib64/python3.4/site-packages/blueman/plugins/applet/TransferService.py:164)
obex owner changed: :1.40
Traceback (most recent call last):
File "/usr/lib64/python3.4/site-packages/dbus/connection.py", line 604, in msg_reply_handler
reply_handler(*message.get_args_list(**get_args_opts))
File "/usr/lib64/python3.4/site-packages/blueman/plugins/applet/TransferService.py", line 169, in _on_obex_owner_changed
self._agent = _Agent(self._applet)
File "/usr/lib64/python3.4/site-packages/blueman/plugins/applet/TransferService.py", line 29, in __init__
self._agent = obex.Agent(self._agent_path)
File "/usr/lib64/python3.4/site-packages/blueman/bluez/obex/Agent.py", line 31, in __init__
dbus.service.Object.__init__(self, dbus.SessionBus(), agent_path)
File "/usr/lib64/python3.4/site-packages/dbus/service.py", line 485, in __init__
self.add_to_connection(conn, object_path)
File "/usr/lib64/python3.4/site-packages/dbus/service.py", line 576, in add_to_connection
self._fallback)
KeyError: "Can't register the object-path handler for '/org/blueman/obex_agent': there is already a handler"

# Fixed code
def on_unload(self):
    if self._watch:
        self._watch.cancel()

    self._unregister_agent()
# Buggy code
def on_manager_state_changed(self, state):
    if not state:
        self._agent = None


# Traceback (KeyError)
_________
Unload (/usr/lib64/python3.4/site-packages/blueman/main/PluginManager.py:183)
Unloading TransferService
_________
__load_plugin (/usr/lib64/python3.4/site-packages/blueman/main/PluginManager.py:133)
loading <class 'blueman.plugins.applet.TransferService.TransferService'>
_________
_on_obex_owner_changed (/usr/lib64/python3.4/site-packages/blueman/plugins/applet/TransferService.py:164)
obex owner changed: :1.40
Traceback (most recent call last):
File "/usr/lib64/python3.4/site-packages/dbus/connection.py", line 604, in msg_reply_handler
reply_handler(*message.get_args_list(**get_args_opts))
File "/usr/lib64/python3.4/site-packages/blueman/plugins/applet/TransferService.py", line 169, in _on_obex_owner_changed
self._agent = _Agent(self._applet)
File "/usr/lib64/python3.4/site-packages/blueman/plugins/applet/TransferService.py", line 29, in __init__
self._agent = obex.Agent(self._agent_path)
File "/usr/lib64/python3.4/site-packages/blueman/bluez/obex/Agent.py", line 31, in __init__
dbus.service.Object.__init__(self, dbus.SessionBus(), agent_path)
File "/usr/lib64/python3.4/site-packages/dbus/service.py", line 485, in __init__
self.add_to_connection(conn, object_path)
File "/usr/lib64/python3.4/site-packages/dbus/service.py", line 576, in add_to_connection
self._fallback)
KeyError: "Can't register the object-path handler for '/org/blueman/obex_agent': there is already a handler"

# Fixed code
def on_manager_state_changed(self, state):
    if not state:
        self._unregister_agent()
# Buggy code
def _on_obex_owner_changed(self, owner):
    dprint("obex owner changed:", owner)
    if owner == "":
        self._agent = None
    else:
        self._agent = _Agent(self._applet)


# Traceback (KeyError)
_________
Unload (/usr/lib64/python3.4/site-packages/blueman/main/PluginManager.py:183)
Unloading TransferService
_________
__load_plugin (/usr/lib64/python3.4/site-packages/blueman/main/PluginManager.py:133)
loading <class 'blueman.plugins.applet.TransferService.TransferService'>
_________
_on_obex_owner_changed (/usr/lib64/python3.4/site-packages/blueman/plugins/applet/TransferService.py:164)
obex owner changed: :1.40
Traceback (most recent call last):
File "/usr/lib64/python3.4/site-packages/dbus/connection.py", line 604, in msg_reply_handler
reply_handler(*message.get_args_list(**get_args_opts))
File "/usr/lib64/python3.4/site-packages/blueman/plugins/applet/TransferService.py", line 169, in _on_obex_owner_changed
self._agent = _Agent(self._applet)
File "/usr/lib64/python3.4/site-packages/blueman/plugins/applet/TransferService.py", line 29, in __init__
self._agent = obex.Agent(self._agent_path)
File "/usr/lib64/python3.4/site-packages/blueman/bluez/obex/Agent.py", line 31, in __init__
dbus.service.Object.__init__(self, dbus.SessionBus(), agent_path)
File "/usr/lib64/python3.4/site-packages/dbus/service.py", line 485, in __init__
self.add_to_connection(conn, object_path)
File "/usr/lib64/python3.4/site-packages/dbus/service.py", line 576, in add_to_connection
self._fallback)
KeyError: "Can't register the object-path handler for '/org/blueman/obex_agent': there is already a handler"

# Fixed code
def _on_obex_owner_changed(self, owner):
    dprint("obex owner changed:", owner)
    if owner == "":
        self._unregister_agent()
    else:
        self._register_agent()
# Buggy code
def wait_for_adapter(bluez_adapter, callback, timeout=1000):
    def on_prop_changed(adapter, key, value):
        if key == "Powered" and value:
            GLib.source_remove(source)
            adapter.disconnect_signal(sig)
            callback()

    def on_timeout():
        bluez_adapter.disconnect_signal(sig)
        GLib.source_remove(source)
        dprint(
            YELLOW("Warning:"),
            "Bluez didn't provide 'Powered' property in a reasonable timeout\nAssuming adapter is ready",
        )
        callback()

    props = bluez_adapter.get_properties()
    if props["Address"] != "00:00:00:00:00:00":
        callback()
        return

    source = GLib.timeout_add(timeout, on_timeout)
    sig = bluez_adapter.connect_signal("property-changed", on_prop_changed)


# Traceback (AttributeError)
_________
_on_property_changed (/usr/lib64/python2.7/site-packages/blueman/bluez/PropertiesBase.py:28)
None Connected 0
Traceback (most recent call last):
File "/usr/lib64/python2.7/site-packages/blueman/plugins/applet/SerialManager.py", line 59, in _on_device_property_changed
self.terminate_all_scripts(device.Address)
AttributeError: 'Device' object has no attribute 'Address'

# Fixed code
def wait_for_adapter(bluez_adapter, callback, timeout=1000):
    def on_prop_changed(adapter, key, value, _path):
        if key == "Powered" and value:
            GLib.source_remove(source)
            adapter.disconnect_signal(sig)
            callback()

    def on_timeout():
        bluez_adapter.disconnect_signal(sig)
        GLib.source_remove(source)
        dprint(
            YELLOW("Warning:"),
            "Bluez didn't provide 'Powered' property in a reasonable timeout\nAssuming adapter is ready",
        )
        callback()

    props = bluez_adapter.get_properties()
    if props["Address"] != "00:00:00:00:00:00":
        callback()
        return

    source = GLib.timeout_add(timeout, on_timeout)
    sig = bluez_adapter.connect_signal("property-changed", on_prop_changed)
# Buggy code
def on_prop_changed(adapter, key, value):
    if key == "Powered" and value:
        GLib.source_remove(source)
        adapter.disconnect_signal(sig)
        callback()


# Traceback (AttributeError)
_________
_on_property_changed (/usr/lib64/python2.7/site-packages/blueman/bluez/PropertiesBase.py:28)
None Connected 0
Traceback (most recent call last):
File "/usr/lib64/python2.7/site-packages/blueman/plugins/applet/SerialManager.py", line 59, in _on_device_property_changed
self.terminate_all_scripts(device.Address)
AttributeError: 'Device' object has no attribute 'Address'

# Fixed code
def on_prop_changed(adapter, key, value, _path):
    if key == "Powered" and value:
        GLib.source_remove(source)
        adapter.disconnect_signal(sig)
        callback()
# Buggy code
def _handle_signal(self, handler, signal, interface_name=None, object_path=None):
    args = (
        handler,
        signal,
        interface_name or self.__interface_name,
        self.__bus_name,
        object_path or self.__obj_path,
    )
    self.__bus.add_signal_receiver(*args)
    self.__signals.append(args)


# Traceback (AttributeError)
_________
_on_property_changed (/usr/lib64/python2.7/site-packages/blueman/bluez/PropertiesBase.py:28)
None Connected 0
Traceback (most recent call last):
File "/usr/lib64/python2.7/site-packages/blueman/plugins/applet/SerialManager.py", line 59, in _on_device_property_changed
self.terminate_all_scripts(device.Address)
AttributeError: 'Device' object has no attribute 'Address'

# Fixed code
def _handle_signal(
    self, handler, signal, interface_name=None, object_path=None, path_keyword=None
):
    args = (
        handler,
        signal,
        interface_name or self.__interface_name,
        self.__bus_name,
        object_path or self.__obj_path,
    )
    self.__bus.add_signal_receiver(*args, path_keyword=path_keyword)
    self.__signals.append(args)
# Buggy code
def __init__(self, interface, obj_path):
    super(PropertiesBase, self).__init__(interface, obj_path)

    self._handler_wrappers = {}

    if obj_path:
        self.__properties_interface = dbus.Interface(
            self._dbus_proxy, "org.freedesktop.DBus.Properties"
        )

    self._handle_signal(
        self._on_properties_changed,
        "PropertiesChanged",
        "org.freedesktop.DBus.Properties",
    )


# Traceback (AttributeError)
_________
_on_property_changed (/usr/lib64/python2.7/site-packages/blueman/bluez/PropertiesBase.py:28)
None Connected 0
Traceback (most recent call last):
File "/usr/lib64/python2.7/site-packages/blueman/plugins/applet/SerialManager.py", line 59, in _on_device_property_changed
self.terminate_all_scripts(device.Address)
AttributeError: 'Device' object has no attribute 'Address'

# Fixed code
def __init__(self, interface, obj_path):
    super(PropertiesBase, self).__init__(interface, obj_path)

    self._handler_wrappers = {}

    if obj_path:
        self.__properties_interface = dbus.Interface(
            self._dbus_proxy, "org.freedesktop.DBus.Properties"
        )

    self._handle_signal(
        self._on_properties_changed,
        "PropertiesChanged",
        "org.freedesktop.DBus.Properties",
        path_keyword="path",
    )
# Buggy code
def _on_property_changed(self, key, value):
    dprint(self.get_object_path(), key, value)
    self.emit("property-changed", key, value)


# Traceback (AttributeError)
_________
_on_property_changed (/usr/lib64/python2.7/site-packages/blueman/bluez/PropertiesBase.py:28)
None Connected 0
Traceback (most recent call last):
File "/usr/lib64/python2.7/site-packages/blueman/plugins/applet/SerialManager.py", line 59, in _on_device_property_changed
self.terminate_all_scripts(device.Address)
AttributeError: 'Device' object has no attribute 'Address'

# Fixed code
def _on_property_changed(self, key, value, path):
    dprint(path, key, value)
    self.emit("property-changed", key, value, path)
# Buggy code
def _on_properties_changed(
    self, interface_name, changed_properties, _invalidated_properties
):
    if interface_name == self._interface_name:
        for name, value in changed_properties.items():
            self._on_property_changed(name, value)


# Traceback (AttributeError)
_________
_on_property_changed (/usr/lib64/python2.7/site-packages/blueman/bluez/PropertiesBase.py:28)
None Connected 0
Traceback (most recent call last):
File "/usr/lib64/python2.7/site-packages/blueman/plugins/applet/SerialManager.py", line 59, in _on_device_property_changed
self.terminate_all_scripts(device.Address)
AttributeError: 'Device' object has no attribute 'Address'

# Fixed code
def _on_properties_changed(
    self, interface_name, changed_properties, _invalidated_properties, path
):
    if interface_name == self._interface_name:
        for name, value in changed_properties.items():
            self._on_property_changed(name, value, path)
# Buggy code
def _on_property_changed(self, _adapter, key, value):
    if key == "Discovering":
        if not value and self.discovering:
            self.StopDiscovery()

    self.emit("adapter-property-changed", self.Adapter, (key, value))


# Traceback (AttributeError)
_________
_on_property_changed (/usr/lib64/python2.7/site-packages/blueman/bluez/PropertiesBase.py:28)
None Connected 0
Traceback (most recent call last):
File "/usr/lib64/python2.7/site-packages/blueman/plugins/applet/SerialManager.py", line 59, in _on_device_property_changed
self.terminate_all_scripts(device.Address)
AttributeError: 'Device' object has no attribute 'Address'

# Fixed code
def _on_property_changed(self, _adapter, key, value, _path):
    if key == "Discovering":
        if not value and self.discovering:
            self.StopDiscovery()

    self.emit("adapter-property-changed", self.Adapter, (key, value))
# Buggy code
def _on_device_property_changed(self, device, key, value):
    iter = self.find_device_by_path(device.get_object_path())

    if iter != None:
        dev = self.get(iter, "device")["device"]
        self.row_update_event(iter, key, value)

        self.emit("device-property-changed", dev, iter, (key, value))

        if key == "Connected":
            if value:
                self.monitor_power_levels(dev)
            else:
                r = Gtk.TreeRowReference.new(
                    self.get_model(), self.props.model.get_path(iter)
                )
                self.level_setup_event(r, dev, None)

        elif key == "Paired":
            if value and dev.Temp:
                dev.Temp = False


# Traceback (AttributeError)
_________
_on_property_changed (/usr/lib64/python2.7/site-packages/blueman/bluez/PropertiesBase.py:28)
None Connected 0
Traceback (most recent call last):
File "/usr/lib64/python2.7/site-packages/blueman/plugins/applet/SerialManager.py", line 59, in _on_device_property_changed
self.terminate_all_scripts(device.Address)
AttributeError: 'Device' object has no attribute 'Address'

# Fixed code
def _on_device_property_changed(self, _device, key, value, path):
    iter = self.find_device_by_path(path)

    if iter != None:
        dev = self.get(iter, "device")["device"]
        self.row_update_event(iter, key, value)

        self.emit("device-property-changed", dev, iter, (key, value))

        if key == "Connected":
            if value:
                self.monitor_power_levels(dev)
            else:
                r = Gtk.TreeRowReference.new(
                    self.get_model(), self.props.model.get_path(iter)
                )
                self.level_setup_event(r, dev, None)

        elif key == "Paired":
            if value and dev.Temp:
                dev.Temp = False
# Buggy code
def _on_service_property_changed(self, _service, key, value):
    if key == "Connected":
        self.Generate()


# Traceback (AttributeError)
_________
_on_property_changed (/usr/lib64/python2.7/site-packages/blueman/bluez/PropertiesBase.py:28)
None Connected 0
Traceback (most recent call last):
File "/usr/lib64/python2.7/site-packages/blueman/plugins/applet/SerialManager.py", line 59, in _on_device_property_changed
self.terminate_all_scripts(device.Address)
AttributeError: 'Device' object has no attribute 'Address'

# Fixed code
def _on_service_property_changed(self, _service, key, _value, _path):
    if key == "Connected":
        self.Generate()
# Buggy code
def __init__(self, instance):
    GObject.GObject.__init__(self)

    self.Properties = {}
    self.Temp = False

    if hasattr(instance, "format") and hasattr(instance, "upper"):
        self.Device = BluezDevice(instance)
    else:
        self.Device = instance

    # set fallback icon, fixes lp:#327718
    self.Device.Icon = "blueman"
    self.Device.Class = "unknown"

    self.Valid = True

    dprint("caching initial properties")
    self.Properties = self.Device.get_properties()

    w = weakref.ref(self)
    self._obj_path = self.Device.get_object_path()
    self.Device.connect_signal(
        "property-changed",
        lambda _device, key, value: w() and w().property_changed(key, value),
    )
    self._manager = Manager()
    self._manager.connect_signal(
        "device-removed", lambda _adapter, path: w() and w().on_device_removed(path)
    )


# Traceback (AttributeError)
_________
_on_property_changed (/usr/lib64/python2.7/site-packages/blueman/bluez/PropertiesBase.py:28)
None Connected 0
Traceback (most recent call last):
File "/usr/lib64/python2.7/site-packages/blueman/plugins/applet/SerialManager.py", line 59, in _on_device_property_changed
self.terminate_all_scripts(device.Address)
AttributeError: 'Device' object has no attribute 'Address'

# Fixed code
def __init__(self, instance):
    GObject.GObject.__init__(self)

    self.Properties = {}
    self.Temp = False

    if hasattr(instance, "format") and hasattr(instance, "upper"):
        self.Device = BluezDevice(instance)
    else:
        self.Device = instance

    # set fallback icon, fixes lp:#327718
    self.Device.Icon = "blueman"
    self.Device.Class = "unknown"

    self.Valid = True

    dprint("caching initial properties")
    self.Properties = self.Device.get_properties()

    w = weakref.ref(self)
    self._obj_path = self.Device.get_object_path()
    self.Device.connect_signal(
        "property-changed",
        lambda _device, key, value, _path: w() and w().property_changed(key, value),
    )
    self._manager = Manager()
    self._manager.connect_signal(
        "device-removed", lambda _adapter, path: w() and w().on_device_removed(path)
    )
# Buggy code
def _on_network_prop_changed(self, _network, key, value):
    if key == "Interface":
        if value != "":
            self.dhcp_acquire(value)


# Traceback (AttributeError)
_________
_on_property_changed (/usr/lib64/python2.7/site-packages/blueman/bluez/PropertiesBase.py:28)
None Connected 0
Traceback (most recent call last):
File "/usr/lib64/python2.7/site-packages/blueman/plugins/applet/SerialManager.py", line 59, in _on_device_property_changed
self.terminate_all_scripts(device.Address)
AttributeError: 'Device' object has no attribute 'Address'

# Fixed code
def _on_network_prop_changed(self, _network, key, value, _path):
    if key == "Interface":
        if value != "":
            self.dhcp_acquire(value)
# Buggy code
def _on_device_property_changed(self, device, key, value):
    if key == "Connected":
        klass = device.get_properties()["Class"] & 0x1FFF

        if klass == 0x504 or klass == 0x508:
            if value:
                self.xdg_screensaver("suspend")
            else:
                self.xdg_screensaver("resume")


# Traceback (AttributeError)
_________
_on_property_changed (/usr/lib64/python2.7/site-packages/blueman/bluez/PropertiesBase.py:28)
None Connected 0
Traceback (most recent call last):
File "/usr/lib64/python2.7/site-packages/blueman/plugins/applet/SerialManager.py", line 59, in _on_device_property_changed
self.terminate_all_scripts(device.Address)
AttributeError: 'Device' object has no attribute 'Address'

# Fixed code
def _on_device_property_changed(self, _device, key, value, path):
    if key == "Connected":
        klass = bluez.Device(path).get_properties()["Class"] & 0x1FFF

        if klass == 0x504 or klass == 0x508:
            if value:
                self.xdg_screensaver("suspend")
            else:
                self.xdg_screensaver("resume")
# Buggy code
def _on_network_property_changed(self, network, key, value):
    if key == "Interface" and value != "":
        d = BluezDevice(network.get_object_path())
        d = Device(d)
        self.monitor_interface(Monitor, d, value)


# Traceback (AttributeError)
_________
_on_property_changed (/usr/lib64/python2.7/site-packages/blueman/bluez/PropertiesBase.py:28)
None Connected 0
Traceback (most recent call last):
File "/usr/lib64/python2.7/site-packages/blueman/plugins/applet/SerialManager.py", line 59, in _on_device_property_changed
self.terminate_all_scripts(device.Address)
AttributeError: 'Device' object has no attribute 'Address'

# Fixed code
def _on_network_property_changed(self, _network, key, value, path):
    if key == "Interface" and value != "":
        d = BluezDevice(path)
        d = Device(d)
        self.monitor_interface(Monitor, d, value)
# Buggy code
def _on_adapter_property_changed(self, _adapter, key, value):
    if key == "Powered":
        if value and not self.CurrentState:
            dprint("adapter powered on while in off state, turning bluetooth on")
            self.RequestPowerState(True)

        self.UpdatePowerState()


# Traceback (AttributeError)
_________
_on_property_changed (/usr/lib64/python2.7/site-packages/blueman/bluez/PropertiesBase.py:28)
None Connected 0
Traceback (most recent call last):
File "/usr/lib64/python2.7/site-packages/blueman/plugins/applet/SerialManager.py", line 59, in _on_device_property_changed
self.terminate_all_scripts(device.Address)
AttributeError: 'Device' object has no attribute 'Address'

# Fixed code
def _on_adapter_property_changed(self, _adapter, key, value, _path):
    if key == "Powered":
        if value and not self.CurrentState:
            dprint("adapter powered on while in off state, turning bluetooth on")
            self.RequestPowerState(True)

        self.UpdatePowerState()
# Buggy code
def _on_device_property_changed(self, device, key, value):
    if key == "Connected" and not value:
        self.terminate_all_scripts(device.Address)


# Traceback (AttributeError)
_________
_on_property_changed (/usr/lib64/python2.7/site-packages/blueman/bluez/PropertiesBase.py:28)
None Connected 0
Traceback (most recent call last):
File "/usr/lib64/python2.7/site-packages/blueman/plugins/applet/SerialManager.py", line 59, in _on_device_property_changed
self.terminate_all_scripts(device.Address)
AttributeError: 'Device' object has no attribute 'Address'

# Fixed code
def _on_device_property_changed(self, _device, key, value, path):
    if key == "Connected" and not value:
        self.terminate_all_scripts(Device(path).Address)
# Buggy code
def _on_device_property_changed(self, _device, key, value):
    if key == "Connected":
        if value:
            self.num_connections += 1
        else:
            self.num_connections -= 1

        if (self.num_connections > 0 and not self.active) or (
            self.num_connections == 0 and self.active
        ):
            self.Applet.Plugins.StatusIcon.IconShouldChange()

        self.update_statusicon()


# Traceback (AttributeError)
_________
_on_property_changed (/usr/lib64/python2.7/site-packages/blueman/bluez/PropertiesBase.py:28)
None Connected 0
Traceback (most recent call last):
File "/usr/lib64/python2.7/site-packages/blueman/plugins/applet/SerialManager.py", line 59, in _on_device_property_changed
self.terminate_all_scripts(device.Address)
AttributeError: 'Device' object has no attribute 'Address'

# Fixed code
def _on_device_property_changed(self, _device, key, value, _path):
    if key == "Connected":
        if value:
            self.num_connections += 1
        else:
            self.num_connections -= 1

        if (self.num_connections > 0 and not self.active) or (
            self.num_connections == 0 and self.active
        ):
            self.Applet.Plugins.StatusIcon.IconShouldChange()

        self.update_statusicon()
# Buggy code
def connected(self):
    return self._service.get_properties()["Connected"]


# Traceback (DBusException)
Run (/usr/local/lib/python2.7/site-packages/blueman/main/PluginManager.py:203)
Function on_request_menu_items on Services Failed
Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/blueman/main/PluginManager.py", line 207, in Run
ret = getattr(inst, function)(args, *kwargs)
File "/usr/local/lib/python2.7/site-packages/blueman/plugins/manager/Services.py", line 54, in on_request_menu_items
add_menu_item(manager_menu, service)
File "/usr/local/lib/python2.7/site-packages/blueman/plugins/manager/Services.py", line 29, in add_menu_item
if service.connected:
File "/usr/local/lib/python2.7/site-packages/blueman/services/meta/NetworkService.py", line 12, in connected
return self._service.get_properties()['Connected']
File "/usr/local/lib/python2.7/site-packages/blueman/bluez/errors.py", line 143, in warp
raise parse_dbus_error(exception)
DBusException: org.freedesktop.DBus.Error.InvalidArgs: No such interface 'org.bluez.Network1'

# Fixed code
def connected(self):
    try:
        return self._service.get_properties()["Connected"]
    except DBusException as e:
        dprint("Could not get properties of network service: %s" % e)
        return False
# Buggy code
def DisplayPasskey(self, device, passkey, entered):
    dprint("DisplayPasskey (%s, %d)" % (device, passkey))
    notify_message = _("Pairing passkey for") + " %s: %s" % (
        self.get_device_alias(device),
        passkey,
    )
    Notification(
        "Bluetooth",
        notify_message,
        0,
        pixbuf=get_icon("blueman", 48),
        status_icon=self.status_icon,
    )


# Traceback (UnknownMethodException)
aep-haswell bluetoothd[655]: Agent replied with an error: org.freedesktop.DBus.Error.UnknownMethod, Traceback (most recent call last):
File "/usr/lib64/python2.7/site-packages/dbus/service.py", line 654, in _message_cb
(candidate_method, parent_method) = _method_lookup(self, method_name, interface_name)
File "/usr/lib64/python2.7/site-packages/dbus/service.py", line 246, in _method_lookup
raise UnknownMethodException('%s is not a valid method of interface %s' % (method_name, dbus_interface))
UnknownMethodException: org.freedesktop.DBus.Error.UnknownMethod: Unknown method: DisplayPinCode is not a valid method of interface org.bluez.Agent1

# Fixed code
def DisplayPasskey(self, device, passkey, entered):
    dprint("DisplayPasskey (%s, %d)" % (device, passkey))
    notify_message = _("Pairing passkey for") + " %s: %s" % (
        self.get_device_alias(device),
        passkey,
    )
    self.n = Notification(
        "Bluetooth",
        notify_message,
        0,
        pixbuf=get_icon("blueman", 48),
        status_icon=self.status_icon,
    )
# Buggy code
def DisplayPinCode(self, device, pin_code):
    dprint("DisplayPinCode (%s, %s)" % (device, pin_code))
    notify_message = _("Pairing PIN code for") + " %s: %s" % (
        self.get_device_alias(device),
        pin_code,
    )
    Notification(
        "Bluetooth",
        notify_message,
        0,
        pixbuf=get_icon("blueman", 48),
        status_icon=self.status_icon,
    )


# Traceback (UnknownMethodException)
aep-haswell bluetoothd[655]: Agent replied with an error: org.freedesktop.DBus.Error.UnknownMethod, Traceback (most recent call last):
File "/usr/lib64/python2.7/site-packages/dbus/service.py", line 654, in _message_cb
(candidate_method, parent_method) = _method_lookup(self, method_name, interface_name)
File "/usr/lib64/python2.7/site-packages/dbus/service.py", line 246, in _method_lookup
raise UnknownMethodException('%s is not a valid method of interface %s' % (method_name, dbus_interface))
UnknownMethodException: org.freedesktop.DBus.Error.UnknownMethod: Unknown method: DisplayPinCode is not a valid method of interface org.bluez.Agent1

# Fixed code
def DisplayPinCode(self, device, pin_code):
    dprint("DisplayPinCode (%s, %s)" % (device, pin_code))
    notify_message = _("Pairing PIN code for") + " %s: %s" % (
        self.get_device_alias(device),
        pin_code,
    )
    self.n = Notification(
        "Bluetooth",
        notify_message,
        0,
        pixbuf=get_icon("blueman", 48),
        status_icon=self.status_icon,
    )
# Buggy code
def on_adapter_property_changed(self, list, adapter, kv):
    (key, value) = kv
    if key == "Name":
        self.generate_adapter_menu()
    elif key == "Discovering":
        if self.Search:
            if value:
                self.Search.props.sensitive = False
            else:
                self.Search.props.sensitive = True


# Traceback (AttributeError)
Traceback (most recent call last):
File "/usr/bin/blueman-adapters", line 78, in on_dialog_response
adapter.SetProperty('Name', settings['name'])
AttributeError: 'Adapter' object has no attribute 'SetProperty'

# Fixed code
def on_adapter_property_changed(self, list, adapter, kv):
    (key, value) = kv
    if key == "Name" or key == "Alias":
        self.generate_adapter_menu()
    elif key == "Discovering":
        if self.Search:
            if value:
                self.Search.props.sensitive = False
            else:
                self.Search.props.sensitive = True
# Buggy code
def generate_adapter_menu(self):
    menu = Gtk.Menu()

    sep = Gtk.SeparatorMenuItem()
    sep.show()
    menu.append(sep)

    settings = Gtk.ImageMenuItem.new_from_stock("gtk-preferences", None)
    settings.connect("activate", lambda x: self.blueman.adapter_properties())
    settings.show()
    menu.append(settings)

    group = []
    for adapter in self.adapters:
        props = adapter.get_properties()
        item = Gtk.RadioMenuItem.new_with_label(group, props["Name"])
        group = item.get_group()

        item.connect("activate", self.on_adapter_selected, adapter.get_object_path())
        if adapter.get_object_path() == self.blueman.List.Adapter.get_object_path():
            item.props.active = True

        item.show()
        menu.prepend(item)

    sep = Gtk.SeparatorMenuItem()
    sep.show()
    menu.prepend(sep)

    item = create_menuitem(_("_Search"), get_icon("gtk-find", 16))
    item.connect("activate", lambda x: self.blueman.inquiry())
    item.show()
    menu.prepend(item)
    self.Search = item

    m = self.item_adapter.get_submenu()
    if m != None:
        m.deactivate()
    self.item_adapter.set_submenu(menu)

    sep = Gtk.SeparatorMenuItem()
    sep.show()
    menu.append(sep)

    item = Gtk.ImageMenuItem.new_from_stock("gtk-quit", None)
    item.connect("activate", lambda x: Gtk.main_quit())
    item.show()
    menu.append(item)


# Traceback (AttributeError)
Traceback (most recent call last):
File "/usr/bin/blueman-adapters", line 78, in on_dialog_response
adapter.SetProperty('Name', settings['name'])
AttributeError: 'Adapter' object has no attribute 'SetProperty'

# Fixed code
def generate_adapter_menu(self):
    menu = Gtk.Menu()

    sep = Gtk.SeparatorMenuItem()
    sep.show()
    menu.append(sep)

    settings = Gtk.ImageMenuItem.new_from_stock("gtk-preferences", None)
    settings.connect("activate", lambda x: self.blueman.adapter_properties())
    settings.show()
    menu.append(settings)

    group = []
    for adapter in self.adapters:
        item = Gtk.RadioMenuItem.new_with_label(group, adapter.get_name())
        group = item.get_group()

        item.connect("activate", self.on_adapter_selected, adapter.get_object_path())
        if adapter.get_object_path() == self.blueman.List.Adapter.get_object_path():
            item.props.active = True

        item.show()
        menu.prepend(item)

    sep = Gtk.SeparatorMenuItem()
    sep.show()
    menu.prepend(sep)

    item = create_menuitem(_("_Search"), get_icon("gtk-find", 16))
    item.connect("activate", lambda x: self.blueman.inquiry())
    item.show()
    menu.prepend(item)
    self.Search = item

    m = self.item_adapter.get_submenu()
    if m != None:
        m.deactivate()
    self.item_adapter.set_submenu(menu)

    sep = Gtk.SeparatorMenuItem()
    sep.show()
    menu.append(sep)

    item = Gtk.ImageMenuItem.new_from_stock("gtk-quit", None)
    item.connect("activate", lambda x: Gtk.main_quit())
    item.show()
    menu.append(item)
# Buggy code
def _redirect(self, to_fd, unbuffered=False, close=False):
    if close:
        fp = getattr(sys, self._stream)
        # TODO(jhr): does this still work under windows?  are we leaking a fd?
        # Do not close old filedescriptor as others might be using it
        fp.close()
    os.dup2(to_fd, self._old_fd)
    if self._io_wrapped:
        if close:
            setattr(sys, self._stream, getattr(sys, self._stream).output_streams[0])
        else:
            setattr(
                sys,
                self._stream,
                StreamFork(
                    [getattr(sys, self._stream), os.fdopen(self._old_fd, "w")],
                    unbuffered=unbuffered,
                ),
            )
    else:
        setattr(sys, self._stream, os.fdopen(self._old_fd, "w"))
        if unbuffered:
            setattr(sys, self._stream, Unbuffered(getattr(sys, self._stream)))


# Traceback (AttributeError)
Error in atexit._run_exitfuncs:
Traceback (most recent call last):
File "/opt/conda/lib/python3.7/site-packages/wandb/sdk/wandb_run.py",
line 1172, in _atexit_cleanup
self._on_finish()
File "/opt/conda/lib/python3.7/site-packages/wandb/sdk/wandb_run.py",
line 1292, in _on_finish
self._console_stop() # TODO: there's a race here with jupyter console
logging
File "/opt/conda/lib/python3.7/site-packages/wandb/sdk/wandb_run.py",
line 1203, in _console_stop
self._restore()
File "/opt/conda/lib/python3.7/site-packages/wandb/sdk/wandb_run.py",
line 1140, in _restore
self._out_redir.uninstall()
File "/opt/conda/lib/python3.7/site-packages/wandb/lib/redirect.py",
line 207, in uninstall
self._redirect(to_fd=self._old_fp.fileno(), close=True)
File "/opt/conda/lib/python3.7/site-packages/wandb/lib/redirect.py",
line 161, in _redirect
fp.close()
AttributeError: 'TeeHandler' object has no attribute 'close'

# Fixed code
def _redirect(self, to_fd, unbuffered=False, close=False):
    if close:
        fp = getattr(sys, self._stream)
        # TODO(jhr): does this still work under windows?  are we leaking a fd?
        # Do not close old filedescriptor as others might be using it
        try:
            fp.close()
        except Exception:
            pass  # Stream might be wrapped by another program which doesn't support closing.
    os.dup2(to_fd, self._old_fd)
    if self._io_wrapped:
        if close:
            setattr(sys, self._stream, getattr(sys, self._stream).output_streams[0])
        else:
            setattr(
                sys,
                self._stream,
                StreamFork(
                    [getattr(sys, self._stream), os.fdopen(self._old_fd, "w")],
                    unbuffered=unbuffered,
                ),
            )
    else:
        setattr(sys, self._stream, os.fdopen(self._old_fd, "w"))
        if unbuffered:
            setattr(sys, self._stream, Unbuffered(getattr(sys, self._stream)))
# Buggy code
def _set_win_sizes(self):
    try:
        win_size = fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, "\0" * 8)
    except OSError:  # eg. in MPI we can't do this
        rows, cols, xpix, ypix = 25, 80, 0, 0
    else:
        rows, cols, xpix, ypix = array.array("h", win_size)

    if cols == 0:
        cols = 80

    win_size = struct.pack("HHHH", rows, cols, xpix, ypix)

    for fd in self.fds:
        try:
            fcntl.ioctl(fd, termios.TIOCSWINSZ, win_size)
        except OSError:  # eg. in MPI we can't do this
            pass


# Traceback (struct.error)
(main) ÷19-06-28 09:14:41|ttys010|trippings-mbp-3|~/git0/mindscribe-question-ai\÷ python
Python 3.6.8 |Anaconda, Inc.| (default, Dec 29 2018, 19:04:46)
[GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
import wandb
wandb.init(project='moonscrub')
wandb: Started W&amp;B process version 0.8.3 with PID 33316
wandb: Local directory: wandb/run-20190628_161454-0ti1q1zb
wandb: Syncing run easy-lion-3: https://app.wandb.ai/yaroslavvb/moonscrub/runs/0ti1q1zb
wandb: Run `wandb off` to turn off syncing.
Traceback (most recent call last):
File "/Users/yaroslavvb/anaconda3/envs/main/lib/python3.6/site-packages/wandb/internal_cli.py", line 105, in <module>
main()
File "/Users/yaroslavvb/anaconda3/envs/main/lib/python3.6/site-packages/wandb/internal_cli.py", line 97, in main
headless(args)
File "/Users/yaroslavvb/anaconda3/envs/main/lib/python3.6/site-packages/wandb/internal_cli.py", line 53, in headless
util.sentry_reraise(e)
File "/Users/yaroslavvb/anaconda3/envs/main/lib/python3.6/site-packages/wandb/util.py", line 88, in sentry_reraise
six.reraise(type(exc), exc, sys.exc_info()[2])
File "/Users/yaroslavvb/anaconda3/envs/main/lib/python3.6/site-packages/six.py", line 693, in reraise
raise value
File "/Users/yaroslavvb/anaconda3/envs/main/lib/python3.6/site-packages/wandb/internal_cli.py", line 51, in headless
user_process_pid, stdout_master_fd, stderr_master_fd)
File "/Users/yaroslavvb/anaconda3/envs/main/lib/python3.6/site-packages/wandb/run_manager.py", line 1053, in wrap_existing_process
io_wrap.SIGWINCH_HANDLER.add_fd(stdout_read_fd)
File "/Users/yaroslavvb/anaconda3/envs/main/lib/python3.6/site-packages/wandb/io_wrap.py", line 118, in add_fd
self._set_win_sizes()
File "/Users/yaroslavvb/anaconda3/envs/main/lib/python3.6/site-packages/wandb/io_wrap.py", line 138, in _set_win_sizes
win_size = struct.pack("HHHH", rows, cols, xpix, ypix)
struct.error: ushort format requires 0 <= number <= (32767 *2 +1)

# Fixed code
def _set_win_sizes(self):
    try:
        win_size = fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, "\0" * 8)
    except OSError:  # eg. in MPI we can't do this
        rows, cols, xpix, ypix = 25, 80, 0, 0
    else:
        rows, cols, xpix, ypix = struct.unpack("HHHH", win_size)

    if cols == 0:
        cols = 80

    win_size = struct.pack("HHHH", rows, cols, xpix, ypix)

    for fd in self.fds:
        try:
            fcntl.ioctl(fd, termios.TIOCSWINSZ, win_size)
        except OSError:  # eg. in MPI we can't do this
            pass