gurudesh/pytracebugs huggingface dataset:
# Buggy code
def find_multipart_redirect_url(data, headers):
    """Return object key and redirect URL if they can be found.

    Data is given as multipart form submission bytes, and redirect is found
    in the success_action_redirect field according to Amazon S3
    documentation for Post uploads:
    http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectPOST.html
    """
    _, params = cgi.parse_header(headers.get("Content-Type"))
    boundary = params["boundary"].encode("ascii")
    data_bytes = to_bytes(data)

    key, redirect_url = None, None

    for disposition, part in _iter_multipart_parts(data_bytes, boundary):
        if disposition.get("name") == "key":
            _, value = part.split(b"\r\n\r\n", 1)
            key = value.rstrip(b"\r\n--").decode("utf8")

    if key:
        for disposition, part in _iter_multipart_parts(data_bytes, boundary):
            if disposition.get("name") == "success_action_redirect":
                _, value = part.split(b"\r\n\r\n", 1)
                redirect_url = value.rstrip(b"\r\n--").decode("utf8")

    return key, redirect_url


# Traceback (TypeError)
2017-10-10T10:58:34:ERROR:localstack.services.generic_proxy: Error forwarding request: string indices must be integers Traceback (most recent call last):
File "/usr/local/lib/python3.6/site-packages/localstack/services/generic_proxy.py", line 194, in forward
path=path, data=data, headers=forward_headers, response=response)
File "/usr/local/lib/python3.6/site-packages/localstack/services/s3/s3_listener.py", line 436, in return_response
send_notifications(method, bucket_name, object_path)
File "/usr/local/lib/python3.6/site-packages/localstack/services/s3/s3_listener.py", line 122, in send_notifications
filter_rules_match(config.get('Filter'), object_path)):
File "/usr/local/lib/python3.6/site-packages/localstack/services/s3/s3_listener.py", line 50, in filter_rules_match
if rule['Name'] == 'prefix':
TypeError: string indices must be integers

# Fixed code
def find_multipart_redirect_url(data, headers):
    """Return object key and redirect URL if they can be found.

    Data is given as multipart form submission bytes, and redirect is found
    in the success_action_redirect field according to Amazon S3
    documentation for Post uploads:
    http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectPOST.html
    """
    _, params = cgi.parse_header(headers.get("Content-Type", ""))
    key, redirect_url = None, None

    if "boundary" not in params:
        return key, redirect_url

    boundary = params["boundary"].encode("ascii")
    data_bytes = to_bytes(data)

    for disposition, part in _iter_multipart_parts(data_bytes, boundary):
        if disposition.get("name") == "key":
            _, value = part.split(b"\r\n\r\n", 1)
            key = value.rstrip(b"\r\n--").decode("utf8")

    if key:
        for disposition, part in _iter_multipart_parts(data_bytes, boundary):
            if disposition.get("name") == "success_action_redirect":
                _, value = part.split(b"\r\n\r\n", 1)
                redirect_url = value.rstrip(b"\r\n--").decode("utf8")

    return key, redirect_url
# Buggy code
def expand_multipart_filename(data, headers):
    """Replace instance of '${filename}' in key with given file name.

    Data is given as multipart form submission bytes, and file name is
    replace according to Amazon S3 documentation for Post uploads:
    http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectPOST.html
    """
    _, params = cgi.parse_header(headers.get("Content-Type"))
    boundary = params["boundary"].encode("ascii")
    data_bytes = to_bytes(data)

    filename = None

    for disposition, _ in _iter_multipart_parts(data_bytes, boundary):
        if disposition.get("name") == "file" and "filename" in disposition:
            filename = disposition["filename"]
            break

    if filename is None:
        # Found nothing, return unaltered
        return data

    for disposition, part in _iter_multipart_parts(data_bytes, boundary):
        if disposition.get("name") == "key" and b"${filename}" in part:
            search = boundary + part
            replace = boundary + part.replace(b"${filename}", filename.encode("utf8"))

            if search in data_bytes:
                return data_bytes.replace(search, replace)

    return data


# Traceback (KeyError)
2017-09-11T04:24:30:ERROR:localstack.services.generic_proxy: Error forwarding request: 'boundary' Traceback (most recent call last):
File "/opt/code/localstack/localstack/services/generic_proxy.py", line 166, in forward
path=path, data=data, headers=forward_headers)
File "/opt/code/localstack/localstack/services/s3/s3_listener.py", line 345, in forward_request
expanded_data = expand_multipart_filename(original_data, headers)
File "/opt/code/localstack/localstack/services/s3/s3_listener.py", line 261, in expand_multipart_filename
boundary = params['boundary'].encode('ascii')
KeyError: 'boundary'

# Fixed code
def expand_multipart_filename(data, headers):
    """Replace instance of '${filename}' in key with given file name.

    Data is given as multipart form submission bytes, and file name is
    replace according to Amazon S3 documentation for Post uploads:
    http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectPOST.html
    """
    _, params = cgi.parse_header(headers.get("Content-Type"))

    if "boundary" not in params:
        return data

    boundary = params["boundary"].encode("ascii")
    data_bytes = to_bytes(data)

    filename = None

    for disposition, _ in _iter_multipart_parts(data_bytes, boundary):
        if disposition.get("name") == "file" and "filename" in disposition:
            filename = disposition["filename"]
            break

    if filename is None:
        # Found nothing, return unaltered
        return data

    for disposition, part in _iter_multipart_parts(data_bytes, boundary):
        if disposition.get("name") == "key" and b"${filename}" in part:
            search = boundary + part
            replace = boundary + part.replace(b"${filename}", filename.encode("utf8"))

            if search in data_bytes:
                return data_bytes.replace(search, replace)

    return data
# Buggy code
def backlight(self):
    level = self._get_backlight_level()
    full_text = self.py3.safe_format(self.format, {"level": level})
    response = {
        "cached_until": self.py3.time_in(self.cache_timeout),
        "full_text": full_text,
    }
    return response


# Traceback (IndexError)
Traceback (most recent call last):
File "battery_level.py", line 448, in <module>
module_test(Py3status)
File "/usr/lib/python3.5/site-packages/py3status/module_test.py", line 51, in module_test
print(getattr(module, method)(*method_args))
File "battery_level.py", line 174, in battery_level
self._refresh_battery_info()
File "battery_level.py", line 316, in _refresh_battery_info
battery = battery_list[self.battery_id]
IndexError: list index out of range

# Fixed code
def backlight(self):
    full_text = ""
    if self.device_path is not None:
        level = self._get_backlight_level()
        full_text = self.py3.safe_format(self.format, {"level": level})

    response = {
        "cached_until": self.py3.time_in(self.cache_timeout),
        "full_text": full_text,
    }
    return response
# Buggy code
def battery_level(self):
    self._refresh_battery_info()

    self._update_icon()
    self._update_ascii_bar()
    self._update_full_text()

    return self._build_response()


# Traceback (IndexError)
Traceback (most recent call last):
File "battery_level.py", line 448, in <module>
module_test(Py3status)
File "/usr/lib/python3.5/site-packages/py3status/module_test.py", line 51, in module_test
print(getattr(module, method)(*method_args))
File "battery_level.py", line 174, in battery_level
self._refresh_battery_info()
File "battery_level.py", line 316, in _refresh_battery_info
battery = battery_list[self.battery_id]
IndexError: list index out of range

# Fixed code
def battery_level(self):
    if not os.listdir(self.sys_battery_path):
        return {"full_text": "", "cached_until": self.py3.time_in(self.cache_timeout)}

    self._refresh_battery_info()
    self._update_icon()
    self._update_ascii_bar()
    self._update_full_text()

    return self._build_response()
# Buggy code
def _config_from_pyproject(path):
    if os.path.isfile(path):
        try:
            with open(path, "r") as f:
                pyproject = tomlkit.loads(f.read())
            if pyproject:
                return dict(pyproject.get("tool").get("semantic_release"))
        except TOMLKitError as e:
            logger.debug(f"Could not decode pyproject.toml: {e}")

    return {}


# Traceback (TypeError)
Run relekang/python-semantic-release@master
/usr/bin/docker run --name eb9cc679ae0e4f1f83d7f2d23985a34f_6e2f70 --label 442333 --workdir /github/workspace --rm -e INPUT_GITHUB_TOKEN -e INPUT_PYPI_TOKEN -e INPUT_DIRECTORY -e INPUT_PYPI_USERNAME -e INPUT_PYPI_PASSWORD -e HOME -e GITHUB_JOB -e GITHUB_REF -e GITHUB_SHA -e GITHUB_REPOSITORY -e GITHUB_REPOSITORY_OWNER -e GITHUB_RUN_ID -e GITHUB_RUN_NUMBER -e GITHUB_RETENTION_DAYS -e GITHUB_ACTOR -e GITHUB_WORKFLOW -e GITHUB_HEAD_REF -e GITHUB_BASE_REF -e GITHUB_EVENT_NAME -e GITHUB_SERVER_URL -e GITHUB_API_URL -e GITHUB_GRAPHQL_URL -e GITHUB_WORKSPACE -e GITHUB_ACTION -e GITHUB_EVENT_PATH -e GITHUB_ACTION_REPOSITORY -e GITHUB_ACTION_REF -e GITHUB_PATH -e GITHUB_ENV -e RUNNER_OS -e RUNNER_TOOL_CACHE -e RUNNER_TEMP -e RUNNER_WORKSPACE -e ACTIONS_RUNTIME_URL -e ACTIONS_RUNTIME_TOKEN -e ACTIONS_CACHE_URL -e GITHUB_ACTIONS=true -e CI=true -v "/var/run/docker.sock":"/var/run/docker.sock" -v "/home/runner/work/_temp/_github_home":"/github/home" -v "/home/runner/work/_temp/_github_workflow":"/github/workflow" -v "/home/runner/work/_temp/_runner_file_commands":"/github/file_commands" -v "/home/runner/work/arbie/arbie":"/github/workspace" 442333:eb9cc679ae0e4f1f83d7f2d23985a34f
Traceback (most recent call last):
File "/usr/local/lib/python3.7/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "/usr/local/lib/python3.7/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/semantic-release/semantic_release/__main__.py", line 1, in <module>
from .cli import entry
File "/semantic-release/semantic_release/cli.py", line 13, in <module>
from .changelog import markdown_changelog
File "/semantic-release/semantic_release/changelog/__init__.py", line 4, in <module>
from ..settings import config, current_changelog_components
File "/semantic-release/semantic_release/settings.py", line 77, in <module>
config = _config()
File "/semantic-release/semantic_release/settings.py", line 29, in _config
toml_config = _config_from_pyproject(toml_path)
File "/semantic-release/semantic_release/settings.py", line 70, in _config_from_pyproject
return dict(pyproject.get("tool").get("semantic_release"))
TypeError: 'NoneType' object is not iterable

# Fixed code
def _config_from_pyproject(path):
    if os.path.isfile(path):
        try:
            with open(path, "r") as f:
                pyproject = tomlkit.loads(f.read())
            if pyproject:
                return pyproject.get("tool", {}).get("semantic_release", {})
        except TOMLKitError as e:
            logger.debug(f"Could not decode pyproject.toml: {e}")

    return {}
# Buggy code
def commit_new_version(version: str):
    """
    Commits the file containing the version number variable with the version number as the commit
    message.

    :param version: The version number to be used in the commit message.
    """

    check_repo()
    commit_message = config.get("semantic_release", "commit_message")
    message = "{0}\n\n{1}".format(version, commit_message)
    repo.git.add(config.get("semantic_release", "version_variable").split(":")[0])
    return repo.git.commit(m=message, author="semantic-release <semantic-release>")


# Traceback (git.exc.NoSuchPathError)
venv) C:\workspace\checklive\src>semantic-release --patch publish
Traceback (most recent call last):
File "c:\python35\lib\runpy.py", line 170, in _run_module_as_main
"__main__", mod_spec)
File "c:\python35\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "C:\workspace\checklive\venv\Scripts\semantic-release.exe\__main__.py", line 5, in <module>
File "c:\workspace\checklive\venv\lib\site-packages\semantic_release\cli.py", line 9, in <module>
from .history import (evaluate_version_bump, get_current_version, get_new_version,
File "c:\workspace\checklive\venv\lib\site-packages\semantic_release\history\__init__.py", line 6, in <module>
from ..vcs_helpers import get_commit_log, get_last_version
File "c:\workspace\checklive\venv\lib\site-packages\semantic_release\vcs_helpers.py", line 8, in <module>
repo = Repo('.git', search_parent_directories=True)
File "c:\workspace\checklive\venv\lib\site-packages\git\repo\base.py", line 135, in __init__
raise NoSuchPathError(epath)
git.exc.NoSuchPathError: C:\workspace\checklive\src\.git

(venv) C:\workspace\checklive\src>

# Fixed code
def commit_new_version(version: str):
    """
    Commits the file containing the version number variable with the version number as the commit
    message.

    :param version: The version number to be used in the commit message.
    """

    check_repo()
    commit_message = config.get("semantic_release", "commit_message")
    message = "{0}\n\n{1}".format(version, commit_message)

    version_file = config.get("semantic_release", "version_variable").split(":")[0]
    # get actual path to filename, to allow running cmd from subdir of git root
    version_filepath = PurePath(os.getcwd(), version_file).relative_to(repo.working_dir)

    repo.git.add(str(version_filepath))
    return repo.git.commit(m=message, author="semantic-release <semantic-release>")
# Buggy code
def __getattr__(self, key):
    # TODO keep this for a version, in order to not break old code
    # this entire method (as well as the _dict attribute in __slots__ and the __setattr__ method)
    # can be removed in 4.0
    # this method is only called if the attribute was not found elsewhere, like in __slots__
    try:
        warnings.warn(
            "Custom attributes of messages are deprecated and will be removed in 4.0",
            DeprecationWarning,
        )
        return self._dict[key]
    except KeyError:
        raise AttributeError("'message' object has no attribute '{}'".format(key))


# Traceback (RecursionError)
/usr/bin/python3.7 /XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SerializationTest.py
2020-04-02 13:35:59,352:MainThread:INFO: Created a socket
2020-04-02 13:35:59,389:MainThread:INFO: pickled
Traceback (most recent call last):
File "/XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SerializationTest.py", line 39, in <module>
canReader.run()
File "/XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SerializationTest.py", line 29, in run
unpick = pickle.loads(pick)
File "/home/XXXXXX/.local/lib/python3.7/site-packages/can/message.py", line 59, in __getattr__
return self._dict[key]
File "/home/XXXXXX/.local/lib/python3.7/site-packages/can/message.py", line 59, in __getattr__
return self._dict[key]
File "/home/XXXXXX/.local/lib/python3.7/site-packages/can/message.py", line 59, in __getattr__
return self._dict[key]
[Previous line repeated 494 more times]
File "/home/XXXXXX/.local/lib/python3.7/site-packages/can/message.py", line 58, in __getattr__
warnings.warn("Custom attributes of messages are deprecated and will be removed in 4.0", DeprecationWarning)
RecursionError: maximum recursion depth exceeded while calling a Python object

Process finished with exit code 1

# Fixed code
def __getattr__(self, key):
    # TODO keep this for a version, in order to not break old code
    # this entire method (as well as the _dict attribute in __slots__ and the __setattr__ method)
    # can be removed in 4.0
    # this method is only called if the attribute was not found elsewhere, like in __slots_
    if key not in self.__slots__:
        raise AttributeError
    try:
        warnings.warn(
            "Custom attributes of messages are deprecated and will be removed in 4.0",
            DeprecationWarning,
        )
        return self._dict[key]
    except KeyError:
        raise AttributeError("'message' object has no attribute '{}'".format(key))
# Buggy code
def build_bcm_header(
    opcode,
    flags,
    count,
    ival1_seconds,
    ival1_usec,
    ival2_seconds,
    ival2_usec,
    can_id,
    nframes,
):
    # == Must use native not standard types for packing ==
    # struct bcm_msg_head {
    #     __u32 opcode; -> I
    #     __u32 flags;  -> I
    #     __u32 count;  -> I
    #     struct timeval ival1, ival2; ->  llll ...
    #     canid_t can_id; -> I
    #     __u32 nframes; -> I
    bcm_cmd_msg_fmt = "@3I4l2I0q"

    return struct.pack(
        bcm_cmd_msg_fmt,
        opcode,
        flags,
        count,
        ival1_seconds,
        ival1_usec,
        ival2_seconds,
        ival2_usec,
        can_id,
        nframes,
    )


# Traceback (can.CanError)
Traceback (most recent call last):

File "./test.py", line 8, in <module>
bus.send_periodic(msg, 0.01, 9)
File "/usr/local/lib/python3.5/dist-packages/can/bus.py", line 201, in send_periodic
task = self._send_periodic_internal(msg, period, duration)
File "/usr/local/lib/python3.5/dist-packages/can/interfaces/socketcan/socketcan.py", line 601, in _send_periodic_internal
task = CyclicSendTask(bcm_socket, msg, period, duration)
File "/usr/local/lib/python3.5/dist-packages/can/interfaces/socketcan/socketcan.py", line 254, in __init__
self._tx_setup(message)
File "/usr/local/lib/python3.5/dist-packages/can/interfaces/socketcan/socketcan.py", line 274, in _tx_setup
send_bcm(self.bcm_socket, header + frame)
File "/usr/local/lib/python3.5/dist-packages/can/interfaces/socketcan/socketcan.py", line 206, in send_bcm
raise can.CanError(base + "You are probably referring to a non-existing frame.")
can.CanError: Couldn't send CAN BCM frame. OS Error 22: Invalid argument
You are probably referring to a non-existing frame.

# Fixed code
def build_bcm_header(
    opcode,
    flags,
    count,
    ival1_seconds,
    ival1_usec,
    ival2_seconds,
    ival2_usec,
    can_id,
    nframes,
):
    result = BcmMsgHead(
        opcode=opcode,
        flags=flags,
        count=count,
        ival1_tv_sec=ival1_seconds,
        ival1_tv_usec=ival1_usec,
        ival2_tv_sec=ival2_seconds,
        ival2_tv_usec=ival2_usec,
        can_id=can_id,
        nframes=nframes,
    )
    return ctypes.string_at(ctypes.addressof(result), ctypes.sizeof(result))
# Buggy code
def write(self, string):
    if not string.endswith("\r"):
        string += "\r"
    self.serialPort.write(string.decode())
    self.serialPort.flush()


# Traceback (AttributeError)
DEBUG:can:loaded can config: {'interface': 'slcan', 'channel': '/dev/ttyUSB0@115200'}
Traceback (most recent call last):
File "encoder-test.py", line 19, in <module>
network.connect(channel='/dev/ttyUSB0@115200', bustype='slcan')
File "/usr/local/lib/python3.5/dist-packages/canopen/network.py", line 100, in connect
self.bus = can.interface.Bus(*args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/can/interface.py", line 120, in __new__
return cls(channel, *args, **config)
File "/usr/local/lib/python3.5/dist-packages/can/interfaces/slcan.py", line 81, in __init__
self.open()
File "/usr/local/lib/python3.5/dist-packages/can/interfaces/slcan.py", line 93, in open
self.write('O')
File "/usr/local/lib/python3.5/dist-packages/can/interfaces/slcan.py", line 89, in write
self.serialPort.write(string.decode())
AttributeError: 'str' object has no attribute 'decode'

# Fixed code
def write(self, string):
    if not string.endswith("\r"):
        string += "\r"
    self.serialPortOrig.write(string.encode())
    self.serialPortOrig.flush()
# Buggy code
def __init__(self, filename):
    self.fp = open(filename, "rb")
    data = self.fp.read(FILE_HEADER_STRUCT.size)
    header = FILE_HEADER_STRUCT.unpack(data)
    # print(header)
    assert header[0] == b"LOGG", "Unknown file format"
    self.file_size = header[10]
    self.uncompressed_size = header[11]
    self.object_count = header[12]
    self.start_timestamp = systemtime_to_timestamp(header[14:22])
    self.stop_timestamp = systemtime_to_timestamp(header[22:30])


# Traceback (AssertionError)
Traceback (most recent call last):
File "D:\eclipse-workspace\blf2csv\pythoncan_blf2csv.py", line 7, in <module>
logging = list(logging)
File "C:\Users\my_user_name\AppData\Local\Python\Python36\lib\site-packages\can\io\blf.py", line 129, in __iter__
assert header[0] == b"LOBJ", "Parse error"
AssertionError: Parse error

# Fixed code
def __init__(self, filename):
    self.fp = open(filename, "rb")
    data = self.fp.read(FILE_HEADER_STRUCT.size)
    header = FILE_HEADER_STRUCT.unpack(data)
    # print(header)
    if header[0] != b"LOGG":
        raise BLFParseError("Unexpected file format")
    self.file_size = header[10]
    self.uncompressed_size = header[11]
    self.object_count = header[12]
    self.start_timestamp = systemtime_to_timestamp(header[14:22])
    self.stop_timestamp = systemtime_to_timestamp(header[22:30])
    # Read rest of header
    self.fp.read(header[1] - FILE_HEADER_STRUCT.size)
# Buggy code
def __init__(self, filename, channel=1):
    self.fp = open(filename, "wb")
    self.channel = channel
    # Header will be written after log is done
    self.fp.write(b"\x00" * FILE_HEADER_STRUCT.size)
    self.cache = []
    self.cache_size = 0
    self.count_of_objects = 0
    self.uncompressed_size = FILE_HEADER_STRUCT.size
    self.start_timestamp = None
    self.stop_timestamp = None


# Traceback (AssertionError)
Traceback (most recent call last):
File "D:\eclipse-workspace\blf2csv\pythoncan_blf2csv.py", line 7, in <module>
logging = list(logging)
File "C:\Users\my_user_name\AppData\Local\Python\Python36\lib\site-packages\can\io\blf.py", line 129, in __iter__
assert header[0] == b"LOBJ", "Parse error"
AssertionError: Parse error

# Fixed code
def __init__(self, filename, channel=1):
    self.fp = open(filename, "wb")
    self.channel = channel
    # Header will be written after log is done
    self.fp.write(b"\x00" * FILE_HEADER_SIZE)
    self.cache = []
    self.cache_size = 0
    self.count_of_objects = 0
    self.uncompressed_size = FILE_HEADER_SIZE
    self.start_timestamp = None
    self.stop_timestamp = None
# Buggy code
def _add_object(self, obj_type, data, timestamp=None):
    if timestamp is None:
        timestamp = self.stop_timestamp or time.time()
    if self.start_timestamp is None:
        self.start_timestamp = timestamp
    self.stop_timestamp = timestamp
    timestamp = int((timestamp - self.start_timestamp) * 1e9)
    obj_size = HEADER_SIZE + len(data)
    base_header = OBJ_HEADER_BASE_STRUCT.pack(
        b"LOBJ", HEADER_SIZE, 1, obj_size, obj_type
    )
    obj_header = OBJ_HEADER_STRUCT.pack(2, 0, 0, max(timestamp, 0))

    self.cache.append(base_header)
    self.cache.append(obj_header)
    self.cache.append(data)
    padding_size = len(data) % 4
    if padding_size:
        self.cache.append(b"\x00" * padding_size)

    self.cache_size += obj_size + padding_size
    self.count_of_objects += 1
    if self.cache_size >= self.MAX_CACHE_SIZE:
        self._flush()


# Traceback (AssertionError)
Traceback (most recent call last):
File "D:\eclipse-workspace\blf2csv\pythoncan_blf2csv.py", line 7, in <module>
logging = list(logging)
File "C:\Users\my_user_name\AppData\Local\Python\Python36\lib\site-packages\can\io\blf.py", line 129, in __iter__
assert header[0] == b"LOBJ", "Parse error"
AssertionError: Parse error

# Fixed code
def _add_object(self, obj_type, data, timestamp=None):
    if timestamp is None:
        timestamp = self.stop_timestamp or time.time()
    if self.start_timestamp is None:
        self.start_timestamp = timestamp
    self.stop_timestamp = timestamp
    timestamp = int((timestamp - self.start_timestamp) * 1e9)
    header_size = OBJ_HEADER_BASE_STRUCT.size + OBJ_HEADER_V1_STRUCT.size
    obj_size = header_size + len(data)
    base_header = OBJ_HEADER_BASE_STRUCT.pack(
        b"LOBJ", header_size, 1, obj_size, obj_type
    )
    obj_header = OBJ_HEADER_V1_STRUCT.pack(TIME_ONE_NANS, 0, 0, max(timestamp, 0))

    self.cache.append(base_header)
    self.cache.append(obj_header)
    self.cache.append(data)
    padding_size = len(data) % 4
    if padding_size:
        self.cache.append(b"\x00" * padding_size)

    self.cache_size += obj_size + padding_size
    self.count_of_objects += 1
    if self.cache_size >= self.MAX_CACHE_SIZE:
        self._flush()
# Buggy code
def _flush(self):
    """Compresses and writes data in the cache to file."""
    if self.fp.closed:
        return
    cache = b"".join(self.cache)
    if not cache:
        # Nothing to write
        return
    uncompressed_data = cache[: self.MAX_CACHE_SIZE]
    # Save data that comes after max size to next round
    tail = cache[self.MAX_CACHE_SIZE :]
    self.cache = [tail]
    self.cache_size = len(tail)
    compressed_data = zlib.compress(uncompressed_data, self.COMPRESSION_LEVEL)
    obj_size = OBJ_HEADER_STRUCT.size + LOG_CONTAINER_STRUCT.size + len(compressed_data)
    base_header = OBJ_HEADER_BASE_STRUCT.pack(
        b"LOBJ", OBJ_HEADER_BASE_STRUCT.size, 1, obj_size, LOG_CONTAINER
    )
    container_header = LOG_CONTAINER_STRUCT.pack(ZLIB_DEFLATE, len(uncompressed_data))
    self.fp.write(base_header)
    self.fp.write(container_header)
    self.fp.write(compressed_data)
    # Write padding bytes
    self.fp.write(b"\x00" * (obj_size % 4))
    self.uncompressed_size += OBJ_HEADER_STRUCT.size + LOG_CONTAINER_STRUCT.size
    self.uncompressed_size += len(uncompressed_data)


# Traceback (AssertionError)
Traceback (most recent call last):
File "D:\eclipse-workspace\blf2csv\pythoncan_blf2csv.py", line 7, in <module>
logging = list(logging)
File "C:\Users\my_user_name\AppData\Local\Python\Python36\lib\site-packages\can\io\blf.py", line 129, in __iter__
assert header[0] == b"LOBJ", "Parse error"
AssertionError: Parse error

# Fixed code
def _flush(self):
    """Compresses and writes data in the cache to file."""
    if self.fp.closed:
        return
    cache = b"".join(self.cache)
    if not cache:
        # Nothing to write
        return
    uncompressed_data = cache[: self.MAX_CACHE_SIZE]
    # Save data that comes after max size to next round
    tail = cache[self.MAX_CACHE_SIZE :]
    self.cache = [tail]
    self.cache_size = len(tail)
    compressed_data = zlib.compress(uncompressed_data, self.COMPRESSION_LEVEL)
    obj_size = (
        OBJ_HEADER_V1_STRUCT.size + LOG_CONTAINER_STRUCT.size + len(compressed_data)
    )
    base_header = OBJ_HEADER_BASE_STRUCT.pack(
        b"LOBJ", OBJ_HEADER_BASE_STRUCT.size, 1, obj_size, LOG_CONTAINER
    )
    container_header = LOG_CONTAINER_STRUCT.pack(ZLIB_DEFLATE, len(uncompressed_data))
    self.fp.write(base_header)
    self.fp.write(container_header)
    self.fp.write(compressed_data)
    # Write padding bytes
    self.fp.write(b"\x00" * (obj_size % 4))
    self.uncompressed_size += OBJ_HEADER_V1_STRUCT.size + LOG_CONTAINER_STRUCT.size
    self.uncompressed_size += len(uncompressed_data)
# Buggy code
def stop(self):
    """Stops logging and closes the file."""
    if self.fp.closed:
        return
    self._flush()
    filesize = self.fp.tell()
    self.fp.close()

    # Write header in the beginning of the file
    header = [b"LOGG", FILE_HEADER_STRUCT.size, APPLICATION_ID, 0, 0, 0, 2, 6, 8, 1]
    # The meaning of "count of objects read" is unknown
    header.extend([filesize, self.uncompressed_size, self.count_of_objects, 0])
    header.extend(timestamp_to_systemtime(self.start_timestamp))
    header.extend(timestamp_to_systemtime(self.stop_timestamp))
    with open(self.fp.name, "r+b") as f:
        f.write(FILE_HEADER_STRUCT.pack(*header))


# Traceback (AssertionError)
Traceback (most recent call last):
File "D:\eclipse-workspace\blf2csv\pythoncan_blf2csv.py", line 7, in <module>
logging = list(logging)
File "C:\Users\my_user_name\AppData\Local\Python\Python36\lib\site-packages\can\io\blf.py", line 129, in __iter__
assert header[0] == b"LOBJ", "Parse error"
AssertionError: Parse error

# Fixed code
def stop(self):
    """Stops logging and closes the file."""
    if self.fp.closed:
        return
    self._flush()
    filesize = self.fp.tell()
    self.fp.close()

    # Write header in the beginning of the file
    header = [b"LOGG", FILE_HEADER_SIZE, APPLICATION_ID, 0, 0, 0, 2, 6, 8, 1]
    # The meaning of "count of objects read" is unknown
    header.extend([filesize, self.uncompressed_size, self.count_of_objects, 0])
    header.extend(timestamp_to_systemtime(self.start_timestamp))
    header.extend(timestamp_to_systemtime(self.stop_timestamp))
    with open(self.fp.name, "r+b") as f:
        f.write(FILE_HEADER_STRUCT.pack(*header))
# Buggy code
def __init__(self, filename):
    self.csv_file = open(filename, "wt")

    # Write a header row
    self.csv_file.write("timestamp, arbitrationid, flags, dlc, data")


# Traceback (ValueError)
#!shell

(py35_python_can) e:\bitbucket_hg\python-can\bin>python can_logger.py  -f ./temp.txt
Can Logger (Started on 2016-07-19 09:49:10.052735)

enter..
Shutdown Bus and Exit.
exit..
close exit ..
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Python35\lib\threading.py", line 914, in _bootstrap_inner
self.run()
File "C:\Python35\lib\threading.py", line 862, in run
self._target(*self._args, **self._kwargs)
File "e:\bitbucket_hg\python-can\can\notifier.py", line 32, in rx_thread
msg = self.bus.recv(self.timeout)
File "e:\bitbucket_hg\python-can\can\interfaces\pcan.py", line 169, in recv
raise Exception(self._get_formatted_error(result[0]))
Exception: Der PCAN Kanal ist nicht initialisiert oder der Initialisierungsvorgang ist fehlgeschlagen

Exception ignored in: <bound method Printer.__del__ of <can.CAN.Printer object at 0x00000000015C3550>>
Traceback (most recent call last):
File "e:\bitbucket_hg\python-can\can\CAN.py", line 97, in __del__
ValueError: I/O operation on closed file.

(py35_python_can) e:\bitbucket_hg\python-can\bin>

# Fixed code
def __init__(self, filename):
    self.csv_file = open(filename, "wt")

    # Write a header row
    self.csv_file.write(
        "timestamp, arbitration id, extended, remote, error, dlc, data\n"
    )
# Buggy code
def on_message_received(self, msg):
    row = ",".join([msg.timestamp, msg.arbitration_id, msg.flags, msg.dlc, msg.data])
    self.csv_file.write(row + "\n")


# Traceback (ValueError)
#!shell

(py35_python_can) e:\bitbucket_hg\python-can\bin>python can_logger.py  -f ./temp.txt
Can Logger (Started on 2016-07-19 09:49:10.052735)

enter..
Shutdown Bus and Exit.
exit..
close exit ..
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Python35\lib\threading.py", line 914, in _bootstrap_inner
self.run()
File "C:\Python35\lib\threading.py", line 862, in run
self._target(*self._args, **self._kwargs)
File "e:\bitbucket_hg\python-can\can\notifier.py", line 32, in rx_thread
msg = self.bus.recv(self.timeout)
File "e:\bitbucket_hg\python-can\can\interfaces\pcan.py", line 169, in recv
raise Exception(self._get_formatted_error(result[0]))
Exception: Der PCAN Kanal ist nicht initialisiert oder der Initialisierungsvorgang ist fehlgeschlagen

Exception ignored in: <bound method Printer.__del__ of <can.CAN.Printer object at 0x00000000015C3550>>
Traceback (most recent call last):
File "e:\bitbucket_hg\python-can\can\CAN.py", line 97, in __del__
ValueError: I/O operation on closed file.

(py35_python_can) e:\bitbucket_hg\python-can\bin>

# Fixed code
def on_message_received(self, msg):
    row = ",".join(
        [
            str(msg.timestamp),
            hex(msg.arbitration_id),
            "1" if msg.id_type else "0",
            "1" if msg.is_remote_frame else "0",
            "1" if msg.is_error_frame else "0",
            str(msg.dlc),
            base64.b64encode(msg.data).decode("utf8"),
        ]
    )
    self.csv_file.write(row + "\n")
# Buggy code
def __init__(self, bus, listeners, timeout=None):
    """Manages the distribution of **Messages** from a given bus to a
    list of listeners.

    :param bus: The :class:`~can.Bus` to listen too.
    :param listeners: An iterable of :class:`~can.Listeners`
    :param timeout: An optional maximum number of seconds to wait for any message.
    """
    self.listeners = listeners
    self.bus = bus
    self.timeout = timeout

    self.running = threading.Event()
    self.running.set()

    self._reader = threading.Thread(target=self.rx_thread)
    self._reader.daemon = True

    self._reader.start()


# Traceback (ValueError)
#!shell

(py35_python_can) e:\bitbucket_hg\python-can\bin>python can_logger.py  -f ./temp.txt
Can Logger (Started on 2016-07-19 09:49:10.052735)

enter..
Shutdown Bus and Exit.
exit..
close exit ..
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Python35\lib\threading.py", line 914, in _bootstrap_inner
self.run()
File "C:\Python35\lib\threading.py", line 862, in run
self._target(*self._args, **self._kwargs)
File "e:\bitbucket_hg\python-can\can\notifier.py", line 32, in rx_thread
msg = self.bus.recv(self.timeout)
File "e:\bitbucket_hg\python-can\can\interfaces\pcan.py", line 169, in recv
raise Exception(self._get_formatted_error(result[0]))
Exception: Der PCAN Kanal ist nicht initialisiert oder der Initialisierungsvorgang ist fehlgeschlagen

Exception ignored in: <bound method Printer.__del__ of <can.CAN.Printer object at 0x00000000015C3550>>
Traceback (most recent call last):
File "e:\bitbucket_hg\python-can\can\CAN.py", line 97, in __del__
ValueError: I/O operation on closed file.

(py35_python_can) e:\bitbucket_hg\python-can\bin>

# Fixed code
def __init__(self, bus, listeners, timeout=None):
    """Manages the distribution of **Messages** from a given bus to a
    list of listeners.

    :param bus: The :ref:`bus` to listen too.
    :param listeners: An iterable of :class:`~can.Listeners`
    :param timeout: An optional maximum number of seconds to wait for any message.
    """
    self.listeners = listeners
    self.bus = bus
    self.timeout = timeout

    self.running = threading.Event()
    self.running.set()

    self._reader = threading.Thread(target=self.rx_thread)
    self._reader.daemon = True

    self._reader.start()
# Buggy code
def stop(self):
    self.running.clear()
    if self.timeout is not None:
        self._reader.join(self.timeout + 0.1)


# Traceback (ValueError)
#!shell

(py35_python_can) e:\bitbucket_hg\python-can\bin>python can_logger.py  -f ./temp.txt
Can Logger (Started on 2016-07-19 09:49:10.052735)

enter..
Shutdown Bus and Exit.
exit..
close exit ..
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Python35\lib\threading.py", line 914, in _bootstrap_inner
self.run()
File "C:\Python35\lib\threading.py", line 862, in run
self._target(*self._args, **self._kwargs)
File "e:\bitbucket_hg\python-can\can\notifier.py", line 32, in rx_thread
msg = self.bus.recv(self.timeout)
File "e:\bitbucket_hg\python-can\can\interfaces\pcan.py", line 169, in recv
raise Exception(self._get_formatted_error(result[0]))
Exception: Der PCAN Kanal ist nicht initialisiert oder der Initialisierungsvorgang ist fehlgeschlagen

Exception ignored in: <bound method Printer.__del__ of <can.CAN.Printer object at 0x00000000015C3550>>
Traceback (most recent call last):
File "e:\bitbucket_hg\python-can\can\CAN.py", line 97, in __del__
ValueError: I/O operation on closed file.

(py35_python_can) e:\bitbucket_hg\python-can\bin>

# Fixed code
def stop(self):
    """Stop notifying Listeners when new :class:`~can.Message` objects arrive
    and call :meth:`~can.Listener.stop` on each Listener."""
    self.running.clear()
    if self.timeout is not None:
        self._reader.join(self.timeout + 0.1)
# Buggy code
def rx_thread(self):
    while self.running.is_set():
        msg = self.bus.recv(self.timeout)
        if msg is not None:
            for callback in self.listeners:
                callback(msg)


# Traceback (ValueError)
#!shell

(py35_python_can) e:\bitbucket_hg\python-can\bin>python can_logger.py  -f ./temp.txt
Can Logger (Started on 2016-07-19 09:49:10.052735)

enter..
Shutdown Bus and Exit.
exit..
close exit ..
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Python35\lib\threading.py", line 914, in _bootstrap_inner
self.run()
File "C:\Python35\lib\threading.py", line 862, in run
self._target(*self._args, **self._kwargs)
File "e:\bitbucket_hg\python-can\can\notifier.py", line 32, in rx_thread
msg = self.bus.recv(self.timeout)
File "e:\bitbucket_hg\python-can\can\interfaces\pcan.py", line 169, in recv
raise Exception(self._get_formatted_error(result[0]))
Exception: Der PCAN Kanal ist nicht initialisiert oder der Initialisierungsvorgang ist fehlgeschlagen

Exception ignored in: <bound method Printer.__del__ of <can.CAN.Printer object at 0x00000000015C3550>>
Traceback (most recent call last):
File "e:\bitbucket_hg\python-can\can\CAN.py", line 97, in __del__
ValueError: I/O operation on closed file.

(py35_python_can) e:\bitbucket_hg\python-can\bin>

# Fixed code
def rx_thread(self):
    while self.running.is_set():
        msg = self.bus.recv(self.timeout)
        if msg is not None:
            for callback in self.listeners:
                callback(msg)

    for listener in self.listeners:
        listener.stop()
# Buggy code
async def get(self):
    user = self.current_user
    if user is None:
        # whoami can be accessed via oauth token
        user = self.get_current_user_oauth_token()
    if user is None:
        raise web.HTTPError(403)
    self.write(json.dumps(self.user_model(user)))


# Traceback (AttributeError)
Uncaught exception GET /hub/api/user (172.17.0.2)
HTTPServerRequest(protocol='http', host='172.17.0.2:8081', method='GET', uri='/hub/api/user', version='HTTP/1.1', remote_ip='172.17.0.2')
Traceback (most recent call last):
File "/usr/local/lib/python3.6/dist-packages/tornado/web.py", line 1703, in _execute
result = await result
File "/usr/local/lib/python3.6/dist-packages/jupyterhub/apihandlers/users.py", line 38, in get
self.write(json.dumps(self.user_model(user)))
File "/usr/local/lib/python3.6/dist-packages/jupyterhub/apihandlers/base.py", line 193, in user_model
'groups': [g.name for g in user.groups],
AttributeError: 'Service' object has no attribute 'groups'

# Fixed code
async def get(self):
    user = self.current_user
    if user is None:
        # whoami can be accessed via oauth token
        user = self.get_current_user_oauth_token()
    if user is None:
        raise web.HTTPError(403)
    if isinstance(user, orm.Service):
        model = self.service_model(user)
    else:
        model = self.user_model(user)
    self.write(json.dumps(model))
# Buggy code
async def shutdown_cancel_tasks(self, sig):
    """Cancel all other tasks of the event loop and initiate cleanup"""
    self.log.critical("Received signal %s, initiating shutdown...", sig.name)
    tasks = [
        t for t in asyncio.Task.all_tasks() if t is not asyncio.Task.current_task()
    ]

    if tasks:
        self.log.debug("Cancelling pending tasks")
        [t.cancel() for t in tasks]

        try:
            await asyncio.wait(tasks)
        except asyncio.CancelledError as e:
            self.log.debug("Caught Task CancelledError. Ignoring")
        except StopAsyncIteration as e:
            self.log.error("Caught StopAsyncIteration Exception", exc_info=True)

        tasks = [t for t in asyncio.Task.all_tasks()]
        for t in tasks:
            self.log.debug("Task status: %s", t)
    await self.cleanup()
    asyncio.get_event_loop().stop()


# Traceback (AttributeError)
^C[C 2020-12-02 16:16:45.801 JupyterHub app:2810] Received signal SIGINT, initiating shutdown...
ERROR:asyncio:Task exception was never retrieved
future: <Task finished name='Task-8' coro=<JupyterHub.shutdown_cancel_tasks() done, defined at /opt/miniconda3/envs/jupyterhub/lib/python3.9/site-packages/jupyterhub/app.py:2808> exception=AttributeError("type object '_asyncio.Task' has no attribute 'all_tasks'")>
Traceback (most recent call last):
File "/opt/miniconda3/envs/jupyterhub/lib/python3.9/site-packages/jupyterhub/app.py", line 2812, in shutdown_cancel_tasks
t for t in asyncio.Task.all_tasks() if t is not asyncio.Task.current_task()
AttributeError: type object '_asyncio.Task' has no attribute 'all_tasks'

# Fixed code
async def shutdown_cancel_tasks(self, sig):
    """Cancel all other tasks of the event loop and initiate cleanup"""
    self.log.critical("Received signal %s, initiating shutdown...", sig.name)
    tasks = [t for t in asyncio_all_tasks() if t is not asyncio_current_task()]

    if tasks:
        self.log.debug("Cancelling pending tasks")
        [t.cancel() for t in tasks]

        try:
            await asyncio.wait(tasks)
        except asyncio.CancelledError as e:
            self.log.debug("Caught Task CancelledError. Ignoring")
        except StopAsyncIteration as e:
            self.log.error("Caught StopAsyncIteration Exception", exc_info=True)

        tasks = [t for t in asyncio_all_tasks()]
        for t in tasks:
            self.log.debug("Task status: %s", t)
    await self.cleanup()
    asyncio.get_event_loop().stop()
# Buggy code
def get(self, token):
    orm_token = orm.APIToken.find(self.db, token)
    if orm_token is None:
        orm_token = orm.OAuthAccessToken.find(self.db, token)
    if orm_token is None:
        raise web.HTTPError(404)
    if orm_token.user:
        model = self.user_model(self.users[orm_token.user])
    elif orm_token.service:
        model = self.service_model(orm_token.service)
    self.write(json.dumps(model))


# Traceback (AttributeError)
Traceback (most recent call last):
File "/usr/lib64/python3.4/site-packages/tornado/web.py", line 1509, in _execute
result = method(*self.path_args, **self.path_kwargs)
File "/usr/lib/python3.4/site-packages/jupyterhub/utils.py", line 193, in decorated
return method(self, *args, **kwargs)
File "/usr/lib/python3.4/site-packages/jupyterhub/apihandlers/auth.py", line 27, in get
elif orm_token.service:
AttributeError: 'OAuthAccessToken' object has no attribute 'service'

# Fixed code
def get(self, token):
    orm_token = orm.APIToken.find(self.db, token)
    if orm_token is None:
        orm_token = orm.OAuthAccessToken.find(self.db, token)
    if orm_token is None:
        raise web.HTTPError(404)
    if orm_token.user:
        model = self.user_model(self.users[orm_token.user])
    elif orm_token.service:
        model = self.service_model(orm_token.service)
    else:
        self.log.warning("%s has no user or service. Deleting..." % orm_token)
        self.db.delete(orm_token)
        self.db.commit()
        raise web.HTTPError(404)
    self.write(json.dumps(model))
# Buggy code
def save_token(self, access_token):
    """
    Stores an access token in the database.

    :param access_token: An instance of :class:`oauth2.datatype.AccessToken`.

    """

    user = self.db.query(orm.User).filter(orm.User.id == access_token.user_id).first()
    orm_access_token = orm.OAuthAccessToken(
        client_id=access_token.client_id,
        grant_type=access_token.grant_type,
        expires_at=access_token.expires_at,
        refresh_token=access_token.refresh_token,
        refresh_expires_at=access_token.refresh_expires_at,
        token=access_token.token,
        user=user,
    )
    self.db.add(orm_access_token)
    self.db.commit()


# Traceback (AttributeError)
Traceback (most recent call last):
File "/usr/lib64/python3.4/site-packages/tornado/web.py", line 1509, in _execute
result = method(*self.path_args, **self.path_kwargs)
File "/usr/lib/python3.4/site-packages/jupyterhub/utils.py", line 193, in decorated
return method(self, *args, **kwargs)
File "/usr/lib/python3.4/site-packages/jupyterhub/apihandlers/auth.py", line 27, in get
elif orm_token.service:
AttributeError: 'OAuthAccessToken' object has no attribute 'service'

# Fixed code
def save_token(self, access_token):
    """
    Stores an access token in the database.

    :param access_token: An instance of :class:`oauth2.datatype.AccessToken`.

    """

    user = self.db.query(orm.User).filter(orm.User.id == access_token.user_id).first()
    if user is None:
        raise ValueError("No user for access token: %s" % access_token.user_id)
    orm_access_token = orm.OAuthAccessToken(
        generated=True,
        client_id=access_token.client_id,
        grant_type=access_token.grant_type,
        expires_at=access_token.expires_at,
        refresh_token=access_token.refresh_token,
        refresh_expires_at=access_token.refresh_expires_at,
        token=access_token.token,
        user=user,
    )
    self.db.add(orm_access_token)
    self.db.commit()
# Buggy code
def start(self):
    """Start a managed service"""
    if not self.managed:
        raise RuntimeError("Cannot start unmanaged service %s" % self)
    self.log.info("Starting service %r: %r", self.name, self.command)
    env = {}
    env.update(self.environment)

    env["JUPYTERHUB_SERVICE_NAME"] = self.name
    env["JUPYTERHUB_API_TOKEN"] = self.api_token
    env["JUPYTERHUB_API_URL"] = self.hub_api_url
    env["JUPYTERHUB_BASE_URL"] = self.base_url
    env["JUPYTERHUB_SERVICE_PREFIX"] = self.server.base_url
    env["JUPYTERHUB_SERVICE_URL"] = self.url

    self.spawner = _ServiceSpawner(
        cmd=self.command,
        environment=env,
        api_token=self.api_token,
        cwd=self.cwd,
        user=_MockUser(
            name=self.user,
            service=self,
            server=self.orm.server,
        ),
    )
    self.spawner.start()
    self.proc = self.spawner.proc
    self.spawner.add_poll_callback(self._proc_stopped)
    self.spawner.start_polling()


# Traceback (AttributeError)
[C 2016-09-20 02:28:37.026 JupyterHub app:1444] Failed to start service cull-idle
Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/jupyterhub/app.py", line 1442, in start
yield service.start()
File "/usr/local/lib/python3.5/dist-packages/jupyterhub/services/service.py", line 228, in start
env['JUPYTERHUB_SERVICE_PREFIX'] = self.server.base_url
AttributeError: 'NoneType' object has no attribute 'base_url'

# Fixed code
def start(self):
    """Start a managed service"""
    if not self.managed:
        raise RuntimeError("Cannot start unmanaged service %s" % self)
    self.log.info("Starting service %r: %r", self.name, self.command)
    env = {}
    env.update(self.environment)

    env["JUPYTERHUB_SERVICE_NAME"] = self.name
    env["JUPYTERHUB_API_TOKEN"] = self.api_token
    env["JUPYTERHUB_API_URL"] = self.hub_api_url
    env["JUPYTERHUB_BASE_URL"] = self.base_url
    if self.url:
        env["JUPYTERHUB_SERVICE_URL"] = self.url
        env["JUPYTERHUB_SERVICE_PREFIX"] = self.server.base_url

    self.spawner = _ServiceSpawner(
        cmd=self.command,
        environment=env,
        api_token=self.api_token,
        cwd=self.cwd,
        user=_MockUser(
            name=self.user,
            service=self,
            server=self.orm.server,
        ),
    )
    self.spawner.start()
    self.proc = self.spawner.proc
    self.spawner.add_poll_callback(self._proc_stopped)
    self.spawner.start_polling()