gurudesh/pytracebugs huggingface dataset:
# Buggy code
async def connect(self) -> bool:
    """Connect to the specified GATT server.

    Returns:
        Boolean representing connection status.

    """
    raise NotImplementedError()


# Traceback (builtins.AttributeError)
Unhandled Error
Traceback (most recent call last):
File "/home/usr/dir/virtualEnv/lib/python3.6/site-packages/txdbus/protocol.py", line 141, in dataReceived
self.rawDBusMessageReceived(raw_msg)
File "/home/usr/dir/virtualEnv/lib/python3.6/site-packages/txdbus/protocol.py", line 262, in rawDBusMessageReceived
self.signalReceived(m)
File "/home/usr/dir/virtualEnv/lib/python3.6/site-packages/txdbus/client.py", line 643, in signalReceived
self.router.routeMessage(msig)
File "/home/usr/dir/virtualEnv/lib/python3.6/site-packages/txdbus/router.py", line 128, in routeMessage
r.match(m)
--- <exception caught here> ---
File "/home/usr/dir/virtualEnv/lib/python3.6/site-packages/txdbus/router.py", line 67, in match
self.callback(m)
File "/home/usr/dir/virtualEnv/lib/python3.6/site-packages/bleak/backends/bluezdbus/discovery.py", line 109, in parse_msg
*_device_info(msg_path, devices.get(msg_path))
File "/home/usr/dir/virtualEnv/lib/python3.6/site-packages/bleak/backends/bluezdbus/discovery.py", line 39, in _device_info
name = props.get("Name", props.get("Alias", path.split("/")[-1]))
builtins.AttributeError: 'NoneType' object has no attribute 'get'

# Fixed code
async def connect(self, **kwargs) -> bool:
    """Connect to the specified GATT server.

    Returns:
        Boolean representing connection status.

    """
    raise NotImplementedError()
# Buggy code
def __init__(self, address: str, loop: AbstractEventLoop = None, **kwargs):
    super(BleakClientDotNet, self).__init__(address, loop, **kwargs)

    # Backend specific. Python.NET objects.
    self._device_info = None
    self._requester = None
    self._bridge = Bridge()
    self._callbacks = {}


# Traceback (builtins.AttributeError)
Unhandled Error
Traceback (most recent call last):
File "/home/usr/dir/virtualEnv/lib/python3.6/site-packages/txdbus/protocol.py", line 141, in dataReceived
self.rawDBusMessageReceived(raw_msg)
File "/home/usr/dir/virtualEnv/lib/python3.6/site-packages/txdbus/protocol.py", line 262, in rawDBusMessageReceived
self.signalReceived(m)
File "/home/usr/dir/virtualEnv/lib/python3.6/site-packages/txdbus/client.py", line 643, in signalReceived
self.router.routeMessage(msig)
File "/home/usr/dir/virtualEnv/lib/python3.6/site-packages/txdbus/router.py", line 128, in routeMessage
r.match(m)
--- <exception caught here> ---
File "/home/usr/dir/virtualEnv/lib/python3.6/site-packages/txdbus/router.py", line 67, in match
self.callback(m)
File "/home/usr/dir/virtualEnv/lib/python3.6/site-packages/bleak/backends/bluezdbus/discovery.py", line 109, in parse_msg
*_device_info(msg_path, devices.get(msg_path))
File "/home/usr/dir/virtualEnv/lib/python3.6/site-packages/bleak/backends/bluezdbus/discovery.py", line 39, in _device_info
name = props.get("Name", props.get("Alias", path.split("/")[-1]))
builtins.AttributeError: 'NoneType' object has no attribute 'get'

# Fixed code
def __init__(self, address: str, loop: AbstractEventLoop = None, **kwargs):
    super(BleakClientDotNet, self).__init__(address, loop, **kwargs)

    # Backend specific. Python.NET objects.
    self._device_info = None
    self._requester = None
    self._bridge = Bridge()
    self._callbacks = {}

    self._address_type = (
        kwargs["address_type"]
        if "address_type" in kwargs and kwargs["address_type"] in ("public", "random")
        else None
    )
# Buggy code
def __init__(self, address, loop=None, **kwargs):
    super(BleakClientBlueZDBus, self).__init__(address, loop, **kwargs)
    self.device = kwargs.get("device") if kwargs.get("device") else "hci0"
    self.address = address

    # Backend specific, TXDBus objects and data
    self._device_path = None
    self._bus = None
    self._descriptors = {}
    self._rules = {}

    self._char_path_to_uuid = {}


# Traceback (bleak.exc.BleakError)
Traceback (most recent call last):
File "/home/jonas/Schreibtisch/TMRTFlib.py", line 572, in <module>
loop.run_until_complete(connect_device_bleak(address, loop))
File "/usr/lib/python3.6/asyncio/base_events.py", line 473, in run_until_complete
return future.result()
File "/home/jonas/Schreibtisch/TMRTFlib.py", line 552, in connect_device_bleak
async with BleakClient(address, loop=loop) as client:
File "/home/jonas/.local/lib/python3.6/site-packages/bleak/backends/client.py", line 35, in __aenter__
await self.connect()
File "/home/jonas/.local/lib/python3.6/site-packages/bleak/backends/bluezdbus/client.py", line 76, in connect
raise BleakError(str(e))
bleak.exc.BleakError: org.freedesktop.DBus.Error.UnknownObject: Method "Connect" with signature "" on interface "org.bluez.Device1" doesn't exist

# Fixed code
def __init__(self, address, loop=None, **kwargs):
    super(BleakClientBlueZDBus, self).__init__(address, loop, **kwargs)
    self.device = kwargs.get("device") if kwargs.get("device") else "hci0"
    self.address = address

    # Backend specific, TXDBus objects and data
    self._device_path = None
    self._bus = None
    self._rules = {}

    self._char_path_to_uuid = {}

    # We need to know BlueZ version since battery level characteristic
    # are stored in a separate DBus interface in the BlueZ >= 5.48.
    p = subprocess.Popen(["bluetoothctl", "--version"], stdout=subprocess.PIPE)
    out, _ = p.communicate()
    s = re.search(b"(\\d+).(\\d+)", out.strip(b"'"))
    self._bluez_version = tuple(map(int, s.groups()))
# Buggy code
async def write_gatt_char(
    self, _uuid: str, data: bytearray, response: bool = False
) -> Any:
    """Write data to a GATT characteristic.

    Args:
        _uuid (str or uuid.UUID): The UUID of the GATT
        characteristic to write to.
        data (bytearray):
        response (bool): Write with response.

    Returns:
        None if not `response=True`, in which case a bytearray is returned.

    """
    char_props = self.characteristics.get(str(_uuid))
    await self._bus.callRemote(
        char_props.get("Path"),
        "WriteValue",
        interface=defs.GATT_CHARACTERISTIC_INTERFACE,
        destination=defs.BLUEZ_SERVICE,
        signature="aya{sv}",
        body=[data, {}],
        returnSignature="",
    ).asFuture(self.loop)
    logger.debug(
        "Write Characteristic {0} | {1}: {2}".format(
            _uuid, char_props.get("Path"), data
        )
    )
    if response:
        return await self.read_gatt_char(_uuid)


# Traceback (bleak.exc.BleakError)
Traceback (most recent call last):
File "/home/jonas/Schreibtisch/TMRTFlib.py", line 572, in <module>
loop.run_until_complete(connect_device_bleak(address, loop))
File "/usr/lib/python3.6/asyncio/base_events.py", line 473, in run_until_complete
return future.result()
File "/home/jonas/Schreibtisch/TMRTFlib.py", line 552, in connect_device_bleak
async with BleakClient(address, loop=loop) as client:
File "/home/jonas/.local/lib/python3.6/site-packages/bleak/backends/client.py", line 35, in __aenter__
await self.connect()
File "/home/jonas/.local/lib/python3.6/site-packages/bleak/backends/bluezdbus/client.py", line 76, in connect
raise BleakError(str(e))
bleak.exc.BleakError: org.freedesktop.DBus.Error.UnknownObject: Method "Connect" with signature "" on interface "org.bluez.Device1" doesn't exist

# Fixed code
async def write_gatt_char(
    self, _uuid: str, data: bytearray, response: bool = False
) -> Any:
    """Write data to a GATT characteristic.

    Args:
        _uuid (str or uuid.UUID): The UUID of the GATT characteristic to write to.
        data (bytearray): The data to write.
        response (bool): If write with response should be done.

    Returns:
        None if not `response=True`, in which case a bytearray is returned.

    """
    characteristic = self.services.get_characteristic(str(_uuid))
    await self._bus.callRemote(
        characteristic.path,
        "WriteValue",
        interface=defs.GATT_CHARACTERISTIC_INTERFACE,
        destination=defs.BLUEZ_SERVICE,
        signature="aya{sv}",
        body=[data, {}],
        returnSignature="",
    ).asFuture(self.loop)
    logger.debug(
        "Write Characteristic {0} | {1}: {2}".format(_uuid, characteristic.path, data)
    )
    if response:
        return await self.read_gatt_char(_uuid)
# Buggy code
async def stop_notify(self, _uuid: str) -> None:
    """Stops a notification session from a characteristic.

    Args:
        _uuid (str or uuid.UUID): The UUID of the characteristic to stop
        subscribing to notifications from.

    """
    char_props = self.characteristics.get(_uuid)
    await self._bus.callRemote(
        char_props.get("Path"),
        "StopNotify",
        interface=defs.GATT_CHARACTERISTIC_INTERFACE,
        destination=defs.BLUEZ_SERVICE,
        signature="",
        body=[],
        returnSignature="",
    ).asFuture(self.loop)
    self._notification_callbacks.pop(char_props.get("Path"), None)


# Traceback (bleak.exc.BleakError)
Traceback (most recent call last):
File "/home/jonas/Schreibtisch/TMRTFlib.py", line 572, in <module>
loop.run_until_complete(connect_device_bleak(address, loop))
File "/usr/lib/python3.6/asyncio/base_events.py", line 473, in run_until_complete
return future.result()
File "/home/jonas/Schreibtisch/TMRTFlib.py", line 552, in connect_device_bleak
async with BleakClient(address, loop=loop) as client:
File "/home/jonas/.local/lib/python3.6/site-packages/bleak/backends/client.py", line 35, in __aenter__
await self.connect()
File "/home/jonas/.local/lib/python3.6/site-packages/bleak/backends/bluezdbus/client.py", line 76, in connect
raise BleakError(str(e))
bleak.exc.BleakError: org.freedesktop.DBus.Error.UnknownObject: Method "Connect" with signature "" on interface "org.bluez.Device1" doesn't exist

# Fixed code
async def stop_notify(self, _uuid: str) -> None:
    """Stops a notification session from a characteristic.

    Args:
        _uuid (str or uuid.UUID): The UUID of the characteristic to stop
            subscribing to notifications from.

    """
    characteristic = self.services.get_characteristic(str(_uuid))
    await self._bus.callRemote(
        characteristic.path,
        "StopNotify",
        interface=defs.GATT_CHARACTERISTIC_INTERFACE,
        destination=defs.BLUEZ_SERVICE,
        signature="",
        body=[],
        returnSignature="",
    ).asFuture(self.loop)
    self._notification_callbacks.pop(characteristic.path, None)
# Buggy code
async def get_all_for_characteristic(self, _uuid):
    char_props = self.characteristics.get(str(_uuid))
    out = await self._bus.callRemote(
        char_props.get("Path"),
        "GetAll",
        interface=defs.PROPERTIES_INTERFACE,
        destination=defs.BLUEZ_SERVICE,
        signature="s",
        body=[defs.GATT_CHARACTERISTIC_INTERFACE],
        returnSignature="a{sv}",
    ).asFuture(self.loop)
    return out


# Traceback (bleak.exc.BleakError)
Traceback (most recent call last):
File "/home/jonas/Schreibtisch/TMRTFlib.py", line 572, in <module>
loop.run_until_complete(connect_device_bleak(address, loop))
File "/usr/lib/python3.6/asyncio/base_events.py", line 473, in run_until_complete
return future.result()
File "/home/jonas/Schreibtisch/TMRTFlib.py", line 552, in connect_device_bleak
async with BleakClient(address, loop=loop) as client:
File "/home/jonas/.local/lib/python3.6/site-packages/bleak/backends/client.py", line 35, in __aenter__
await self.connect()
File "/home/jonas/.local/lib/python3.6/site-packages/bleak/backends/bluezdbus/client.py", line 76, in connect
raise BleakError(str(e))
bleak.exc.BleakError: org.freedesktop.DBus.Error.UnknownObject: Method "Connect" with signature "" on interface "org.bluez.Device1" doesn't exist

# Fixed code
async def get_all_for_characteristic(self, _uuid):
    characteristic = self.services.get_characteristic(str(_uuid))
    out = await self._bus.callRemote(
        characteristic.path,
        "GetAll",
        interface=defs.PROPERTIES_INTERFACE,
        destination=defs.BLUEZ_SERVICE,
        signature="s",
        body=[defs.GATT_CHARACTERISTIC_INTERFACE],
        returnSignature="a{sv}",
    ).asFuture(self.loop)
    return out
# Buggy code
async def _get_device_properties(self):
    return await self._bus.callRemote(
        self._device_path,
        "GetAll",
        interface=defs.PROPERTIES_INTERFACE,
        destination=defs.BLUEZ_SERVICE,
        signature="s",
        body=[defs.DEVICE_INTERFACE],
        returnSignature="a{sv}",
    ).asFuture(self.loop)


# Traceback (bleak.exc.BleakError)
Traceback (most recent call last):
File "/home/jonas/Schreibtisch/TMRTFlib.py", line 572, in <module>
loop.run_until_complete(connect_device_bleak(address, loop))
File "/usr/lib/python3.6/asyncio/base_events.py", line 473, in run_until_complete
return future.result()
File "/home/jonas/Schreibtisch/TMRTFlib.py", line 552, in connect_device_bleak
async with BleakClient(address, loop=loop) as client:
File "/home/jonas/.local/lib/python3.6/site-packages/bleak/backends/client.py", line 35, in __aenter__
await self.connect()
File "/home/jonas/.local/lib/python3.6/site-packages/bleak/backends/bluezdbus/client.py", line 76, in connect
raise BleakError(str(e))
bleak.exc.BleakError: org.freedesktop.DBus.Error.UnknownObject: Method "Connect" with signature "" on interface "org.bluez.Device1" doesn't exist

# Fixed code
async def _get_device_properties(self, interface=defs.DEVICE_INTERFACE):
    return await self._bus.callRemote(
        self._device_path,
        "GetAll",
        interface=defs.PROPERTIES_INTERFACE,
        destination=defs.BLUEZ_SERVICE,
        signature="s",
        body=[interface],
        returnSignature="a{sv}",
    ).asFuture(self.loop)
# Buggy code
def _properties_changed_callback(self, message):
    """Notification handler.

    If the BlueZ DBus API, notifications come as
    PropertiesChanged callbacks on the GATT Characteristic interface
    that StartNotify has been called on.

    Args:
        message (): The PropertiesChanged DBus signal message relaying
            the new data on the GATT Characteristic.

    """
    if message.body[0] == defs.GATT_CHARACTERISTIC_INTERFACE:
        if message.path in self._notification_callbacks:
            logger.info(
                "GATT Char Properties Changed: {0} | {1}".format(
                    message.path, message.body[1:]
                )
            )
            self._notification_callbacks[message.path](message.path, message.body[1])


# Traceback (bleak.exc.BleakError)
Traceback (most recent call last):
File "/home/jonas/Schreibtisch/TMRTFlib.py", line 572, in <module>
loop.run_until_complete(connect_device_bleak(address, loop))
File "/usr/lib/python3.6/asyncio/base_events.py", line 473, in run_until_complete
return future.result()
File "/home/jonas/Schreibtisch/TMRTFlib.py", line 552, in connect_device_bleak
async with BleakClient(address, loop=loop) as client:
File "/home/jonas/.local/lib/python3.6/site-packages/bleak/backends/client.py", line 35, in __aenter__
await self.connect()
File "/home/jonas/.local/lib/python3.6/site-packages/bleak/backends/bluezdbus/client.py", line 76, in connect
raise BleakError(str(e))
bleak.exc.BleakError: org.freedesktop.DBus.Error.UnknownObject: Method "Connect" with signature "" on interface "org.bluez.Device1" doesn't exist

# Fixed code
def _properties_changed_callback(self, message):
    """Notification handler.

    In the BlueZ DBus API, notifications come as
    PropertiesChanged callbacks on the GATT Characteristic interface
    that StartNotify has been called on.

    Args:
        message (): The PropertiesChanged DBus signal message relaying
            the new data on the GATT Characteristic.

    """
    if message.body[0] == defs.GATT_CHARACTERISTIC_INTERFACE:
        if message.path in self._notification_callbacks:
            logger.info(
                "GATT Char Properties Changed: {0} | {1}".format(
                    message.path, message.body[1:]
                )
            )
            self._notification_callbacks[message.path](message.path, message.body[1])
# Buggy code
def parse_msg(message):
    if message.member in ("InterfacesAdded", "InterfacesRemoved"):
        msg_path = message.body[0]
        device_interface = message.body[1].get("org.bluez.Device1", {})
        devices[msg_path] = (
            {**devices[msg_path], **device_interface}
            if msg_path in devices
            else device_interface
        )
    elif message.member == "PropertiesChanged":
        iface, changed, invalidated = message.body
        if iface != defs.DEVICE_INTERFACE:
            return

        msg_path = message.path
        devices[msg_path] = (
            {**devices[msg_path], **changed} if msg_path in devices else changed
        )
    else:
        msg_path = message.path
        logger.info(
            "{0}, {1} ({2}): {3}".format(
                message.member, message.interface, message.path, message.body
            )
        )

    logger.info(
        "{0}, {1} ({2} dBm), Object Path: {3}".format(
            *_device_info(msg_path, devices.get(msg_path))
        )
    )


# Traceback (bleak.exc.BleakError)
Traceback (most recent call last):
File "/home/jonas/Schreibtisch/TMRTFlib.py", line 572, in <module>
loop.run_until_complete(connect_device_bleak(address, loop))
File "/usr/lib/python3.6/asyncio/base_events.py", line 473, in run_until_complete
return future.result()
File "/home/jonas/Schreibtisch/TMRTFlib.py", line 552, in connect_device_bleak
async with BleakClient(address, loop=loop) as client:
File "/home/jonas/.local/lib/python3.6/site-packages/bleak/backends/client.py", line 35, in __aenter__
await self.connect()
File "/home/jonas/.local/lib/python3.6/site-packages/bleak/backends/bluezdbus/client.py", line 76, in connect
raise BleakError(str(e))
bleak.exc.BleakError: org.freedesktop.DBus.Error.UnknownObject: Method "Connect" with signature "" on interface "org.bluez.Device1" doesn't exist

# Fixed code
def parse_msg(message):
    if message.member == "InterfacesAdded":
        msg_path = message.body[0]
        try:
            device_interface = message.body[1].get("org.bluez.Device1", {})
        except Exception as e:
            raise e
        devices[msg_path] = (
            {**devices[msg_path], **device_interface}
            if msg_path in devices
            else device_interface
        )
    elif message.member == "PropertiesChanged":
        iface, changed, invalidated = message.body
        if iface != defs.DEVICE_INTERFACE:
            return

        msg_path = message.path
        devices[msg_path] = (
            {**devices[msg_path], **changed} if msg_path in devices else changed
        )
    else:
        msg_path = message.path
        logger.info(
            "{0}, {1} ({2}): {3}".format(
                message.member, message.interface, message.path, message.body
            )
        )

    logger.info(
        "{0}, {1} ({2} dBm), Object Path: {3}".format(
            *_device_info(msg_path, devices.get(msg_path))
        )
    )
# Buggy code
def __init__(self, address, loop=None, **kwargs):
    self.address = address
    self.loop = loop if loop else asyncio.get_event_loop()
    self.services = {}
    self.characteristics = {}

    self._services_resolved = False
    self._notification_callbacks = {}


# Traceback (bleak.exc.BleakError)
Traceback (most recent call last):
File "/home/jonas/Schreibtisch/TMRTFlib.py", line 572, in <module>
loop.run_until_complete(connect_device_bleak(address, loop))
File "/usr/lib/python3.6/asyncio/base_events.py", line 473, in run_until_complete
return future.result()
File "/home/jonas/Schreibtisch/TMRTFlib.py", line 552, in connect_device_bleak
async with BleakClient(address, loop=loop) as client:
File "/home/jonas/.local/lib/python3.6/site-packages/bleak/backends/client.py", line 35, in __aenter__
await self.connect()
File "/home/jonas/.local/lib/python3.6/site-packages/bleak/backends/bluezdbus/client.py", line 76, in connect
raise BleakError(str(e))
bleak.exc.BleakError: org.freedesktop.DBus.Error.UnknownObject: Method "Connect" with signature "" on interface "org.bluez.Device1" doesn't exist

# Fixed code
def __init__(self, address, loop=None, **kwargs):
    self.address = address
    self.loop = loop if loop else asyncio.get_event_loop()

    self.services = BleakGATTServiceCollection()

    self._services_resolved = False
    self._notification_callbacks = {}
# Buggy code
async def get_services(self):
    raise NotImplementedError()


# Traceback (bleak.exc.BleakError)
Traceback (most recent call last):
File "/home/jonas/Schreibtisch/TMRTFlib.py", line 572, in <module>
loop.run_until_complete(connect_device_bleak(address, loop))
File "/usr/lib/python3.6/asyncio/base_events.py", line 473, in run_until_complete
return future.result()
File "/home/jonas/Schreibtisch/TMRTFlib.py", line 552, in connect_device_bleak
async with BleakClient(address, loop=loop) as client:
File "/home/jonas/.local/lib/python3.6/site-packages/bleak/backends/client.py", line 35, in __aenter__
await self.connect()
File "/home/jonas/.local/lib/python3.6/site-packages/bleak/backends/bluezdbus/client.py", line 76, in connect
raise BleakError(str(e))
bleak.exc.BleakError: org.freedesktop.DBus.Error.UnknownObject: Method "Connect" with signature "" on interface "org.bluez.Device1" doesn't exist

# Fixed code
async def get_services(self) -> BleakGATTServiceCollection:
    raise NotImplementedError()
# Buggy code
def __init__(self, address: str, loop: AbstractEventLoop = None, **kwargs):
    super(BleakClientDotNet, self).__init__(address, loop, **kwargs)

    # Backend specific. Python.NET objects.
    self._device_info = None
    self._requester = None
    self._bridge = Bridge()


# Traceback (bleak.exc.BleakError)
Traceback (most recent call last):
File "/home/jonas/Schreibtisch/TMRTFlib.py", line 572, in <module>
loop.run_until_complete(connect_device_bleak(address, loop))
File "/usr/lib/python3.6/asyncio/base_events.py", line 473, in run_until_complete
return future.result()
File "/home/jonas/Schreibtisch/TMRTFlib.py", line 552, in connect_device_bleak
async with BleakClient(address, loop=loop) as client:
File "/home/jonas/.local/lib/python3.6/site-packages/bleak/backends/client.py", line 35, in __aenter__
await self.connect()
File "/home/jonas/.local/lib/python3.6/site-packages/bleak/backends/bluezdbus/client.py", line 76, in connect
raise BleakError(str(e))
bleak.exc.BleakError: org.freedesktop.DBus.Error.UnknownObject: Method "Connect" with signature "" on interface "org.bluez.Device1" doesn't exist

# Fixed code
def __init__(self, address: str, loop: AbstractEventLoop = None, **kwargs):
    super(BleakClientDotNet, self).__init__(address, loop, **kwargs)

    # Backend specific. Python.NET objects.
    self._device_info = None
    self._requester = None
    self._bridge = Bridge()
    self._callbacks = {}
# Buggy code
async def disconnect(self) -> bool:
    logger.debug("Disconnecting from BLE device...")
    # Remove notifications
    # TODO: Make sure all notifications are removed prior to Dispose.
    # Dispose all components that we have requested and created.
    for service_uuid, service in self.services.items():
        service.Dispose()
    self.services = None
    self._requester.Dispose()
    self._requester = None

    return not await self.is_connected()


# Traceback (bleak.exc.BleakError)
Traceback (most recent call last):
File "/home/jonas/Schreibtisch/TMRTFlib.py", line 572, in <module>
loop.run_until_complete(connect_device_bleak(address, loop))
File "/usr/lib/python3.6/asyncio/base_events.py", line 473, in run_until_complete
return future.result()
File "/home/jonas/Schreibtisch/TMRTFlib.py", line 552, in connect_device_bleak
async with BleakClient(address, loop=loop) as client:
File "/home/jonas/.local/lib/python3.6/site-packages/bleak/backends/client.py", line 35, in __aenter__
await self.connect()
File "/home/jonas/.local/lib/python3.6/site-packages/bleak/backends/bluezdbus/client.py", line 76, in connect
raise BleakError(str(e))
bleak.exc.BleakError: org.freedesktop.DBus.Error.UnknownObject: Method "Connect" with signature "" on interface "org.bluez.Device1" doesn't exist

# Fixed code
async def disconnect(self) -> bool:
    logger.debug("Disconnecting from BLE device...")
    # Remove notifications
    # TODO: Make sure all notifications are removed prior to Dispose.
    # Dispose all components that we have requested and created.
    for service in self.services:
        # for characteristic in service.characteristics:
        #     for descriptor in characteristic.descriptors:
        #         descriptor.obj.Dispose()
        #     characteristic.obj.Dispose()
        service.obj.Dispose()
    self.services = BleakGATTServiceCollection()
    self._requester.Dispose()
    self._requester = None

    return not await self.is_connected()
# Buggy code
async def read_gatt_char(self, _uuid: str) -> bytearray:
    """Perform read operation on the specified characteristic.

    Args:
        _uuid (str or UUID): The uuid of the characteristics to start notification on.

    Returns:
        (bytearray) The read data.

    """
    characteristic = self.characteristics.get(str(_uuid))
    if not characteristic:
        raise BleakError("Characteristic {0} was not found!".format(_uuid))

    read_results = await wrap_Task(
        self._bridge.ReadCharacteristicValueAsync(characteristic), loop=self.loop
    )
    status, value = read_results.Item1, bytearray(read_results.Item2)
    if status == GattCommunicationStatus.Success:
        logger.debug("Read Characteristic {0} : {1}".format(_uuid, value))
    else:
        raise BleakError(
            "Could not read characteristic value for {0}: {1}",
            characteristic.Uuid.ToString(),
            status,
        )

    return value


# Traceback (bleak.exc.BleakError)
Traceback (most recent call last):
File "/home/jonas/Schreibtisch/TMRTFlib.py", line 572, in <module>
loop.run_until_complete(connect_device_bleak(address, loop))
File "/usr/lib/python3.6/asyncio/base_events.py", line 473, in run_until_complete
return future.result()
File "/home/jonas/Schreibtisch/TMRTFlib.py", line 552, in connect_device_bleak
async with BleakClient(address, loop=loop) as client:
File "/home/jonas/.local/lib/python3.6/site-packages/bleak/backends/client.py", line 35, in __aenter__
await self.connect()
File "/home/jonas/.local/lib/python3.6/site-packages/bleak/backends/bluezdbus/client.py", line 76, in connect
raise BleakError(str(e))
bleak.exc.BleakError: org.freedesktop.DBus.Error.UnknownObject: Method "Connect" with signature "" on interface "org.bluez.Device1" doesn't exist

# Fixed code
async def read_gatt_char(self, _uuid: str) -> bytearray:
    """Perform read operation on the specified characteristic.

    Args:
        _uuid (str or UUID): The uuid of the characteristics to read from.

    Returns:
        (bytearray) The read data.

    """
    characteristic = self.services.get_characteristic(str(_uuid))
    if not characteristic:
        raise BleakError("Characteristic {0} was not found!".format(_uuid))

    read_result = await wrap_IAsyncOperation(
        IAsyncOperation[GattReadResult](
            characteristic.obj.ReadValueAsync(BluetoothCacheMode.Uncached)
        ),
        return_type=GattReadResult,
        loop=self.loop,
    )
    if read_result.Status == GattCommunicationStatus.Success:
        reader = DataReader.FromBuffer(IBuffer(read_result.Value))
        # TODO: Find better way of initializing this...
        output = Array[Byte]([0] * reader.UnconsumedBufferLength)
        reader.ReadBytes(output)
        value = bytearray(output)
        logger.debug("Read Characteristic {0} : {1}".format(_uuid, value))
    else:
        raise BleakError(
            "Could not read characteristic value for {0}: {1}".format(
                characteristic.uuid, read_result.Status
            )
        )
    return value
# Buggy code
async def start_notify(
    self, _uuid: str, callback: Callable[[str, Any], Any], **kwargs
) -> None:
    """Activate notifications on a characteristic.

    Callbacks must accept two inputs. The first will be a uuid string
    object and the second will be a bytearray.

    .. code-block:: python

        def callback(sender, data):
            print(f"{sender}: {data}")
        client.start_notify(char_uuid, callback)

    Args:
        _uuid (str or UUID): The uuid of the characteristics to start notification on.
        callback (function): The function to be called on notification.

    """
    characteristic = self.characteristics.get(str(_uuid))

    if self._notification_callbacks.get(str(_uuid)):
        await self.stop_notify(_uuid)

    dotnet_callback = TypedEventHandler[GattCharacteristic, Array[Byte]](
        _notification_wrapper(callback)
    )
    status = await wrap_Task(
        self._bridge.StartNotify(characteristic, dotnet_callback), loop=self.loop
    )
    if status != GattCommunicationStatus.Success:
        raise BleakError(
            "Could not start notify on {0}: {1}",
            characteristic.Uuid.ToString(),
            status,
        )


# Traceback (bleak.exc.BleakError)
Traceback (most recent call last):
File "/home/jonas/Schreibtisch/TMRTFlib.py", line 572, in <module>
loop.run_until_complete(connect_device_bleak(address, loop))
File "/usr/lib/python3.6/asyncio/base_events.py", line 473, in run_until_complete
return future.result()
File "/home/jonas/Schreibtisch/TMRTFlib.py", line 552, in connect_device_bleak
async with BleakClient(address, loop=loop) as client:
File "/home/jonas/.local/lib/python3.6/site-packages/bleak/backends/client.py", line 35, in __aenter__
await self.connect()
File "/home/jonas/.local/lib/python3.6/site-packages/bleak/backends/bluezdbus/client.py", line 76, in connect
raise BleakError(str(e))
bleak.exc.BleakError: org.freedesktop.DBus.Error.UnknownObject: Method "Connect" with signature "" on interface "org.bluez.Device1" doesn't exist

# Fixed code
async def start_notify(
    self, _uuid: str, callback: Callable[[str, Any], Any], **kwargs
) -> None:
    """Activate notifications on a characteristic.

    Callbacks must accept two inputs. The first will be a uuid string
    object and the second will be a bytearray.

    .. code-block:: python

        def callback(sender, data):
            print(f"{sender}: {data}")
        client.start_notify(char_uuid, callback)

    Args:
        _uuid (str or UUID): The uuid of the characteristics to start notification on.
        callback (function): The function to be called on notification.

    """
    characteristic = self.services.get_characteristic(str(_uuid))

    if self._notification_callbacks.get(str(_uuid)):
        await self.stop_notify(_uuid)

    status = await self._start_notify(characteristic.obj, callback)

    if status != GattCommunicationStatus.Success:
        raise BleakError(
            "Could not start notify on {0}: {1}".format(characteristic.uuid, status)
        )
# Buggy code
async def stop_notify(self, _uuid: str) -> None:
    """Deactivate notification on a specified characteristic.

    Args:
        _uuid: The characteristic to stop notifying on.

    """
    characteristic = self.characteristics.get(str(_uuid))
    status = await wrap_Task(self._bridge.StopNotify(characteristic), loop=self.loop)
    if status != GattCommunicationStatus.Success:
        raise BleakError(
            "Could not start notify on {0}: {1}",
            characteristic.Uuid.ToString(),
            status,
        )


# Traceback (bleak.exc.BleakError)
Traceback (most recent call last):
File "/home/jonas/Schreibtisch/TMRTFlib.py", line 572, in <module>
loop.run_until_complete(connect_device_bleak(address, loop))
File "/usr/lib/python3.6/asyncio/base_events.py", line 473, in run_until_complete
return future.result()
File "/home/jonas/Schreibtisch/TMRTFlib.py", line 552, in connect_device_bleak
async with BleakClient(address, loop=loop) as client:
File "/home/jonas/.local/lib/python3.6/site-packages/bleak/backends/client.py", line 35, in __aenter__
await self.connect()
File "/home/jonas/.local/lib/python3.6/site-packages/bleak/backends/bluezdbus/client.py", line 76, in connect
raise BleakError(str(e))
bleak.exc.BleakError: org.freedesktop.DBus.Error.UnknownObject: Method "Connect" with signature "" on interface "org.bluez.Device1" doesn't exist

# Fixed code
async def stop_notify(self, _uuid: str) -> None:
    """Deactivate notification on a specified characteristic.

    Args:
        _uuid: The characteristic to stop notifying on.

    """
    characteristic = self.services.get_characteristic(str(_uuid))

    status = await wrap_IAsyncOperation(
        IAsyncOperation[GattCommunicationStatus](
            characteristic.obj.WriteClientCharacteristicConfigurationDescriptorAsync(
                getattr(GattClientCharacteristicConfigurationDescriptorValue, "None")
            )
        ),
        return_type=GattCommunicationStatus,
        loop=self.loop,
    )

    if status != GattCommunicationStatus.Success:
        raise BleakError(
            "Could not start notify on {0}: {1}".format(characteristic.uuid, status)
        )
    else:
        callback = self._callbacks.pop(characteristic.uuid)
        self._bridge.RemoveValueChangedCallback(characteristic.obj, callback)
# Buggy code
def _notification_wrapper(func: Callable):
    @wraps(func)
    def dotnet_notification_parser(sender: Any, data: Any):
        # Return only the UUID string representation as sender.
        # Also do a conversion from System.Bytes[] to bytearray.
        return func(sender.Uuid.ToString(), bytearray(data))

    return dotnet_notification_parser


# Traceback (bleak.exc.BleakError)
Traceback (most recent call last):
File "/home/jonas/Schreibtisch/TMRTFlib.py", line 572, in <module>
loop.run_until_complete(connect_device_bleak(address, loop))
File "/usr/lib/python3.6/asyncio/base_events.py", line 473, in run_until_complete
return future.result()
File "/home/jonas/Schreibtisch/TMRTFlib.py", line 552, in connect_device_bleak
async with BleakClient(address, loop=loop) as client:
File "/home/jonas/.local/lib/python3.6/site-packages/bleak/backends/client.py", line 35, in __aenter__
await self.connect()
File "/home/jonas/.local/lib/python3.6/site-packages/bleak/backends/bluezdbus/client.py", line 76, in connect
raise BleakError(str(e))
bleak.exc.BleakError: org.freedesktop.DBus.Error.UnknownObject: Method "Connect" with signature "" on interface "org.bluez.Device1" doesn't exist

# Fixed code
def _notification_wrapper(func: Callable):
    @wraps(func)
    def dotnet_notification_parser(sender: Any, args: Any):
        # Return only the UUID string representation as sender.
        # Also do a conversion from System.Bytes[] to bytearray.
        reader = DataReader.FromBuffer(args.CharacteristicValue)
        output = Array[Byte]([0] * reader.UnconsumedBufferLength)
        reader.ReadBytes(output)

        return func(sender.Uuid.ToString(), bytearray(output))

    return dotnet_notification_parser
# Buggy code
def dotnet_notification_parser(sender: Any, data: Any):
    # Return only the UUID string representation as sender.
    # Also do a conversion from System.Bytes[] to bytearray.
    return func(sender.Uuid.ToString(), bytearray(data))


# Traceback (bleak.exc.BleakError)
Traceback (most recent call last):
File "/home/jonas/Schreibtisch/TMRTFlib.py", line 572, in <module>
loop.run_until_complete(connect_device_bleak(address, loop))
File "/usr/lib/python3.6/asyncio/base_events.py", line 473, in run_until_complete
return future.result()
File "/home/jonas/Schreibtisch/TMRTFlib.py", line 552, in connect_device_bleak
async with BleakClient(address, loop=loop) as client:
File "/home/jonas/.local/lib/python3.6/site-packages/bleak/backends/client.py", line 35, in __aenter__
await self.connect()
File "/home/jonas/.local/lib/python3.6/site-packages/bleak/backends/bluezdbus/client.py", line 76, in connect
raise BleakError(str(e))
bleak.exc.BleakError: org.freedesktop.DBus.Error.UnknownObject: Method "Connect" with signature "" on interface "org.bluez.Device1" doesn't exist

# Fixed code
def dotnet_notification_parser(sender: Any, args: Any):
    # Return only the UUID string representation as sender.
    # Also do a conversion from System.Bytes[] to bytearray.
    reader = DataReader.FromBuffer(args.CharacteristicValue)
    output = Array[Byte]([0] * reader.UnconsumedBufferLength)
    reader.ReadBytes(output)

    return func(sender.Uuid.ToString(), bytearray(output))
# Buggy code
async def wrap_Task(task, loop):
    """Enables await on .NET Task using asyncio.Event and a lambda callback.

    Args:
        task (System.Threading.Tasks.Task): .NET async task object
        to await upon.
        loop (Event Loop): The event loop to await on the Task in.

    Returns:
        The results of the the .NET Task.

    """
    done = asyncio.Event()
    # Register Action<Task> callback that triggers the above asyncio.Event.
    task.ContinueWith(Action[Task](lambda x: loop.call_soon_threadsafe(done.set)))
    # Wait for callback.
    await done.wait()
    # TODO: Handle IsCancelled.
    if task.IsFaulted:
        # Exception occurred. Wrap it in BleakDotNetTaskError
        # to make it catchable.
        raise BleakDotNetTaskError(task.Exception.ToString())

    return task.Result


# Traceback (bleak.exc.BleakError)
Traceback (most recent call last):
File "/home/jonas/Schreibtisch/TMRTFlib.py", line 572, in <module>
loop.run_until_complete(connect_device_bleak(address, loop))
File "/usr/lib/python3.6/asyncio/base_events.py", line 473, in run_until_complete
return future.result()
File "/home/jonas/Schreibtisch/TMRTFlib.py", line 552, in connect_device_bleak
async with BleakClient(address, loop=loop) as client:
File "/home/jonas/.local/lib/python3.6/site-packages/bleak/backends/client.py", line 35, in __aenter__
await self.connect()
File "/home/jonas/.local/lib/python3.6/site-packages/bleak/backends/bluezdbus/client.py", line 76, in connect
raise BleakError(str(e))
bleak.exc.BleakError: org.freedesktop.DBus.Error.UnknownObject: Method "Connect" with signature "" on interface "org.bluez.Device1" doesn't exist

# Fixed code
async def wrap_Task(task, loop):
    """Enables await on .NET Task using asyncio.Event and a lambda callback.

    Args:
        task (System.Threading.Tasks.Task): .NET async task object
        to await upon.
        loop (Event Loop): The event loop to await on the Task in.

    Returns:
        The results of the the .NET Task.

    """
    done = asyncio.Event()
    # Register Action<Task> callback that triggers the above asyncio.Event.
    task.ContinueWith(Action[Task]())
    # Wait for callback.
    await done.wait()
    # TODO: Handle IsCancelled.
    if task.IsFaulted:
        # Exception occurred. Wrap it in BleakDotNetTaskError
        # to make it catchable.
        raise BleakDotNetTaskError(task.Exception.ToString())

    return task.Result
# Buggy code
def __init__(self, task, loop):
    self._loop = loop
    self.task = task
    self.done = asyncio.Event()


# Traceback (bleak.exc.BleakError)
Traceback (most recent call last):
File "/home/jonas/Schreibtisch/TMRTFlib.py", line 572, in <module>
loop.run_until_complete(connect_device_bleak(address, loop))
File "/usr/lib/python3.6/asyncio/base_events.py", line 473, in run_until_complete
return future.result()
File "/home/jonas/Schreibtisch/TMRTFlib.py", line 552, in connect_device_bleak
async with BleakClient(address, loop=loop) as client:
File "/home/jonas/.local/lib/python3.6/site-packages/bleak/backends/client.py", line 35, in __aenter__
await self.connect()
File "/home/jonas/.local/lib/python3.6/site-packages/bleak/backends/bluezdbus/client.py", line 76, in connect
raise BleakError(str(e))
bleak.exc.BleakError: org.freedesktop.DBus.Error.UnknownObject: Method "Connect" with signature "" on interface "org.bluez.Device1" doesn't exist

# Fixed code
def __init__(self, operation, return_type, loop):
    self.operation = IAsyncOperation[return_type](operation)
    self.done = asyncio.Event()
    self.return_type = return_type
    self._loop = loop
# Buggy code
def __await__(self):
    def callback(task):
        self._loop.call_soon_threadsafe(self.done.set)

    self.task.ContinueWith(Action[Task](callback))
    yield from self.done.wait()
    return self


# Traceback (bleak.exc.BleakError)
Traceback (most recent call last):
File "/home/jonas/Schreibtisch/TMRTFlib.py", line 572, in <module>
loop.run_until_complete(connect_device_bleak(address, loop))
File "/usr/lib/python3.6/asyncio/base_events.py", line 473, in run_until_complete
return future.result()
File "/home/jonas/Schreibtisch/TMRTFlib.py", line 552, in connect_device_bleak
async with BleakClient(address, loop=loop) as client:
File "/home/jonas/.local/lib/python3.6/site-packages/bleak/backends/client.py", line 35, in __aenter__
await self.connect()
File "/home/jonas/.local/lib/python3.6/site-packages/bleak/backends/bluezdbus/client.py", line 76, in connect
raise BleakError(str(e))
bleak.exc.BleakError: org.freedesktop.DBus.Error.UnknownObject: Method "Connect" with signature "" on interface "org.bluez.Device1" doesn't exist

# Fixed code
def __await__(self):
    # Register AsyncOperationCompletedHandler callback that triggers the above asyncio.Event.
    self.operation.Completed = AsyncOperationCompletedHandler[self.return_type](
        lambda x, y: self._loop.call_soon_threadsafe(self.done.set)
    )
    yield from self.done.wait()
    return self
# Buggy code
def result(self):
    # TODO: Handle IsCancelled.
    if self.task.IsFaulted:
        # Exception occurred. Wrap it in BleakDotNetTaskError
        # to make it catchable.
        raise BleakDotNetTaskError(self.task.Exception.ToString())

    return self.task.Result


# Traceback (bleak.exc.BleakError)
Traceback (most recent call last):
File "/home/jonas/Schreibtisch/TMRTFlib.py", line 572, in <module>
loop.run_until_complete(connect_device_bleak(address, loop))
File "/usr/lib/python3.6/asyncio/base_events.py", line 473, in run_until_complete
return future.result()
File "/home/jonas/Schreibtisch/TMRTFlib.py", line 552, in connect_device_bleak
async with BleakClient(address, loop=loop) as client:
File "/home/jonas/.local/lib/python3.6/site-packages/bleak/backends/client.py", line 35, in __aenter__
await self.connect()
File "/home/jonas/.local/lib/python3.6/site-packages/bleak/backends/bluezdbus/client.py", line 76, in connect
raise BleakError(str(e))
bleak.exc.BleakError: org.freedesktop.DBus.Error.UnknownObject: Method "Connect" with signature "" on interface "org.bluez.Device1" doesn't exist

# Fixed code
def result(self):
    if self.operation.Status == AsyncStatus.Completed:
        return self.operation.GetResults()
    elif self.operation.Status == AsyncStatus.Error:
        # Exception occurred. Wrap it in BleakDotNetTaskError
        # to make it catchable.
        raise BleakDotNetTaskError(self.operation.ErrorCode.ToString())
    else:
        # TODO: Handle IsCancelled.
        raise BleakDotNetTaskError(
            "IAsyncOperation Status: {0}".format(self.operation.Status)
        )
# Buggy code
def _connected_by_alternating_paths(G, matching, targets):
    """Returns the set of vertices that are connected to one of the target
    vertices by an alternating path in `G`.

    An *alternating path* is a path in which every other edge is in the
    specified maximum matching (and the remaining edges in the path are not in
    the matching). An alternating path may have matched edges in the even
    positions or in the odd positions, as long as the edges alternate between
    'matched' and 'unmatched'.

    `G` is an undirected bipartite NetworkX graph.

    `matching` is a dictionary representing a maximum matching in `G`, as
    returned by, for example, :func:`maximum_matching`.

    `targets` is a set of vertices.

    """
    # TODO This can be parallelized.
    return {v for v in G if _is_connected_by_alternating_path(G, v, matching, targets)}


# Traceback (AssertionError)
$ python2.7 vertex_cover.py
Using version 1.11
Edges: [(0, 3), (1, 3), (1, 4), (2, 3)]
Matching: {0: 3, 1: 4, 3: 0, 4: 1}
Vertex cover: set([0, 1])
Traceback (most recent call last):
File "vertex_cover.py", line 16, in <module>
assert u in vertex_cover or v in vertex_cover
AssertionError
$ python3.6 vertex_cover.py
Using version 1.11
Edges: [(0, 3), (3, 1), (3, 2), (1, 4)]
Matching: {0: 3, 1: 4, 3: 0, 4: 1}
Vertex cover: {0, 1}
Traceback (most recent call last):
File "vertex_cover.py", line 16, in <module>
assert u in vertex_cover or v in vertex_cover
AssertionError

# Fixed code
def _connected_by_alternating_paths(G, matching, targets):
    """Returns the set of vertices that are connected to one of the target
    vertices by an alternating path in `G` or are themselves a target.

    An *alternating path* is a path in which every other edge is in the
    specified maximum matching (and the remaining edges in the path are not in
    the matching). An alternating path may have matched edges in the even
    positions or in the odd positions, as long as the edges alternate between
    'matched' and 'unmatched'.

    `G` is an undirected bipartite NetworkX graph.

    `matching` is a dictionary representing a maximum matching in `G`, as
    returned by, for example, :func:`maximum_matching`.

    `targets` is a set of vertices.

    """
    # Get the set of matched edges and the set of unmatched edges. Only include
    # one version of each undirected edge (for example, include edge (1, 2) but
    # not edge (2, 1)). Using frozensets as an intermediary step we do not
    # require nodes to be orderable.
    edge_sets = {frozenset((u, v)) for u, v in matching.items()}
    matched_edges = {tuple(edge) for edge in edge_sets}
    unmatched_edges = {
        (u, v) for (u, v) in G.edges() if frozenset((u, v)) not in edge_sets
    }

    return {
        v
        for v in G
        if v in targets
        or _is_connected_by_alternating_path(
            G, v, matched_edges, unmatched_edges, targets
        )
    }
# Buggy code
def __init__(self, *args, **kwargs):
    self.application = kwargs.pop("application", None)
    super(ApplicationForm, self).__init__(*args, **kwargs)
    for field in self.application.system_app_type.enforced_data:
        # preserve existing value for disabled fields
        self[field].data = self[field].object_data


# Traceback (AttributeError)
Traceback (most recent call last):
File "/usr/home/indicoadm/indicov2/.indicov2/lib/python2.7/site-packages/indico/legacy/webinterface/rh/base.py", line 493, in process
profile_name, res = self._do_process(profile)
File "/usr/home/indicoadm/indicov2/.indicov2/lib/python2.7/site-packages/indico/legacy/webinterface/rh/base.py", line 464, in _do_process
res = self._process()
File "/usr/home/indicoadm/indicov2/.indicov2/lib/python2.7/site-packages/indico/modules/oauth/controllers.py", line 132, in _process
form = ApplicationForm(obj=FormDefaults(is_enabled=True))
File "/usr/home/indicoadm/indicov2/.indicov2/lib/python2.7/site-packages/indico/web/forms/base.py", line 70, in __call__
return super(IndicoFormMeta, cls).__call__(*args, **kwargs)
File "/usr/home/indicoadm/indicov2/.indicov2/lib/python2.7/site-packages/wtforms/form.py", line 212, in __call__
return type.__call__(cls, *args, **kwargs)
File "/usr/home/indicoadm/indicov2/.indicov2/lib/python2.7/site-packages/indico/modules/oauth/forms.py", line 63, in __init__
for field in self.application.system_app_type.enforced_data:
AttributeError: 'NoneType' object has no attribute 'system_app_type'

# Fixed code
def __init__(self, *args, **kwargs):
    self.application = kwargs.pop("application", None)
    super(ApplicationForm, self).__init__(*args, **kwargs)
    if self.application is not None:
        for field in self.application.system_app_type.enforced_data:
            # preserve existing value for disabled fields
            self[field].data = self[field].object_data