gurudesh/pytracebugs huggingface dataset:
# Buggy code
def blacklistExport():
    path = request.form.get("file")
    force = request.form.get("force")
    if matchFilePath(path):
        if (force == "df") and (os.path.isfile(path)):
            status = ["bl_file_already_exists", "warning"]
        else:
            if os.path.isfile(path):
                os.remove(path)
            exportBlacklist(path)
            status = ["bl_exported", "success"]
    else:
        status = ["invalid_path", "error"]
    return render_template("admin.html", status=status)


# Traceback (TypeError)
Starting vendor
Traceback (most recent call last):                           ] 0/1440
File ".../cve-search/db_mgmt_vendorstatements.py", line 83, in <module>
bulk.find({'id': statement['id']}).upsert().update({'id': statement['id']}, {"$set":{'statement': statement['statement'], 'id': statement['id'], 'organization': statement['organization'], 'contributor': statement['contributor'], 'lastmodified': statement['lastmodified']}})
TypeError: update() takes 2 positional arguments but 3 were given

# Fixed code
def blacklistExport():
    file = request.files["file"]
    filename = secure_filename(file.filename)
    force = request.form.get("force")
    if (force == "df") and (os.path.isfile(filename)):
        status = ["bl_file_already_exists", "warning"]
    else:
        if os.path.isfile(filename):
            os.remove(filename)
        exportBlacklist(filename)
        status = ["bl_exported", "success"]
    return render_template("admin.html", status=status)
# Buggy code
def promptNewPass():
    password = getpass.getpass("New password:")
    verify = getpass.getpass("Verify password:")
    if password != verify:
        sys.exit("The passwords don't match!")
    # generate new salt
    salt = os.urandom(32)
    keyset = {"password": buildPassword(password, salt=salt), "salt": salt}
    return keyset


# Traceback (pymongo.errors.DuplicateKeyError)
python3 ./db_mgmt.py -p

Database population started

Year 2002 imported.

Traceback (most recent call last):

File "./db_mgmt.py", line 186, in <module>

ret = collection.insert(ch.cves)

File "/usr/local/lib/python3.4/site-packages/pymongo/collection.py", line 410, in insert

_check_write_command_response(results)

File "/usr/local/lib/python3.4/site-packages/pymongo/helpers.py", line 198, in _check_write_command_response

raise DuplicateKeyError(error.get("errmsg"), 11000, error)

pymongo.errors.DuplicateKeyError: insertDocument :: caused by :: 11000 E11000 duplicate key error index: cvedb.cves.$_id_  dup key: { : ObjectId('54c7b9d737b9ad76355dcd4b') }

# Fixed code
def promptNewPass():
    password = getpass.getpass("New password:")
    verify = getpass.getpass("Verify password:")
    if password != verify:
        sys.exit(exits["passwordMatch"])
    return pbkdf2_sha256.encrypt(password, rounds=rounds, salt_size=saltLength)
# Buggy code
def masterLogin():
    master = input("Master account username: ")
    masterPass = buildPassword(getpass.getpass("Master password:"), user=master)
    if (
        collection.find(
            {"username": master, "password": masterPass, "master": True}
        ).count()
        == 0
    ):
        sys.exit("Master user/password combination does not exist")
    return True


# Traceback (pymongo.errors.DuplicateKeyError)
python3 ./db_mgmt.py -p

Database population started

Year 2002 imported.

Traceback (most recent call last):

File "./db_mgmt.py", line 186, in <module>

ret = collection.insert(ch.cves)

File "/usr/local/lib/python3.4/site-packages/pymongo/collection.py", line 410, in insert

_check_write_command_response(results)

File "/usr/local/lib/python3.4/site-packages/pymongo/helpers.py", line 198, in _check_write_command_response

raise DuplicateKeyError(error.get("errmsg"), 11000, error)

pymongo.errors.DuplicateKeyError: insertDocument :: caused by :: 11000 E11000 duplicate key error index: cvedb.cves.$_id_  dup key: { : ObjectId('54c7b9d737b9ad76355dcd4b') }

# Fixed code
def masterLogin():
    master = input("Master account username: ")
    if verifyPass(getpass.getpass("Master password:"), master):
        if collection.find({"username": master, "master": True}).count() == 0:
            sys.exit(exits["noMaster"])
    else:
        sys.exit("Master user/password combination does not exist")
    return True
# Buggy code
def isLastAdmin(user):
    if len(list(collection.find({"username": {"$ne": user}, "master": True}))) == 0:
        sys.exit(
            "This user is the last admin in the database and thus can not be removed"
        )


# Traceback (pymongo.errors.DuplicateKeyError)
python3 ./db_mgmt.py -p

Database population started

Year 2002 imported.

Traceback (most recent call last):

File "./db_mgmt.py", line 186, in <module>

ret = collection.insert(ch.cves)

File "/usr/local/lib/python3.4/site-packages/pymongo/collection.py", line 410, in insert

_check_write_command_response(results)

File "/usr/local/lib/python3.4/site-packages/pymongo/helpers.py", line 198, in _check_write_command_response

raise DuplicateKeyError(error.get("errmsg"), 11000, error)

pymongo.errors.DuplicateKeyError: insertDocument :: caused by :: 11000 E11000 duplicate key error index: cvedb.cves.$_id_  dup key: { : ObjectId('54c7b9d737b9ad76355dcd4b') }

# Fixed code
def isLastAdmin(user):
    if len(list(collection.find({"username": {"$ne": user}, "master": True}))) == 0:
        sys.exit(exits["lastMaster"])
# Buggy code
def login_check():
    users = db.mgmt_users
    # validate username and password
    username = request.form.get("username")
    # get salt
    if users.find({"username": username}).count() > 0:
        if users.find({"username": username, "salt": {"$exists": True}}).count() > 0:
            salt = (list(users.find({"username": username}))[0])["salt"]
        else:
            return render_template("login.html", status=["outdated_database", "error"])
    else:
        salt = bytearray()
    password = hashlib.sha256(
        salt + bytes(request.form.get("password"), "utf-8")
    ).hexdigest()
    person = User.get(username)
    if person and person.password == password:
        login_user(person)
        return render_template("admin.html", status=["logged_in", "success"])
    else:
        return render_template("login.html", status=["wrong_combination", "warning"])


# Traceback (pymongo.errors.DuplicateKeyError)
python3 ./db_mgmt.py -p

Database population started

Year 2002 imported.

Traceback (most recent call last):

File "./db_mgmt.py", line 186, in <module>

ret = collection.insert(ch.cves)

File "/usr/local/lib/python3.4/site-packages/pymongo/collection.py", line 410, in insert

_check_write_command_response(results)

File "/usr/local/lib/python3.4/site-packages/pymongo/helpers.py", line 198, in _check_write_command_response

raise DuplicateKeyError(error.get("errmsg"), 11000, error)

pymongo.errors.DuplicateKeyError: insertDocument :: caused by :: 11000 E11000 duplicate key error index: cvedb.cves.$_id_  dup key: { : ObjectId('54c7b9d737b9ad76355dcd4b') }

# Fixed code
def login_check():
    users = db.mgmt_users
    # validate username and password
    username = request.form.get("username")
    password = request.form.get("password")
    person = User.get(username)
    try:
        if person and pbkdf2_sha256.verify(password, person.password):
            login_user(person)
            return render_template("admin.html", status=["logged_in", "success"])
        else:
            return render_template(
                "login.html", status=["wrong_combination", "warning"]
            )
    except:
        return render_template("login.html", status=["outdated_database", "error"])
# Buggy code
def _parent_id(self):
    """
    Return the id of the course or group that spawned this discussion topic.

    :rtype: int
    """
    if hasattr(self, "course_id"):
        return self.course_id
    elif hasattr(self, "group_id"):
        return self.group_id
    else:
        raise ValueError("Discussion Topic does not have a course_id or group_id")


# Traceback (ValueError)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-15-667b0a4b45f2> in <module>
2 announcements = canvas.get_announcements(context_codes=['course_{}'.format(course_id)])
3 a = announcements[0]
----> 4 a.update()

~/opt/anaconda3/lib/python3.7/site-packages/canvasapi/discussion_topic.py in update(self, **kwargs)
309             "PUT",
310             "{}s/{}/discussion_topics/{}".format(
--> 311                 self._parent_type, self._parent_id, self.id
312             ),
313             _kwargs=combine_kwargs(**kwargs),

~/opt/anaconda3/lib/python3.7/site-packages/canvasapi/canvas_object.py in __getattribute__(self, name)
15
16     def __getattribute__(self, name):
---> 17         return super(CanvasObject, self).__getattribute__(name)
18
19     def __init__(self, requester, attributes):

~/opt/anaconda3/lib/python3.7/site-packages/canvasapi/discussion_topic.py in _parent_type(self)
34             return "group"
35         else:
---> 36             raise ValueError("Discussion Topic does not have a course_id or group_id")
37
38     def delete(self, **kwargs):

ValueError: Discussion Topic does not have a course_id or group_id

# Fixed code
def _parent_id(self):
    """
    Return the id of the course or group that spawned this discussion topic.

    :rtype: int
    """
    if hasattr(self, "course_id"):
        return self.course_id
    elif hasattr(self, "group_id"):
        return self.group_id
    elif hasattr(self, "context_code"):
        if self.context_code.startswith("course_"):
            self.course_id = self.context_code.split("_")[1]
            return self.course_id
        elif self.context_code.startswith("group_"):
            self.group_id = self.context_code.split("_")[1]
            return self.group_id
    else:
        raise ValueError("Discussion Topic does not have a course_id or group_id")
# Buggy code
def _parent_type(self):
    """
    Return whether the discussion topic was spawned from a course or group.

    :rtype: str
    """
    if hasattr(self, "course_id"):
        return "course"
    elif hasattr(self, "group_id"):
        return "group"
    else:
        raise ValueError("Discussion Topic does not have a course_id or group_id")


# Traceback (ValueError)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-15-667b0a4b45f2> in <module>
2 announcements = canvas.get_announcements(context_codes=['course_{}'.format(course_id)])
3 a = announcements[0]
----> 4 a.update()

~/opt/anaconda3/lib/python3.7/site-packages/canvasapi/discussion_topic.py in update(self, **kwargs)
309             "PUT",
310             "{}s/{}/discussion_topics/{}".format(
--> 311                 self._parent_type, self._parent_id, self.id
312             ),
313             _kwargs=combine_kwargs(**kwargs),

~/opt/anaconda3/lib/python3.7/site-packages/canvasapi/canvas_object.py in __getattribute__(self, name)
15
16     def __getattribute__(self, name):
---> 17         return super(CanvasObject, self).__getattribute__(name)
18
19     def __init__(self, requester, attributes):

~/opt/anaconda3/lib/python3.7/site-packages/canvasapi/discussion_topic.py in _parent_type(self)
34             return "group"
35         else:
---> 36             raise ValueError("Discussion Topic does not have a course_id or group_id")
37
38     def delete(self, **kwargs):

ValueError: Discussion Topic does not have a course_id or group_id

# Fixed code
def _parent_type(self):
    """
    Return whether the discussion topic was spawned from a course or group.

    :rtype: str
    """
    if hasattr(self, "course_id"):
        return "course"
    elif hasattr(self, "group_id"):
        return "group"
    elif hasattr(self, "context_code"):
        if self.context_code.startswith("course"):
            return "course"
        elif self.context_code.startswith("group"):
            return "group"
    else:
        raise ValueError("Discussion Topic does not have a course_id or group_id")
# Buggy code
def clean_headers(headers):
    """
    Sanitize a dictionary containing HTTP headers of sensitive values.

    :param headers: The headers to sanitize.
    :type headers: dict
    :returns: A list of headers without sensitive information stripped out.
    :rtype: dict
    """
    cleaned_headers = headers.copy()

    authorization_header = headers.get("Authorization")
    if authorization_header:
        # Grab the actual token (not the "Bearer" prefix)
        _, token = authorization_header.split(" ")

        # Trim all but the last four characters
        sanitized = "****" + token[-4:]

        cleaned_headers["Authorization"] = sanitized

    return cleaned_headers


# Traceback (ValueError)
Traceback (most recent call last):
File "_test.py", line 42, in <module>
course = canvas.get_course(COURSE_ID)
File "<YANKED>canvasapi/canvas.py", line 603, in get_course
"GET", uri_str.format(course_id), _kwargs=combine_kwargs(**kwargs)
File "<YANKED>canvasapi/requester.py", line 191, in request
"Headers: {headers}".format(headers=pformat(clean_headers(headers)))
File "<YANKED>canvasapi/util.py", line 248, in clean_headers
_, token = authorization_header.split(" ")
ValueError: too many values to unpack (expected 2)

# Fixed code
def clean_headers(headers):
    """
    Sanitize a dictionary containing HTTP headers of sensitive values.

    :param headers: The headers to sanitize.
    :type headers: dict
    :returns: A list of headers without sensitive information stripped out.
    :rtype: dict
    """
    cleaned_headers = headers.copy()

    authorization_header = headers.get("Authorization")
    if authorization_header:
        sanitized = "****" + authorization_header[-4:]
        cleaned_headers["Authorization"] = sanitized

    return cleaned_headers
# Buggy code
def __init__(self, base_url, access_token):
    """
    :param base_url: The base URL of the Canvas instance's API.
    :type base_url: str
    :param access_token: The API key to authenticate requests with.
    :type access_token: str
    """
    new_url = get_institution_url(base_url)

    if "api/v1" in base_url:
        warnings.warn(
            "`base_url` no longer requires an API version be specified. "
            "Rewriting `base_url` to {}".format(new_url),
            DeprecationWarning,
        )
    base_url = new_url + "/api/v1/"

    self.__requester = Requester(base_url, access_token)


# Traceback (AttributeError)
a.create_course(course={'name': 'JSA_TST1337_Jesse_McBride'})
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/local/lib/python2.7/site-packages/canvasapi/account.py", line 77, in create_course
return Course(self._requester, response.json())
File "/usr/local/lib/python2.7/site-packages/canvasapi/canvas_object.py", line 28, in __init__
self.set_attributes(attributes)
File "/usr/local/lib/python2.7/site-packages/canvasapi/canvas_object.py", line 68, in set_attributes
for attribute, value in attributes.items():
AttributeError: 'list' object has no attribute 'items'

# Fixed code
def __init__(self, base_url, access_token):
    """
    :param base_url: The base URL of the Canvas instance's API.
    :type base_url: str
    :param access_token: The API key to authenticate requests with.
    :type access_token: str
    """
    new_url = get_institution_url(base_url)

    if "api/v1" in base_url:
        warnings.warn(
            "`base_url` no longer requires an API version be specified. "
            "Rewriting `base_url` to {}".format(new_url),
            DeprecationWarning,
        )

    if "http://" in base_url:
        warnings.warn(
            "Canvas may respond unexpectedly when making requests to HTTP "
            "URLs. If possible, please use HTTPS.",
            UserWarning,
        )
    base_url = new_url + "/api/v1/"

    self.__requester = Requester(base_url, access_token)
# Buggy code
def wait_for_run_completion(self, timeout=None):
    timeout = timeout or datetime.datetime.max - datetime.datetime.min
    return self._client.wait_for_run_completion(self.run_id, timeout)


# Traceback (AttributeError)
AttributeError
Traceback (most recent call last)
<ipython-input-8-8ebf2be6196c> in <module>
1 client = kfp.Client(host='2c688415e5fe965e-dot-us-central2.pipelines.googleusercontent.com')
----> 2 client.wait_for_run_completion(run_id=run_result.run_id, timeout=36000)

~/Library/Python/3.7/lib/python/site-packages/kfp/_client.py in wait_for_run_completion(self, run_id, timeout)
597     while status is None or status.lower() not in ['succeeded', 'failed', 'skipped', 'error']:
598       get_run_response = self._run_api.get_run(run_id=run_id)
--> 599       status = get_run_response.run.status
600       elapsed_time = (datetime.now() - start_time).seconds
601       logging.info('Waiting for the job to complete...')

AttributeError: 'NoneType' object has no attribute 'status'

# Fixed code
def wait_for_run_completion(self, timeout=None):
    timeout = timeout or datetime.timedelta.max
    return self._client.wait_for_run_completion(self.run_id, timeout)
# Buggy code
def create_artifact_with_type(
    store,
    uri: str,
    type_name: str,
    properties: dict = None,
    type_properties: dict = None,
) -> metadata_store_pb2.Artifact:
    artifact_type = get_or_create_artifact_type(
        store=store,
        type_name=type_name,
        properties=type_properties,
    )
    artifact = metadata_store_pb2.Artifact(
        uri=uri,
        type_id=artifact_type.id,
        properties=properties,
    )
    artifact.id = store.put_artifacts([artifact])[0]
    return artifact


# Traceback (TypeError)
Kubernetes Pod event:  MODIFIED file-passing-pipelines-mbzrz-3001099438 1555702
Traceback (most recent call last):
File "/kfp/metadata_writer/metadata_writer.py", line 183, in <module>
KFP_POD_NAME_EXECUTION_PROPERTY_NAME: pod_name,
File "/kfp/metadata_writer/metadata_helpers.py", line 280, in create_new_execution_in_existing_run_context
custom_properties=custom_properties,
TypeError: create_new_execution_in_existing_context() got an unexpected keyword argument 'custom_properties'

# Fixed code
def create_artifact_with_type(
    store,
    uri: str,
    type_name: str,
    properties: dict = None,
    type_properties: dict = None,
    custom_properties: dict = None,
) -> metadata_store_pb2.Artifact:
    artifact_type = get_or_create_artifact_type(
        store=store,
        type_name=type_name,
        properties=type_properties,
    )
    artifact = metadata_store_pb2.Artifact(
        uri=uri,
        type_id=artifact_type.id,
        properties=properties,
        custom_properties=custom_properties,
    )
    artifact.id = store.put_artifacts([artifact])[0]
    return artifact
# Buggy code
def create_execution_with_type(
    store,
    type_name: str,
    properties: dict = None,
    type_properties: dict = None,
) -> metadata_store_pb2.Execution:
    execution_type = get_or_create_execution_type(
        store=store,
        type_name=type_name,
        properties=type_properties,
    )
    execution = metadata_store_pb2.Execution(
        type_id=execution_type.id,
        properties=properties,
    )
    execution.id = store.put_executions([execution])[0]
    return execution


# Traceback (TypeError)
Kubernetes Pod event:  MODIFIED file-passing-pipelines-mbzrz-3001099438 1555702
Traceback (most recent call last):
File "/kfp/metadata_writer/metadata_writer.py", line 183, in <module>
KFP_POD_NAME_EXECUTION_PROPERTY_NAME: pod_name,
File "/kfp/metadata_writer/metadata_helpers.py", line 280, in create_new_execution_in_existing_run_context
custom_properties=custom_properties,
TypeError: create_new_execution_in_existing_context() got an unexpected keyword argument 'custom_properties'

# Fixed code
def create_execution_with_type(
    store,
    type_name: str,
    properties: dict = None,
    type_properties: dict = None,
    custom_properties: dict = None,
) -> metadata_store_pb2.Execution:
    execution_type = get_or_create_execution_type(
        store=store,
        type_name=type_name,
        properties=type_properties,
    )
    execution = metadata_store_pb2.Execution(
        type_id=execution_type.id,
        properties=properties,
        custom_properties=custom_properties,
    )
    execution.id = store.put_executions([execution])[0]
    return execution
# Buggy code
def create_context_with_type(
    store,
    context_name: str,
    type_name: str,
    properties: dict = None,
    type_properties: dict = None,
) -> metadata_store_pb2.Context:
    # ! Context_name must be unique
    context_type = get_or_create_context_type(
        store=store,
        type_name=type_name,
        properties=type_properties,
    )
    context = metadata_store_pb2.Context(
        name=context_name,
        type_id=context_type.id,
        properties=properties,
    )
    context.id = store.put_contexts([context])[0]
    return context


# Traceback (TypeError)
Kubernetes Pod event:  MODIFIED file-passing-pipelines-mbzrz-3001099438 1555702
Traceback (most recent call last):
File "/kfp/metadata_writer/metadata_writer.py", line 183, in <module>
KFP_POD_NAME_EXECUTION_PROPERTY_NAME: pod_name,
File "/kfp/metadata_writer/metadata_helpers.py", line 280, in create_new_execution_in_existing_run_context
custom_properties=custom_properties,
TypeError: create_new_execution_in_existing_context() got an unexpected keyword argument 'custom_properties'

# Fixed code
def create_context_with_type(
    store,
    context_name: str,
    type_name: str,
    properties: dict = None,
    type_properties: dict = None,
    custom_properties: dict = None,
) -> metadata_store_pb2.Context:
    # ! Context_name must be unique
    context_type = get_or_create_context_type(
        store=store,
        type_name=type_name,
        properties=type_properties,
    )
    context = metadata_store_pb2.Context(
        name=context_name,
        type_id=context_type.id,
        properties=properties,
        custom_properties=custom_properties,
    )
    context.id = store.put_contexts([context])[0]
    return context
# Buggy code
def get_or_create_context_with_type(
    store,
    context_name: str,
    type_name: str,
    properties: dict = None,
    type_properties: dict = None,
) -> metadata_store_pb2.Context:
    try:
        context = get_context_by_name(store, context_name)
    except:
        context = create_context_with_type(
            store=store,
            context_name=context_name,
            type_name=type_name,
            properties=properties,
            type_properties=type_properties,
        )
        return context

    # Verifying that the context has the expected type name
    context_types = store.get_context_types_by_id([context.type_id])
    assert len(context_types) == 1
    if context_types[0].name != type_name:
        raise RuntimeError(
            'Context "{}" was found, but it has type "{}" instead of "{}"'.format(
                context_name, context_types[0].name, type_name
            )
        )
    return context


# Traceback (TypeError)
Kubernetes Pod event:  MODIFIED file-passing-pipelines-mbzrz-3001099438 1555702
Traceback (most recent call last):
File "/kfp/metadata_writer/metadata_writer.py", line 183, in <module>
KFP_POD_NAME_EXECUTION_PROPERTY_NAME: pod_name,
File "/kfp/metadata_writer/metadata_helpers.py", line 280, in create_new_execution_in_existing_run_context
custom_properties=custom_properties,
TypeError: create_new_execution_in_existing_context() got an unexpected keyword argument 'custom_properties'

# Fixed code
def get_or_create_context_with_type(
    store,
    context_name: str,
    type_name: str,
    properties: dict = None,
    type_properties: dict = None,
    custom_properties: dict = None,
) -> metadata_store_pb2.Context:
    try:
        context = get_context_by_name(store, context_name)
    except:
        context = create_context_with_type(
            store=store,
            context_name=context_name,
            type_name=type_name,
            properties=properties,
            type_properties=type_properties,
            custom_properties=custom_properties,
        )
        return context

    # Verifying that the context has the expected type name
    context_types = store.get_context_types_by_id([context.type_id])
    assert len(context_types) == 1
    if context_types[0].name != type_name:
        raise RuntimeError(
            'Context "{}" was found, but it has type "{}" instead of "{}"'.format(
                context_name, context_types[0].name, type_name
            )
        )
    return context
# Buggy code
def create_new_execution_in_existing_context(
    store,
    execution_type_name: str,
    context_id: int,
    properties: dict = None,
    execution_type_properties: dict = None,
) -> metadata_store_pb2.Execution:
    execution = create_execution_with_type(
        store=store,
        properties=properties,
        type_name=execution_type_name,
        type_properties=execution_type_properties,
    )
    association = metadata_store_pb2.Association(
        execution_id=execution.id,
        context_id=context_id,
    )

    store.put_attributions_and_associations([], [association])
    return execution


# Traceback (TypeError)
Kubernetes Pod event:  MODIFIED file-passing-pipelines-mbzrz-3001099438 1555702
Traceback (most recent call last):
File "/kfp/metadata_writer/metadata_writer.py", line 183, in <module>
KFP_POD_NAME_EXECUTION_PROPERTY_NAME: pod_name,
File "/kfp/metadata_writer/metadata_helpers.py", line 280, in create_new_execution_in_existing_run_context
custom_properties=custom_properties,
TypeError: create_new_execution_in_existing_context() got an unexpected keyword argument 'custom_properties'

# Fixed code
def create_new_execution_in_existing_context(
    store,
    execution_type_name: str,
    context_id: int,
    properties: dict = None,
    execution_type_properties: dict = None,
    custom_properties: dict = None,
) -> metadata_store_pb2.Execution:
    execution = create_execution_with_type(
        store=store,
        properties=properties,
        custom_properties=custom_properties,
        type_name=execution_type_name,
        type_properties=execution_type_properties,
    )
    association = metadata_store_pb2.Association(
        execution_id=execution.id,
        context_id=context_id,
    )

    store.put_attributions_and_associations([], [association])
    return execution
# Buggy code
def create_new_artifact_event_and_attribution(
    store,
    execution_id: int,
    context_id: int,
    uri: str,
    type_name: str,
    event_type: metadata_store_pb2.Event.Type,
    properties: dict = None,
    artifact_type_properties: dict = None,
    artifact_name_path: metadata_store_pb2.Event.Path = None,
    milliseconds_since_epoch: int = None,
) -> metadata_store_pb2.Artifact:
    artifact = create_artifact_with_type(
        store=store,
        uri=uri,
        type_name=type_name,
        type_properties=artifact_type_properties,
        properties=properties,
    )
    event = metadata_store_pb2.Event(
        execution_id=execution_id,
        artifact_id=artifact.id,
        type=event_type,
        path=artifact_name_path,
        milliseconds_since_epoch=milliseconds_since_epoch,
    )
    store.put_events([event])

    attribution = metadata_store_pb2.Attribution(
        context_id=context_id,
        artifact_id=artifact.id,
    )
    store.put_attributions_and_associations([attribution], [])

    return artifact


# Traceback (TypeError)
Kubernetes Pod event:  MODIFIED file-passing-pipelines-mbzrz-3001099438 1555702
Traceback (most recent call last):
File "/kfp/metadata_writer/metadata_writer.py", line 183, in <module>
KFP_POD_NAME_EXECUTION_PROPERTY_NAME: pod_name,
File "/kfp/metadata_writer/metadata_helpers.py", line 280, in create_new_execution_in_existing_run_context
custom_properties=custom_properties,
TypeError: create_new_execution_in_existing_context() got an unexpected keyword argument 'custom_properties'

# Fixed code
def create_new_artifact_event_and_attribution(
    store,
    execution_id: int,
    context_id: int,
    uri: str,
    type_name: str,
    event_type: metadata_store_pb2.Event.Type,
    properties: dict = None,
    artifact_type_properties: dict = None,
    custom_properties: dict = None,
    artifact_name_path: metadata_store_pb2.Event.Path = None,
    milliseconds_since_epoch: int = None,
) -> metadata_store_pb2.Artifact:
    artifact = create_artifact_with_type(
        store=store,
        uri=uri,
        type_name=type_name,
        type_properties=artifact_type_properties,
        properties=properties,
        custom_properties=custom_properties,
    )
    event = metadata_store_pb2.Event(
        execution_id=execution_id,
        artifact_id=artifact.id,
        type=event_type,
        path=artifact_name_path,
        milliseconds_since_epoch=milliseconds_since_epoch,
    )
    store.put_events([event])

    attribution = metadata_store_pb2.Attribution(
        context_id=context_id,
        artifact_id=artifact.id,
    )
    store.put_attributions_and_associations([attribution], [])

    return artifact
# Buggy code
async def on_close(response: Response) -> None:
    response.elapsed = datetime.timedelta(seconds=await timer.async_elapsed())
    if hasattr(stream, "aclose"):
        await stream.aclose()


# Traceback (OSError)
.tox/py38/lib/python3.8/site-packages/httpx/_client.py:1846: in __aexit__
await self.response.aclose()
.tox/py38/lib/python3.8/site-packages/httpx/_models.py:1299: in aclose
await self._on_close(self)
.tox/py38/lib/python3.8/site-packages/httpx/_client.py:1513: in on_close
await stream.aclose()
.tox/py38/lib/python3.8/site-packages/httpcore/_async/connection_pool.py:69: in aclose
await self.stream.aclose()
.tox/py38/lib/python3.8/site-packages/httpcore/_bytestreams.py:78: in aclose
await self._aclose_func()
.tox/py38/lib/python3.8/site-packages/httpcore/_async/http11.py:192: in _response_closed
await self.aclose()
.tox/py38/lib/python3.8/site-packages/httpcore/_async/http11.py:202: in aclose
await self.socket.aclose()
.tox/py38/lib/python3.8/site-packages/httpcore/_backends/asyncio.py:198: in aclose
await self.stream_writer.wait_closed()  # type: ignore
/usr/lib64/python3.8/contextlib.py:131: in __exit__
self.gen.throw(type, value, traceback)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

map = {<class 'OSError'>: <class 'httpcore.CloseError'>}

@contextlib.contextmanager
def map_exceptions(map: Dict[Type[Exception], Type[Exception]]) -> Iterator[None]:
try:
yield
except Exception as exc:  # noqa: PIE786
for from_exc, to_exc in map.items():
if isinstance(exc, from_exc):
raise to_exc(exc) from None
E                   httpcore.CloseError: [Errno 104] Connection reset by peer

.tox/py38/lib/python3.8/site-packages/httpcore/_exceptions.py:12: CloseError
------------------------------------------------- Captured log call --------------------------------------------------
ERROR    asyncio:base_events.py:1707 Exception in callback _SelectorSocketTransport._call_connection_lost(None)
handle: <Handle _SelectorSocketTransport._call_connection_lost(None)>
Traceback (most recent call last):
File "/usr/lib64/python3.8/asyncio/events.py", line 81, in _run
self._context.run(self._callback, *self._args)
File "/usr/lib64/python3.8/asyncio/selector_events.py", line 970, in _call_connection_lost
super()._call_connection_lost(exc)
File "/usr/lib64/python3.8/asyncio/selector_events.py", line 730, in _call_connection_lost
self._sock.close()
File "/usr/lib64/python3.8/socket.py", line 500, in close
self._real_close()
File "/usr/lib64/python3.8/socket.py", line 494, in _real_close
_ss.close(self)
OSError: [Errno 9] Bad file descriptor

# Fixed code
async def on_close(response: Response) -> None:
    response.elapsed = datetime.timedelta(seconds=await timer.async_elapsed())
    if hasattr(stream, "aclose"):
        with map_exceptions(HTTPCORE_EXC_MAP, request=request):
            await stream.aclose()
# Buggy code
def raw(self) -> typing.List[typing.Tuple[bytes, bytes]]:
    """
    Returns a list of the raw header items, as byte pairs.
    May be mutated in-place.
    """
    return self._list


# Traceback (KeyError)
import httpx
client = httpx.Client()
request = client.build_request("GET", "https://google.com")
requests.headers
Headers({'host': 'google.com', 'user-agent': 'python-httpx/0.14.1', 'accept': '*/*', 'accept-encoding': 'gzip, deflate, br', 'connection': 'keep-alive'})
"host" in request.headers
False
request.headers.pop("host")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "D:\programs\anaconda3\lib\_collections_abc.py", line 801, in pop
del self[key]
File "E:\projects\pycharm\httpx\httpx\_models.py", line 536, in __delitem__
del self._dict[del_key]
KeyError: b'host'

# Fixed code
def raw(self) -> typing.List[typing.Tuple[bytes, bytes]]:
    """
    Returns a list of the raw header items, as byte pairs.
    """
    return list(self._list)
# Buggy code
def username(self) -> str:
    userinfo = self._uri_reference.userinfo or ""
    return userinfo.partition(":")[0]


# Traceback (httpx.exceptions.InvalidURL)
import httpx
httpx.URL("https://user@gmail.com:password@google.com")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/sethmlarson/Desktop/http3/httpx/models.py", line 112, in __init__
raise InvalidURL("No host included in URL.")
httpx.exceptions.InvalidURL: No host included in URL.

# Fixed code
def username(self) -> str:
    userinfo = self._uri_reference.userinfo or ""
    return unquote(userinfo.partition(":")[0])
# Buggy code
def password(self) -> str:
    userinfo = self._uri_reference.userinfo or ""
    return userinfo.partition(":")[2]


# Traceback (httpx.exceptions.InvalidURL)
import httpx
httpx.URL("https://user@gmail.com:password@google.com")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/sethmlarson/Desktop/http3/httpx/models.py", line 112, in __init__
raise InvalidURL("No host included in URL.")
httpx.exceptions.InvalidURL: No host included in URL.

# Fixed code
def password(self) -> str:
    userinfo = self._uri_reference.userinfo or ""
    return unquote(userinfo.partition(":")[2])
# Buggy code
def copy_with(self, **kwargs: typing.Any) -> "URL":
    if (
        "username" in kwargs
        or "password" in kwargs
        or "host" in kwargs
        or "port" in kwargs
    ):
        host = kwargs.pop("host", self.host)
        port = kwargs.pop("port", self.port)
        username = kwargs.pop("username", self.username)
        password = kwargs.pop("password", self.password)

        authority = host
        if port is not None:
            authority += f":{port}"
        if username:
            userpass = username
            if password:
                userpass += f":{password}"
            authority = f"{userpass}@{authority}"

        kwargs["authority"] = authority

    return URL(self._uri_reference.copy_with(**kwargs).unsplit())


# Traceback (httpx.exceptions.InvalidURL)
import httpx
httpx.URL("https://user@gmail.com:password@google.com")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/sethmlarson/Desktop/http3/httpx/models.py", line 112, in __init__
raise InvalidURL("No host included in URL.")
httpx.exceptions.InvalidURL: No host included in URL.

# Fixed code
def copy_with(self, **kwargs: typing.Any) -> "URL":
    if (
        "username" in kwargs
        or "password" in kwargs
        or "host" in kwargs
        or "port" in kwargs
    ):
        host = kwargs.pop("host", self.host)
        port = kwargs.pop("port", self.port)
        username = quote(kwargs.pop("username", self.username) or "")
        password = quote(kwargs.pop("password", self.password) or "")

        authority = host
        if port is not None:
            authority += f":{port}"
        if username:
            userpass = username
            if password:
                userpass += f":{password}"
            authority = f"{userpass}@{authority}"

        kwargs["authority"] = authority

    return URL(self._uri_reference.copy_with(**kwargs).unsplit())
# Buggy code
def join(self, url: URLTypes) -> "URL":
    """
    Return an absolute URL, using given this URL as the base.
    """
    if self.is_relative_url:
        return URL(url)

    # We drop any fragment portion, because RFC 3986 strictly
    # treats URLs with a fragment portion as not being absolute URLs.
    base_uri = self._uri_reference.copy_with(fragment=None)
    relative_url = URL(url)
    return URL(relative_url._uri_reference.resolve_with(base_uri).unsplit())


# Traceback (httpx.exceptions.InvalidURL)
import httpx
httpx.URL("https://user@gmail.com:password@google.com")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/sethmlarson/Desktop/http3/httpx/models.py", line 112, in __init__
raise InvalidURL("No host included in URL.")
httpx.exceptions.InvalidURL: No host included in URL.

# Fixed code
def join(self, url: URLTypes) -> "URL":
    """
    Return an absolute URL, using this URL as the base.
    """
    if self.is_relative_url:
        return URL(url)

    # We drop any fragment portion, because RFC 3986 strictly
    # treats URLs with a fragment portion as not being absolute URLs.
    base_uri = self._uri_reference.copy_with(fragment=None)
    relative_url = URL(url)
    return URL(relative_url._uri_reference.resolve_with(base_uri).unsplit())
# Buggy code
def __init__(self) -> None:
    self.decompressor = zlib.decompressobj(-zlib.MAX_WBITS)


# Traceback (zlib.error)
httpx.get('http://localhost:9999')
Traceback (most recent call last):
File "/Users/jamie/code/httpx/httpx/decoders.py", line 52, in decode
return self.decompressor.decompress(data)
zlib.error: Error -3 while decompressing data: invalid stored block lengths

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/jamie/code/httpx/httpx/api.py", line 170, in get
trust_env=trust_env,
File "/Users/jamie/code/httpx/httpx/api.py", line 96, in request
allow_redirects=allow_redirects,
File "/Users/jamie/code/httpx/httpx/client.py", line 568, in request
request, auth=auth, allow_redirects=allow_redirects, timeout=timeout,
File "/Users/jamie/code/httpx/httpx/client.py", line 593, in send
response.read()
File "/Users/jamie/code/httpx/httpx/models.py", line 900, in read
self._content = b"".join([part for part in self.iter_bytes()])
File "/Users/jamie/code/httpx/httpx/models.py", line 900, in <listcomp>
self._content = b"".join([part for part in self.iter_bytes()])
File "/Users/jamie/code/httpx/httpx/models.py", line 912, in iter_bytes
yield self.decoder.decode(chunk)
File "/Users/jamie/code/httpx/httpx/decoders.py", line 54, in decode
raise DecodingError from exc
httpx.exceptions.DecodingError

# Fixed code
def __init__(self) -> None:
    self.first_attempt = True
    self.decompressor = zlib.decompressobj()
# Buggy code
def decode(self, data: bytes) -> bytes:
    try:
        return self.decompressor.decompress(data)
    except zlib.error as exc:
        raise DecodingError from exc


# Traceback (zlib.error)
httpx.get('http://localhost:9999')
Traceback (most recent call last):
File "/Users/jamie/code/httpx/httpx/decoders.py", line 52, in decode
return self.decompressor.decompress(data)
zlib.error: Error -3 while decompressing data: invalid stored block lengths

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/jamie/code/httpx/httpx/api.py", line 170, in get
trust_env=trust_env,
File "/Users/jamie/code/httpx/httpx/api.py", line 96, in request
allow_redirects=allow_redirects,
File "/Users/jamie/code/httpx/httpx/client.py", line 568, in request
request, auth=auth, allow_redirects=allow_redirects, timeout=timeout,
File "/Users/jamie/code/httpx/httpx/client.py", line 593, in send
response.read()
File "/Users/jamie/code/httpx/httpx/models.py", line 900, in read
self._content = b"".join([part for part in self.iter_bytes()])
File "/Users/jamie/code/httpx/httpx/models.py", line 900, in <listcomp>
self._content = b"".join([part for part in self.iter_bytes()])
File "/Users/jamie/code/httpx/httpx/models.py", line 912, in iter_bytes
yield self.decoder.decode(chunk)
File "/Users/jamie/code/httpx/httpx/decoders.py", line 54, in decode
raise DecodingError from exc
httpx.exceptions.DecodingError

# Fixed code
def decode(self, data: bytes) -> bytes:
    was_first_attempt = self.first_attempt
    self.first_attempt = False
    try:
        return self.decompressor.decompress(data)
    except zlib.error as exc:
        if was_first_attempt:
            self.decompressor = zlib.decompressobj(-zlib.MAX_WBITS)
            return self.decode(data)
        raise DecodingError from exc
# Buggy code
async def close(self) -> None:
    await self.stream.aclose()


# Traceback (AssertionError)
Traceback (most recent call last):
File "/Users/primoz/PycharmProjects/orange3-imageanalytics/example.py", line 57, in <module>
asyncio.get_event_loop().run_until_complete(cl.embedd_batch())
File "/Users/primoz/miniconda3/lib/python3.7/asyncio/base_events.py", line 584, in run_until_complete
return future.result()
File "/Users/primoz/PycharmProjects/orange3-imageanalytics/example.py", line 19, in embedd_batch
embeddings = await asyncio.gather(*requests)
File "/Users/primoz/PycharmProjects/orange3-imageanalytics/example.py", line 43, in _send_to_server
emb = await self._send_request(client, im, url)
File "/Users/primoz/PycharmProjects/orange3-imageanalytics/example.py", line 50, in _send_request
response = await client.post(url, headers=headers, data=image)
File "/Users/primoz/venv/orange/lib/python3.7/site-packages/httpx/client.py", line 492, in post
trust_env=trust_env,
File "/Users/primoz/venv/orange/lib/python3.7/site-packages/httpx/client.py", line 634, in request
trust_env=trust_env,
File "/Users/primoz/venv/orange/lib/python3.7/site-packages/httpx/client.py", line 658, in send
trust_env=trust_env,
File "/Users/primoz/venv/orange/lib/python3.7/site-packages/httpx/client.py", line 273, in _get_response
return await get_response(request)
File "/Users/primoz/venv/orange/lib/python3.7/site-packages/httpx/middleware/redirect.py", line 31, in __call__
response = await get_response(request)
File "/Users/primoz/venv/orange/lib/python3.7/site-packages/httpx/client.py", line 228, in get_response
request, verify=verify, cert=cert, timeout=timeout
File "/Users/primoz/venv/orange/lib/python3.7/site-packages/httpx/dispatch/connection_pool.py", line 126, in send
raise exc
File "/Users/primoz/venv/orange/lib/python3.7/site-packages/httpx/dispatch/connection_pool.py", line 121, in send
request, verify=verify, cert=cert, timeout=timeout
File "/Users/primoz/venv/orange/lib/python3.7/site-packages/httpx/dispatch/connection.py", line 62, in send
response = await self.h2_connection.send(request, timeout=timeout)
File "/Users/primoz/venv/orange/lib/python3.7/site-packages/httpx/dispatch/http2.py", line 49, in send
stream_id = await self.send_headers(request, timeout)
File "/Users/primoz/venv/orange/lib/python3.7/site-packages/httpx/dispatch/http2.py", line 121, in send_headers
await self.stream.write(data_to_send, timeout)
File "/Users/primoz/venv/orange/lib/python3.7/site-packages/httpx/concurrency/asyncio.py", line 149, in write
self.stream_writer.drain(), timeout.write_timeout
File "/Users/primoz/miniconda3/lib/python3.7/asyncio/tasks.py", line 416, in wait_for
return fut.result()
File "/Users/primoz/miniconda3/lib/python3.7/asyncio/streams.py", line 348, in drain
await self._protocol._drain_helper()
File "/Users/primoz/miniconda3/lib/python3.7/asyncio/streams.py", line 206, in _drain_helper
assert waiter is None or waiter.cancelled()
AssertionError

# Fixed code
async def close(self) -> None:
    async with self.write_lock:
        await self.stream.aclose()
# Buggy code
def __init__(self) -> None:
    self._event = trio.Event()


# Traceback (AssertionError)
Traceback (most recent call last):
File "/Users/primoz/PycharmProjects/orange3-imageanalytics/example.py", line 57, in <module>
asyncio.get_event_loop().run_until_complete(cl.embedd_batch())
File "/Users/primoz/miniconda3/lib/python3.7/asyncio/base_events.py", line 584, in run_until_complete
return future.result()
File "/Users/primoz/PycharmProjects/orange3-imageanalytics/example.py", line 19, in embedd_batch
embeddings = await asyncio.gather(*requests)
File "/Users/primoz/PycharmProjects/orange3-imageanalytics/example.py", line 43, in _send_to_server
emb = await self._send_request(client, im, url)
File "/Users/primoz/PycharmProjects/orange3-imageanalytics/example.py", line 50, in _send_request
response = await client.post(url, headers=headers, data=image)
File "/Users/primoz/venv/orange/lib/python3.7/site-packages/httpx/client.py", line 492, in post
trust_env=trust_env,
File "/Users/primoz/venv/orange/lib/python3.7/site-packages/httpx/client.py", line 634, in request
trust_env=trust_env,
File "/Users/primoz/venv/orange/lib/python3.7/site-packages/httpx/client.py", line 658, in send
trust_env=trust_env,
File "/Users/primoz/venv/orange/lib/python3.7/site-packages/httpx/client.py", line 273, in _get_response
return await get_response(request)
File "/Users/primoz/venv/orange/lib/python3.7/site-packages/httpx/middleware/redirect.py", line 31, in __call__
response = await get_response(request)
File "/Users/primoz/venv/orange/lib/python3.7/site-packages/httpx/client.py", line 228, in get_response
request, verify=verify, cert=cert, timeout=timeout
File "/Users/primoz/venv/orange/lib/python3.7/site-packages/httpx/dispatch/connection_pool.py", line 126, in send
raise exc
File "/Users/primoz/venv/orange/lib/python3.7/site-packages/httpx/dispatch/connection_pool.py", line 121, in send
request, verify=verify, cert=cert, timeout=timeout
File "/Users/primoz/venv/orange/lib/python3.7/site-packages/httpx/dispatch/connection.py", line 62, in send
response = await self.h2_connection.send(request, timeout=timeout)
File "/Users/primoz/venv/orange/lib/python3.7/site-packages/httpx/dispatch/http2.py", line 49, in send
stream_id = await self.send_headers(request, timeout)
File "/Users/primoz/venv/orange/lib/python3.7/site-packages/httpx/dispatch/http2.py", line 121, in send_headers
await self.stream.write(data_to_send, timeout)
File "/Users/primoz/venv/orange/lib/python3.7/site-packages/httpx/concurrency/asyncio.py", line 149, in write
self.stream_writer.drain(), timeout.write_timeout
File "/Users/primoz/miniconda3/lib/python3.7/asyncio/tasks.py", line 416, in wait_for
return fut.result()
File "/Users/primoz/miniconda3/lib/python3.7/asyncio/streams.py", line 348, in drain
await self._protocol._drain_helper()
File "/Users/primoz/miniconda3/lib/python3.7/asyncio/streams.py", line 206, in _drain_helper
assert waiter is None or waiter.cancelled()
AssertionError

# Fixed code
def __init__(self) -> None:
    self._lock = trio.Lock()