gurudesh/pytracebugs huggingface dataset:
# Buggy code
def persistence_image_amplitudes(
    diagrams,
    sampling,
    step_size,
    weight_function=lambda x: x,
    sigma=1.0,
    p=2.0,
    **kwargs,
):
    persistence_image = persistence_images(
        diagrams, sampling, step_size, weight_function, sigma
    )
    return np.linalg.norm(persistence_image, axis=(1, 2), ord=p)


# Traceback (TypeError)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-5e233492b878> in <module>
----> 1 Amplitude(metric="persistence_image").fit_transform(Xd)

~\Workspace\giotto-tda_ulupo\gtda\utils\_docs.py in fit_transform_wrapper(*args, **kwargs)
104         @wraps(original_fit_transform)
105         def fit_transform_wrapper(*args, **kwargs):
--> 106             return original_fit_transform(*args, **kwargs)
107         fit_transform_wrapper.__doc__ = \
108             make_fit_transform_docs(fit_docs, transform_docs)

~\Anaconda3\envs\gtda-ulupo-py38\lib\site-packages\sklearn\base.py in fit_transform(self, X, y, **fit_params)
688         if y is None:
689             # fit method of arity 1 (unsupervised transformation)
--> 690             return self.fit(X, **fit_params).transform(X)
691         else:
692             # fit method of arity 2 (supervised transformation)

~\Workspace\giotto-tda_ulupo\gtda\diagrams\features.py in fit(self, X, y)
273         if self.metric == 'persistence_image':
274             self.effective_metric_params_['weights'] = \
--> 275                 _calculate_weights(X, **self.effective_metric_params_)
276
277         return self

TypeError: _calculate_weights() missing 1 required positional argument: 'weight_function'

# Fixed code
def persistence_image_amplitudes(
    diagrams,
    sampling,
    step_size,
    sigma=0.1,
    weight_function=np.ones_like,
    p=2.0,
    **kwargs,
):
    # For persistence images, `sampling` is a tall matrix with two columns
    # (the first for birth and the second for persistence), and `step_size` is
    # a 2d array
    weights = weight_function(sampling[:, 1])
    step_sizes_factor = np.product(step_size) ** (1 / p)
    # WARNING: `persistence_images` modifies `diagrams` in place
    persistence_images_ = persistence_images(
        diagrams, sampling, step_size, sigma, weights
    ).reshape(len(diagrams), -1)
    amplitudes = np.linalg.norm(persistence_images_, axis=1, ord=p)
    amplitudes *= step_sizes_factor
    return amplitudes
# Buggy code
def silhouette_amplitudes(diagrams, sampling, step_size, power=2.0, p=2.0, **kwargs):
    sht = silhouettes(diagrams, sampling, power)
    return (step_size ** (1 / p)) * np.linalg.norm(sht, axis=1, ord=p)


# Traceback (TypeError)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-5e233492b878> in <module>
----> 1 Amplitude(metric="persistence_image").fit_transform(Xd)

~\Workspace\giotto-tda_ulupo\gtda\utils\_docs.py in fit_transform_wrapper(*args, **kwargs)
104         @wraps(original_fit_transform)
105         def fit_transform_wrapper(*args, **kwargs):
--> 106             return original_fit_transform(*args, **kwargs)
107         fit_transform_wrapper.__doc__ = \
108             make_fit_transform_docs(fit_docs, transform_docs)

~\Anaconda3\envs\gtda-ulupo-py38\lib\site-packages\sklearn\base.py in fit_transform(self, X, y, **fit_params)
688         if y is None:
689             # fit method of arity 1 (unsupervised transformation)
--> 690             return self.fit(X, **fit_params).transform(X)
691         else:
692             # fit method of arity 2 (supervised transformation)

~\Workspace\giotto-tda_ulupo\gtda\diagrams\features.py in fit(self, X, y)
273         if self.metric == 'persistence_image':
274             self.effective_metric_params_['weights'] = \
--> 275                 _calculate_weights(X, **self.effective_metric_params_)
276
277         return self

TypeError: _calculate_weights() missing 1 required positional argument: 'weight_function'

# Fixed code
def silhouette_amplitudes(diagrams, sampling, step_size, power=1.0, p=2.0, **kwargs):
    step_size_factor = step_size ** (1 / p)
    silhouettes_ = silhouettes(diagrams, sampling, power)
    amplitudes = np.linalg.norm(silhouettes_, axis=1, ord=p)
    amplitudes *= step_size_factor
    return amplitudes
# Buggy code
def _sample_image(image, sampled_diag):
    # NOTE: Modifies `image` in-place
    unique, counts = np.unique(sampled_diag, axis=0, return_counts=True)
    unique = tuple(tuple(row) for row in unique.astype(np.int).T)
    image[unique] = counts


# Traceback (TypeError)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-5e233492b878> in <module>
----> 1 Amplitude(metric="persistence_image").fit_transform(Xd)

~\Workspace\giotto-tda_ulupo\gtda\utils\_docs.py in fit_transform_wrapper(*args, **kwargs)
104         @wraps(original_fit_transform)
105         def fit_transform_wrapper(*args, **kwargs):
--> 106             return original_fit_transform(*args, **kwargs)
107         fit_transform_wrapper.__doc__ = \
108             make_fit_transform_docs(fit_docs, transform_docs)

~\Anaconda3\envs\gtda-ulupo-py38\lib\site-packages\sklearn\base.py in fit_transform(self, X, y, **fit_params)
688         if y is None:
689             # fit method of arity 1 (unsupervised transformation)
--> 690             return self.fit(X, **fit_params).transform(X)
691         else:
692             # fit method of arity 2 (supervised transformation)

~\Workspace\giotto-tda_ulupo\gtda\diagrams\features.py in fit(self, X, y)
273         if self.metric == 'persistence_image':
274             self.effective_metric_params_['weights'] = \
--> 275                 _calculate_weights(X, **self.effective_metric_params_)
276
277         return self

TypeError: _calculate_weights() missing 1 required positional argument: 'weight_function'

# Fixed code
def _sample_image(image, diagram_pixel_coords):
    # WARNING: Modifies `image` in-place
    unique, counts = np.unique(diagram_pixel_coords, axis=0, return_counts=True)
    unique = tuple(tuple(row) for row in unique.astype(np.int).T)
    image[unique] = counts
# Buggy code
def __init__(self, metric="landscape", metric_params=None, order=2.0, n_jobs=None):
    self.metric = metric
    self.metric_params = metric_params
    self.order = order
    self.n_jobs = n_jobs


# Traceback (TypeError)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-5e233492b878> in <module>
----> 1 Amplitude(metric="persistence_image").fit_transform(Xd)

~\Workspace\giotto-tda_ulupo\gtda\utils\_docs.py in fit_transform_wrapper(*args, **kwargs)
104         @wraps(original_fit_transform)
105         def fit_transform_wrapper(*args, **kwargs):
--> 106             return original_fit_transform(*args, **kwargs)
107         fit_transform_wrapper.__doc__ = \
108             make_fit_transform_docs(fit_docs, transform_docs)

~\Anaconda3\envs\gtda-ulupo-py38\lib\site-packages\sklearn\base.py in fit_transform(self, X, y, **fit_params)
688         if y is None:
689             # fit method of arity 1 (unsupervised transformation)
--> 690             return self.fit(X, **fit_params).transform(X)
691         else:
692             # fit method of arity 2 (supervised transformation)

~\Workspace\giotto-tda_ulupo\gtda\diagrams\features.py in fit(self, X, y)
273         if self.metric == 'persistence_image':
274             self.effective_metric_params_['weights'] = \
--> 275                 _calculate_weights(X, **self.effective_metric_params_)
276
277         return self

TypeError: _calculate_weights() missing 1 required positional argument: 'weight_function'

# Fixed code
def __init__(self, metric="landscape", metric_params=None, order=None, n_jobs=None):
    self.metric = metric
    self.metric_params = metric_params
    self.order = order
    self.n_jobs = n_jobs
# Buggy code
def inverse_transform(self, X):
    """Scale back the data to the original representation. Multiplies by
    the scale found in :meth:`fit`.

    Parameters
    ----------
    X : ndarray of shape (n_samples, n_features, 3)
        Data to apply the inverse transform to, c.f. :meth:`transform`.

    Returns
    -------
    Xs : ndarray of shape (n_samples, n_features, 3)
        Rescaled diagrams.

    """
    check_is_fitted(self)

    Xs = check_diagrams(X)
    Xs[:, :, :2] *= self.scale_
    return Xs


# Traceback (TypeError)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-5e233492b878> in <module>
----> 1 Amplitude(metric="persistence_image").fit_transform(Xd)

~\Workspace\giotto-tda_ulupo\gtda\utils\_docs.py in fit_transform_wrapper(*args, **kwargs)
104         @wraps(original_fit_transform)
105         def fit_transform_wrapper(*args, **kwargs):
--> 106             return original_fit_transform(*args, **kwargs)
107         fit_transform_wrapper.__doc__ = \
108             make_fit_transform_docs(fit_docs, transform_docs)

~\Anaconda3\envs\gtda-ulupo-py38\lib\site-packages\sklearn\base.py in fit_transform(self, X, y, **fit_params)
688         if y is None:
689             # fit method of arity 1 (unsupervised transformation)
--> 690             return self.fit(X, **fit_params).transform(X)
691         else:
692             # fit method of arity 2 (supervised transformation)

~\Workspace\giotto-tda_ulupo\gtda\diagrams\features.py in fit(self, X, y)
273         if self.metric == 'persistence_image':
274             self.effective_metric_params_['weights'] = \
--> 275                 _calculate_weights(X, **self.effective_metric_params_)
276
277         return self

TypeError: _calculate_weights() missing 1 required positional argument: 'weight_function'

# Fixed code
def inverse_transform(self, X):
    """Scale back the data to the original representation. Multiplies by
    the scale found in :meth:`fit`.

    Parameters
    ----------
    X : ndarray of shape (n_samples, n_features, 3)
        Data to apply the inverse transform to, c.f. :meth:`transform`.

    Returns
    -------
    Xs : ndarray of shape (n_samples, n_features, 3)
        Rescaled diagrams.

    """
    check_is_fitted(self)

    Xs = check_diagrams(X, copy=True)
    Xs[:, :, :2] *= self.scale_
    return Xs
# Buggy code
def __init__(self, sigma=1.0, n_bins=100, n_jobs=None):
    self.sigma = sigma
    self.n_bins = n_bins
    self.n_jobs = n_jobs


# Traceback (TypeError)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-5e233492b878> in <module>
----> 1 Amplitude(metric="persistence_image").fit_transform(Xd)

~\Workspace\giotto-tda_ulupo\gtda\utils\_docs.py in fit_transform_wrapper(*args, **kwargs)
104         @wraps(original_fit_transform)
105         def fit_transform_wrapper(*args, **kwargs):
--> 106             return original_fit_transform(*args, **kwargs)
107         fit_transform_wrapper.__doc__ = \
108             make_fit_transform_docs(fit_docs, transform_docs)

~\Anaconda3\envs\gtda-ulupo-py38\lib\site-packages\sklearn\base.py in fit_transform(self, X, y, **fit_params)
688         if y is None:
689             # fit method of arity 1 (unsupervised transformation)
--> 690             return self.fit(X, **fit_params).transform(X)
691         else:
692             # fit method of arity 2 (supervised transformation)

~\Workspace\giotto-tda_ulupo\gtda\diagrams\features.py in fit(self, X, y)
273         if self.metric == 'persistence_image':
274             self.effective_metric_params_['weights'] = \
--> 275                 _calculate_weights(X, **self.effective_metric_params_)
276
277         return self

TypeError: _calculate_weights() missing 1 required positional argument: 'weight_function'

# Fixed code
def __init__(self, sigma=0.1, n_bins=100, n_jobs=None):
    self.sigma = sigma
    self.n_bins = n_bins
    self.n_jobs = n_jobs
# Buggy code
def __init__(self, sigma=1.0, n_bins=100, weight_function=None, n_jobs=None):
    self.sigma = sigma
    self.n_bins = n_bins
    self.weight_function = weight_function
    self.n_jobs = n_jobs


# Traceback (TypeError)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-5e233492b878> in <module>
----> 1 Amplitude(metric="persistence_image").fit_transform(Xd)

~\Workspace\giotto-tda_ulupo\gtda\utils\_docs.py in fit_transform_wrapper(*args, **kwargs)
104         @wraps(original_fit_transform)
105         def fit_transform_wrapper(*args, **kwargs):
--> 106             return original_fit_transform(*args, **kwargs)
107         fit_transform_wrapper.__doc__ = \
108             make_fit_transform_docs(fit_docs, transform_docs)

~\Anaconda3\envs\gtda-ulupo-py38\lib\site-packages\sklearn\base.py in fit_transform(self, X, y, **fit_params)
688         if y is None:
689             # fit method of arity 1 (unsupervised transformation)
--> 690             return self.fit(X, **fit_params).transform(X)
691         else:
692             # fit method of arity 2 (supervised transformation)

~\Workspace\giotto-tda_ulupo\gtda\diagrams\features.py in fit(self, X, y)
273         if self.metric == 'persistence_image':
274             self.effective_metric_params_['weights'] = \
--> 275                 _calculate_weights(X, **self.effective_metric_params_)
276
277         return self

TypeError: _calculate_weights() missing 1 required positional argument: 'weight_function'

# Fixed code
def __init__(self, sigma=0.1, n_bins=100, weight_function=None, n_jobs=None):
    self.sigma = sigma
    self.n_bins = n_bins
    self.weight_function = weight_function
    self.n_jobs = n_jobs
# Buggy code
def __init__(self):
    logger.debug("A call from A.B.__init__")
    self.__test()


# Traceback (RecursionError)
File "/home/ash/.local/share/EDMarketConnector/plugins/edrodent/load.py", line 38, in ready_to_rat
logger.debug("ready_to_rat: %r %r %r %r %r", self.open, self.low_fuel, self.hud_in_analysis_mode, self.has_fuel_transfer_limpet_controller, self.limpets)
File "/usr/local/lib/python3.7/logging/__init__.py", line 1366, in debug
self._log(DEBUG, msg, args, **kwargs)
File "/usr/local/lib/python3.7/logging/__init__.py", line 1514, in _log
self.handle(record)
File "/usr/local/lib/python3.7/logging/__init__.py", line 1523, in handle
if (not self.disabled) and self.filter(record):
File "/usr/local/lib/python3.7/logging/__init__.py", line 751, in filter
result = f.filter(record)
File "/home/ash/src/EDMarketConnector/EDMCLogging.py", line 255, in filter
(class_name, qualname, module_name) = self.caller_attributes(module_name=getattr(record, 'module'))
File "/home/ash/src/EDMarketConnector/EDMCLogging.py", line 317, in caller_attributes
fn = getattr(frame_class, name, None)
File "/home/ash/.local/share/EDMarketConnector/plugins/edrodent/load.py", line 38, in ready_to_rat
logger.debug("ready_to_rat: %r %r %r %r %r", self.open, self.low_fuel, self.hud_in_analysis_mode, self.has_fuel_transfer_limpet_controller, self.limpets)
File "/usr/local/lib/python3.7/logging/__init__.py", line 1366, in debug
self._log(DEBUG, msg, args, **kwargs)
File "/usr/local/lib/python3.7/logging/__init__.py", line 1513, in _log
exc_info, func, extra, sinfo)
File "/usr/local/lib/python3.7/logging/__init__.py", line 1483, in makeRecord
sinfo)
File "/usr/local/lib/python3.7/logging/__init__.py", line 316, in __init__
self.filename = os.path.basename(pathname)
File "/usr/local/lib/python3.7/posixpath.py", line 147, in basename
sep = _get_sep(p)
File "/usr/local/lib/python3.7/posixpath.py", line 42, in _get_sep
if isinstance(path, bytes):
RecursionError: maximum recursion depth exceeded while calling a Python object

# Fixed code
def __init__(self):
    logger.debug("A call from A.B.__init__")
    self.__test()
    _ = self.test_prop
# Buggy code
def __init__(self):
    logger.debug("A call from A.B.__init__")


# Traceback (AttributeError)
Exception in thread Thread-2:
Traceback (most recent call last):
File "/usr/local/lib/python3.7/threading.py", line 926, in _bootstrap_inner
self.run()
File "/usr/local/lib/python3.7/threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "/home/ash/.local/share/EDMarketConnector/plugins/edmcoverlay/_edmcoverlay.py", line 94, in __server
logger.info("edmcoverlay2: server running")
File "/usr/local/lib/python3.7/logging/__init__.py", line 1378, in info
self._log(INFO, msg, args, **kwargs)
File "/usr/local/lib/python3.7/logging/__init__.py", line 1514, in _log
self.handle(record)
File "/usr/local/lib/python3.7/logging/__init__.py", line 1523, in handle
if (not self.disabled) and self.filter(record):
File "/usr/local/lib/python3.7/logging/__init__.py", line 751, in filter
result = f.filter(record)
File "/home/ash/src/EDMarketConnector/EDMCLogging.py", line 255, in filter
(class_name, qualname, module_name) = self.caller_attributes(module_name=getattr(record, 'module'))
File "/home/ash/src/EDMarketConnector/EDMCLogging.py", line 294, in caller_attributes
fn = getattr(frame_class, frame_info.function)
AttributeError: 'Overlay' object has no attribute '__server'

# Fixed code
def __init__(self):
    logger.debug("A call from A.B.__init__")
    self.__test()
# Buggy code
def is_horizons(
    economies: MAP_STR_ANY, modules: MAP_STR_ANY, ships: MAP_STR_ANY
) -> bool:
    return (
        any(economy["name"] == "Colony" for economy in economies.values())
        or any(module.get("sku") == HORIZ_SKU for module in modules.values())
        or any(
            ship.get("sku") == HORIZ_SKU
            for ship in (ships["shipyard_list"] or {}).values()
        )
    )


# Traceback (AttributeError)
2020-08-21 13:06:28.140 - DEBUG - plugins.eddn.cmdr_data:726: Failed exporting data
Traceback (most recent call last):
File "/home/ad/development/python/EDMarketConnector/plugins/eddn.py", line 716, in cmdr_data
this.eddn.export_shipyard(data, is_beta)
File "/home/ad/development/python/EDMarketConnector/plugins/eddn.py", line 312, in export_shipyard
horizons: bool = is_horizons(
File "/home/ad/development/python/EDMarketConnector/plugins/eddn.py", line 736, in is_horizons
any(module.get('sku') == HORIZ_SKU for module in modules.values()) or
AttributeError: 'list' object has no attribute 'values'

# Fixed code
def is_horizons(economies: MAP_STR_ANY, modules: Dict, ships: MAP_STR_ANY) -> bool:
    return (
        any(economy["name"] == "Colony" for economy in economies.values())
        or any(module.get("sku") == HORIZ_SKU for module in modules.values())
        or any(
            ship.get("sku") == HORIZ_SKU
            for ship in (ships["shipyard_list"] or {}).values()
        )
    )
# Buggy code
def __init__(self, address_or_ble_device: Union[BLEDevice, str], **kwargs):
    super(BleakClientDotNet, self).__init__(address_or_ble_device, **kwargs)

    # Backend specific. Python.NET objects.
    if isinstance(address_or_ble_device, BLEDevice):
        self._device_info = address_or_ble_device.details.BluetoothAddress
    else:
        self._device_info = None
    self._requester = None
    self._bridge = None

    self._address_type = (
        kwargs["address_type"]
        if "address_type" in kwargs and kwargs["address_type"] in ("public", "random")
        else None
    )


# Traceback (AttributeError)
Connecting to mac: [mac here]
Poking services...
Disconnect on device end now...
0...
1...
2...
3...
4...
Waiting for device to indicate disconnection... ensure it is ready to reconnect
0...
1...
2...
3...
4...
5...
6...
7...
8...
9...
10...
11...
12...
13...
14...
Reconnecting...
Poking services...
Disconnecting...
Waiting for device to indicate disconnection...
0...
1...
2...
3...
4...
5...
6...
7...
8...
9...
At this point, nothing has happened and the device still shows as connected... trying again
Disconnecting...
Traceback (most recent call last):
File "c:/Users/user/Documents/ble/test.py", line 338, in <module>
test.start()
File "c:/Users/user/Documents/ble/test.py", line 330, in start
self.loop.run_until_complete(self.__loop())
File "C:\Python38\lib\asyncio\base_events.py", line 616, in run_until_complete
return future.result()
File "c:/Users/user/Documents/ble/test.py", line 323, in __loop
await self.__stdin_msg_handler(msgs)
File "c:/Users/user/Documents/ble/test.py", line 306, in __stdin_msg_handler
await self.__attributeerror_test(mac)
File "c:/Users/user/Documents/ble/test.py", line 197, in __attributeerror_test
await client.disconnect() # this will throw an AttributeError
File "C:\Python38\lib\site-packages\bleak\backends\dotnet\client.py", line 230, in disconnect
self._requester.Dispose()
AttributeError: 'NoneType' object has no attribute 'Dispose'

# Fixed code
def __init__(self, address_or_ble_device: Union[BLEDevice, str], **kwargs):
    super(BleakClientDotNet, self).__init__(address_or_ble_device, **kwargs)

    # Backend specific. Python.NET objects.
    if isinstance(address_or_ble_device, BLEDevice):
        self._device_info = address_or_ble_device.details.BluetoothAddress
    else:
        self._device_info = None
    self._requester = None
    self._bridge = None
    self._disconnect_events: list[asyncio.Event] = []

    self._address_type = (
        kwargs["address_type"]
        if "address_type" in kwargs and kwargs["address_type"] in ("public", "random")
        else None
    )
# Buggy code
def _ConnectionStatusChanged_Handler(sender, args):
    logger.debug("_ConnectionStatusChanged_Handler: %d", sender.ConnectionStatus)
    if (
        sender.ConnectionStatus == BluetoothConnectionStatus.Disconnected
        and self._disconnected_callback
    ):
        loop.call_soon_threadsafe(self._disconnected_callback, self)


# Traceback (AttributeError)
Connecting to mac: [mac here]
Poking services...
Disconnect on device end now...
0...
1...
2...
3...
4...
Waiting for device to indicate disconnection... ensure it is ready to reconnect
0...
1...
2...
3...
4...
5...
6...
7...
8...
9...
10...
11...
12...
13...
14...
Reconnecting...
Poking services...
Disconnecting...
Waiting for device to indicate disconnection...
0...
1...
2...
3...
4...
5...
6...
7...
8...
9...
At this point, nothing has happened and the device still shows as connected... trying again
Disconnecting...
Traceback (most recent call last):
File "c:/Users/user/Documents/ble/test.py", line 338, in <module>
test.start()
File "c:/Users/user/Documents/ble/test.py", line 330, in start
self.loop.run_until_complete(self.__loop())
File "C:\Python38\lib\asyncio\base_events.py", line 616, in run_until_complete
return future.result()
File "c:/Users/user/Documents/ble/test.py", line 323, in __loop
await self.__stdin_msg_handler(msgs)
File "c:/Users/user/Documents/ble/test.py", line 306, in __stdin_msg_handler
await self.__attributeerror_test(mac)
File "c:/Users/user/Documents/ble/test.py", line 197, in __attributeerror_test
await client.disconnect() # this will throw an AttributeError
File "C:\Python38\lib\site-packages\bleak\backends\dotnet\client.py", line 230, in disconnect
self._requester.Dispose()
AttributeError: 'NoneType' object has no attribute 'Dispose'

# Fixed code
def _ConnectionStatusChanged_Handler(sender, args):
    logger.debug("_ConnectionStatusChanged_Handler: %d", sender.ConnectionStatus)
    if sender.ConnectionStatus == BluetoothConnectionStatus.Disconnected:
        if self._disconnected_callback:
            loop.call_soon_threadsafe(self._disconnected_callback, self)

        for e in self._disconnect_events:
            loop.call_soon_threadsafe(e.set)

        def handle_disconnect():
            self._requester = None

        loop.call_soon_threadsafe(handle_disconnect)
# Buggy code
async def is_connected(self) -> bool:
    """Check connection status between this client and the server.

    Returns:
        Boolean representing connection status.

    """
    # TODO: Listen to connected property changes.
    is_connected = False
    try:
        is_connected = await self._bus.callRemote(
            self._device_path,
            "Get",
            interface=defs.PROPERTIES_INTERFACE,
            destination=defs.BLUEZ_SERVICE,
            signature="ss",
            body=[defs.DEVICE_INTERFACE, "Connected"],
            returnSignature="v",
        ).asFuture(asyncio.get_event_loop())
    except AttributeError:
        # The `self._bus` object had already been cleaned up due to disconnect...
        pass
    except ConnectionDone:
        # Twisted error stating that "Connection was closed cleanly."
        pass
    except Exception as e:
        # Do not want to silence unknown errors. Send this upwards.
        raise
    return is_connected


# Traceback (txdbus.error.RemoteError)
client = BleakClient(address)
await client.connect()
await client.disconnect()

Traceback (most recent call last):
File "/home/pi/venv/lib/python3.7/site-packages/aioconsole/execute.py", line 87, in aexec
result, new_local = await coro
File "<aexec>", line 2, in __corofn
File "/home/pi/venv/lib/python3.7/site-packages/bleak/backends/bluezdbus/client.py", line 245, in disconnect
is_disconnected = not await self.is_connected()
File "/home/pi/venv/lib/python3.7/site-packages/bleak/backends/bluezdbus/client.py", line 346, in is_connected
).asFuture(asyncio.get_event_loop())
txdbus.error.RemoteError: org.freedesktop.DBus.Error.UnknownObject: Method "Get" with signature "ss" on interface "org.freedesktop.DBus.Properties" doesn't exist

# Fixed code
async def is_connected(self) -> bool:
    """Check connection status between this client and the server.

    Returns:
        Boolean representing connection status.

    """
    # TODO: Listen to connected property changes.
    is_connected = False
    try:
        is_connected = await self._bus.callRemote(
            self._device_path,
            "Get",
            interface=defs.PROPERTIES_INTERFACE,
            destination=defs.BLUEZ_SERVICE,
            signature="ss",
            body=[defs.DEVICE_INTERFACE, "Connected"],
            returnSignature="v",
        ).asFuture(asyncio.get_event_loop())
    except AttributeError:
        # The `self._bus` object had already been cleaned up due to disconnect...
        pass
    except ConnectionDone:
        # Twisted error stating that "Connection was closed cleanly."
        pass
    except RemoteError as e:
        if e.errName != "org.freedesktop.DBus.Error.UnknownObject":
            raise
    except Exception as e:
        # Do not want to silence unknown errors. Send this upwards.
        raise
    return is_connected
# Buggy code
async def is_connected(self) -> bool:
    """Check connection status between this client and the server.

    Returns:
        Boolean representing connection status.

    """
    # TODO: Listen to connected property changes.
    return await self._bus.callRemote(
        self._device_path,
        "Get",
        interface=defs.PROPERTIES_INTERFACE,
        destination=defs.BLUEZ_SERVICE,
        signature="ss",
        body=[defs.DEVICE_INTERFACE, "Connected"],
        returnSignature="v",
    ).asFuture(asyncio.get_event_loop())


# Traceback (AttributeError)
INFO:__main__:Connected: True
True
True
...
True
True
DEBUG:bleak.backends.bluezdbus.client:DBUS: path: /org/bluez/hci0/dev_REDACTED, domain: org.bluez.Device1, body: {'ServicesResolved': False, 'Connected': False}
DEBUG:bleak.backends.bluezdbus.client:Device REDACTED disconnected.
DEBUG:bleak.backends.bluezdbus.client:Removing rule PropChanged, ID: 1
DEBUG:bleak.backends.bluezdbus.client:Disconnecting from BLE device...
Traceback (most recent call last):
File "disconnect_test.py", line 21, in <module>
asyncio.run(run(address))
File "/usr/lib/python3.7/asyncio/runners.py", line 43, in run
return loop.run_until_complete(main)
File "/usr/lib/python3.7/asyncio/base_events.py", line 584, in run_until_complete
return future.result()
File "disconnect_test.py", line 16, in run
print(await client.is_connected())
File "/home/pi/.local/lib/python3.7/site-packages/bleak/backends/bluezdbus/client.py", line 282, in is_connected
return await self._bus.callRemote(
AttributeError: 'NoneType' object has no attribute 'callRemote'

# Fixed code
async def is_connected(self) -> bool:
    """Check connection status between this client and the server.

    Returns:
        Boolean representing connection status.

    """
    # TODO: Listen to connected property changes.
    is_connected = False
    try:
        is_connected = await self._bus.callRemote(
            self._device_path,
            "Get",
            interface=defs.PROPERTIES_INTERFACE,
            destination=defs.BLUEZ_SERVICE,
            signature="ss",
            body=[defs.DEVICE_INTERFACE, "Connected"],
            returnSignature="v",
        ).asFuture(asyncio.get_event_loop())
    except AttributeError:
        # The `self._bus` object had already been cleaned up due to disconnect...
        pass
    except ConnectionDone:
        # Twisted error stating that "Connection was closed cleanly."
        pass
    except Exception as e:
        # Do not want to silence unknown errors. Send this upwards.
        raise
    return is_connected
# Buggy code
async def scanForPeripherals_(self, scan_options) -> List[CBPeripheral]:
    """
    Scan for peripheral devices
    scan_options = { service_uuids, timeout }
    """
    # remove old
    self.devices = {}
    service_uuids = []
    if "service_uuids" in scan_options:
        service_uuids_str = scan_options["service_uuids"]
        service_uuids = NSArray.alloc().initWithArray_(
            list(map(string2uuid, service_uuids_str))
        )

    timeout = 0
    if "timeout" in scan_options:
        timeout = float(scan_options["timeout"])

    self.central_manager.scanForPeripheralsWithServices_options_(service_uuids, None)

    if timeout > 0:
        await asyncio.sleep(timeout)

    self.central_manager.stopScan()
    while self.central_manager.isScanning():
        await asyncio.sleep(0.1)

    return []


# Traceback (AttributeError)
$ python scanner.py
Traceback (most recent call last):
File "scanner.py", line 12, in <module>
loop.run_until_complete(run())
File "/usr/local/Cellar/python/3.7.0/Frameworks/Python.framework/Versions/3.7/lib/python3.7/asyncio/base_events.py", line 568, in run_until_complete
return future.result()
File "scanner.py", line 6, in run
devices = await discover()
File "/Users/matteo/virtualenvs/bt-scanner/lib/python3.7/site-packages/bleak/backends/corebluetooth/discovery.py", line 35, in discover
await cbapp.central_manager_delegate.scanForPeripherals_(scan_options)
File "/Users/matteo/virtualenvs/bt-scanner/lib/python3.7/site-packages/bleak/backends/corebluetooth/CentralManagerDelegate.py", line 121, in scanForPeripherals_
while self.central_manager.isScanning():
AttributeError: 'CBCentralManager' object has no attribute 'isScanning'

# Fixed code
async def scanForPeripherals_(self, scan_options) -> List[CBPeripheral]:
    """
    Scan for peripheral devices
    scan_options = { service_uuids, timeout }
    """
    # remove old
    self.devices = {}
    service_uuids = []
    if "service_uuids" in scan_options:
        service_uuids_str = scan_options["service_uuids"]
        service_uuids = NSArray.alloc().initWithArray_(
            list(map(string2uuid, service_uuids_str))
        )

    timeout = 0
    if "timeout" in scan_options:
        timeout = float(scan_options["timeout"])

    self.central_manager.scanForPeripheralsWithServices_options_(service_uuids, None)

    if timeout > 0:
        await asyncio.sleep(timeout)

    self.central_manager.stopScan()

    # Wait a while to allow central manager to stop scanning.
    # The `isScanning` attribute is added in macOS 10.13, so before that
    # just waiting some will have to do. In 10.13+ I have never seen
    # bleak enter the while-loop, so this fix is most probably safe.
    if _IS_PRE_10_13:
        await asyncio.sleep(0.1)
    else:
        while self.central_manager.isScanning():
            await asyncio.sleep(0.1)

    return []
# 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._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()))


# Traceback (txdbus.error.RemoteError)
Traceback (most recent call last):
File "discover.py", line 29, in <module>
loop.run_until_complete(run())
File "/usr/lib64/python3.7/asyncio/base_events.py", line 584, in run_until_complete
return future.result()
File "discover.py", line 22, in run
devices = await discover(timeout=1)
File "/home/joe/code/proglove/python/bleak/bleak/backends/bluezdbus/discovery.py", line 125, in discover
bus = await client.connect(reactor, "system").asFuture(loop)
txdbus.error.RemoteError: org.freedesktop.DBus.Error.LimitsExceeded: The maximum number of active connections for UID 1000 has been reached

# 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._subscriptions = list()

    self._disconnected_callback = None

    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 disconnect(self) -> bool:
    """Disconnect from the specified GATT server.

    Returns:
        Boolean representing connection status.

    """
    logger.debug("Disconnecting from BLE device...")
    for rule_name, rule_id in self._rules.items():
        logger.debug("Removing rule {0}, ID: {1}".format(rule_name, rule_id))
        await self._bus.delMatch(rule_id).asFuture(self.loop)
    await self._bus.callRemote(
        self._device_path,
        "Disconnect",
        interface=defs.DEVICE_INTERFACE,
        destination=defs.BLUEZ_SERVICE,
    ).asFuture(self.loop)
    return not await self.is_connected()


# Traceback (txdbus.error.RemoteError)
Traceback (most recent call last):
File "discover.py", line 29, in <module>
loop.run_until_complete(run())
File "/usr/lib64/python3.7/asyncio/base_events.py", line 584, in run_until_complete
return future.result()
File "discover.py", line 22, in run
devices = await discover(timeout=1)
File "/home/joe/code/proglove/python/bleak/bleak/backends/bluezdbus/discovery.py", line 125, in discover
bus = await client.connect(reactor, "system").asFuture(loop)
txdbus.error.RemoteError: org.freedesktop.DBus.Error.LimitsExceeded: The maximum number of active connections for UID 1000 has been reached

# Fixed code
async def disconnect(self) -> bool:
    """Disconnect from the specified GATT server.

    Returns:
        Boolean representing connection status.

    """
    logger.debug("Disconnecting from BLE device...")

    await self._cleanup()

    await self._bus.callRemote(
        self._device_path,
        "Disconnect",
        interface=defs.DEVICE_INTERFACE,
        destination=defs.BLUEZ_SERVICE,
    ).asFuture(self.loop)
    return not await self.is_connected()
# Buggy code
async def stop_notify(self, _uuid: str) -> None:
    """Deactivate notification/indication on a specified characteristic.

    Args:
        _uuid: The characteristic to stop notifying/indicating on.

    """
    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)


# Traceback (txdbus.error.RemoteError)
Traceback (most recent call last):
File "discover.py", line 29, in <module>
loop.run_until_complete(run())
File "/usr/lib64/python3.7/asyncio/base_events.py", line 584, in run_until_complete
return future.result()
File "discover.py", line 22, in run
devices = await discover(timeout=1)
File "/home/joe/code/proglove/python/bleak/bleak/backends/bluezdbus/discovery.py", line 125, in discover
bus = await client.connect(reactor, "system").asFuture(loop)
txdbus.error.RemoteError: org.freedesktop.DBus.Error.LimitsExceeded: The maximum number of active connections for UID 1000 has been reached

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

    Args:
        _uuid: The characteristic to stop notifying/indicating on.

    """
    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)

    self._subscriptions.remove(_uuid)
# Buggy 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])


# Traceback (txdbus.error.RemoteError)
Traceback (most recent call last):
File "discover.py", line 29, in <module>
loop.run_until_complete(run())
File "/usr/lib64/python3.7/asyncio/base_events.py", line 584, in run_until_complete
return future.result()
File "discover.py", line 22, in run
devices = await discover(timeout=1)
File "/home/joe/code/proglove/python/bleak/bleak/backends/bluezdbus/discovery.py", line 125, in discover
bus = await client.connect(reactor, "system").asFuture(loop)
txdbus.error.RemoteError: org.freedesktop.DBus.Error.LimitsExceeded: The maximum number of active connections for UID 1000 has been reached

# 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.

    """

    logger.debug(
        "DBUS: path: {}, domain: {}, body: {}".format(
            message.path, message.body[0], message.body[1]
        )
    )

    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])
    elif message.body[0] == defs.DEVICE_INTERFACE:
        device_path = "/org/bluez/%s/dev_%s" % (
            self.device,
            self.address.replace(":", "_"),
        )
        if message.path == device_path:
            message_body_map = message.body[1]
            if "Connected" in message_body_map and not message_body_map["Connected"]:
                logger.debug("Device {} disconnected.".format(self.address))

                self.loop.create_task(self._cleanup())

                if self._disconnected_callback is not None:
                    self._disconnected_callback(self)
# Buggy code
def __init__(self, address, hci_device="hci0"):
    raise NotImplementedError("BleakClientCoreBluetooth not implemented yet.")


# Traceback (txdbus.error.RemoteError)
Traceback (most recent call last):
File "discover.py", line 29, in <module>
loop.run_until_complete(run())
File "/usr/lib64/python3.7/asyncio/base_events.py", line 584, in run_until_complete
return future.result()
File "discover.py", line 22, in run
devices = await discover(timeout=1)
File "/home/joe/code/proglove/python/bleak/bleak/backends/bluezdbus/discovery.py", line 125, in discover
bus = await client.connect(reactor, "system").asFuture(loop)
txdbus.error.RemoteError: org.freedesktop.DBus.Error.LimitsExceeded: The maximum number of active connections for UID 1000 has been reached

# Fixed code
def __init__(self):
    self.main_loop = asyncio.get_event_loop()
    self.main_loop.create_task(self._handle_nsrunloop())
    self.main_loop.create_task(self._central_manager_delegate_ready())

    self.nsrunloop = NSRunLoop.currentRunLoop()

    self.central_manager_delegate = CentralManagerDelegate.alloc().init()
# Buggy code
def rssi(self):
    """Get the signal strength in dBm"""
    if isinstance(self.details, dict) and "props" in self.details:
        rssi = self.details["props"].get("RSSI", 0)  # Should not be set to 0...
    elif hasattr(self.details, "RawSignalStrengthInDBm"):
        rssi = self.details.RawSignalStrengthInDBm
    else:
        rssi = None
    return int(rssi) if rssi is not None else None


# Traceback (txdbus.error.RemoteError)
Traceback (most recent call last):
File "discover.py", line 29, in <module>
loop.run_until_complete(run())
File "/usr/lib64/python3.7/asyncio/base_events.py", line 584, in run_until_complete
return future.result()
File "discover.py", line 22, in run
devices = await discover(timeout=1)
File "/home/joe/code/proglove/python/bleak/bleak/backends/bluezdbus/discovery.py", line 125, in discover
bus = await client.connect(reactor, "system").asFuture(loop)
txdbus.error.RemoteError: org.freedesktop.DBus.Error.LimitsExceeded: The maximum number of active connections for UID 1000 has been reached

# Fixed code
def rssi(self):
    """Get the signal strength in dBm"""
    if isinstance(self.details, dict) and "props" in self.details:
        rssi = self.details["props"].get("RSSI", 0)  # Should not be set to 0...
    elif hasattr(self.details, "RawSignalStrengthInDBm"):
        rssi = self.details.RawSignalStrengthInDBm
    elif hasattr(self.details, "Properties"):
        rssi = {p.Key: p.Value for p in self.details.Properties}[
            "System.Devices.Aep.SignalStrength"
        ]
    else:
        rssi = None
    return int(rssi) if rssi is not None else None
# Buggy code
async def stop_notify(self, _uuid: str) -> None:
    """Deactivate notification/indication on a specified characteristic.

    Args:
        _uuid: The characteristic to stop notifying/indicating 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)


# Traceback (txdbus.error.RemoteError)
Traceback (most recent call last):
File "discover.py", line 29, in <module>
loop.run_until_complete(run())
File "/usr/lib64/python3.7/asyncio/base_events.py", line 584, in run_until_complete
return future.result()
File "discover.py", line 22, in run
devices = await discover(timeout=1)
File "/home/joe/code/proglove/python/bleak/bleak/backends/bluezdbus/discovery.py", line 125, in discover
bus = await client.connect(reactor, "system").asFuture(loop)
txdbus.error.RemoteError: org.freedesktop.DBus.Error.LimitsExceeded: The maximum number of active connections for UID 1000 has been reached

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

    Args:
        _uuid: The characteristic to stop notifying/indicating 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 stop notify on {0}: {1}".format(characteristic.uuid, status)
        )
    else:
        callback = self._callbacks.pop(characteristic.uuid)
        self._bridge.RemoveValueChangedCallback(characteristic.obj, callback)
# Buggy code
def _device_info(path, props):
    name = props.get("Name", props.get("Alias", path.split("/")[-1]))
    address = props.get("Address", None)
    if address is None:
        try:
            address = path[-17:].replace("_", ":")
            if not validate_mac_address(address):
                address = None
        except Exception:
            address = None
    rssi = props.get("RSSI", "?")
    return name, address, rssi, path


# 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 _device_info(path, props):
    try:
        name = props.get("Name", props.get("Alias", path.split("/")[-1]))
        address = props.get("Address", None)
        if address is None:
            try:
                address = path[-17:].replace("_", ":")
                if not validate_mac_address(address):
                    address = None
            except Exception:
                address = None
        rssi = props.get("RSSI", "?")
        return name, address, rssi, path
    except Exception as e:
        logger.exception(e, exc_info=True)
        return None, None, None, None